Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: implement daily device presence tracking and refactor upsert logic for web and device WebSocket connections.

0xken159bd8cf166731
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index e15ab98c6..2c3a023b0 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -456,3 +456,22 @@ model UserDailyRemoteUsage {
@@index([userId, dayUtc])
@@map("user_daily_remote_usage")
}
+
+/// Per-day record of whether a user's device was connected to the device-ws relay
+/// (src/lib/deviceWs.ts). One row per (user, device, UTC day); a connection spanning
+/// midnight produces a row for each day it touches.
+model UserDailyDevicePresence {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ userId String
+ deviceId String
+ dayUtc DateTime
+ connections Int @default(0)
+ firstSeenAt DateTime
+ lastSeenAt DateTime
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([userId, deviceId, dayUtc])
+ @@index([userId, dayUtc])
+ @@map("user_daily_device_presence")
+}
diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.ts
index 8fc961e01..fbb893e7a 100644
--- a/backend/src/lib/dailyTracking.ts
+++ b/backend/src/lib/dailyTracking.ts
@@ -1,22 +1,21 @@
/**
- * Presence / remote-usage daily tracking — write path for `UserDailyPresence` and
- * `UserDailyRemoteUsage` (prisma/schema.prisma). Separate model family and separate module from
- * the opt-in `Analytics*` telemetry in analyticsIngest.ts: these two signals are derived directly
- * from the web-ws relay (src/lib/webWs.ts), not from a collector upload.
+ * Presence / remote-usage daily tracking — write path for `UserDailyPresence`,
+ * `UserDailyRemoteUsage` and `UserDailyDevicePresence` (prisma/schema.prisma). Separate model
+ * family and separate module from the opt-in `Analytics*` telemetry in analyticsIngest.ts: these
+ * signals are derived directly from the web-ws/device-ws relays (src/lib/webWs.ts,
+ * src/lib/deviceWs.ts), not from a collector upload.
*
- * Both entry points are meant to be called fire-and-forget from the hot path (connection open,
+ * Unlike analyticsIngest.ts, none of these rows need last-write-wins ordering (there's no
+ * client-supplied revision to defend against), so each touch is a plain atomic `upsert` on the
+ * day's unique key — no separate create-then-swallow-P2002 step that could drop a concurrent
+ * write's `lastSeenAt`/counter increment.
+ *
+ * All entry points are meant to be called fire-and-forget from the hot path (connection open,
* periodic re-seed, p2p_offer) — callers must not await them inline.
*/
-import { Prisma } from '@prisma/client'
import { prisma } from './prisma.js'
import { utcDayStart } from '../types/analytics.js'
-/** A unique-constraint violation here means a concurrent write already created today's row. */
-function swallowUniqueViolation(err: unknown): void {
- if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') return
- throw err
-}
-
/**
* Mark a user online for the UTC day containing `now`. Call once on connect
* (`isNewConnection: true`, bumps `connections`) and again whenever a day-boundary check on an
@@ -28,18 +27,14 @@ export async function touchUserOnlineDay(
opts: { isNewConnection: boolean },
): Promise<void> {
const dayUtc = utcDayStart(now)
- const touched = await prisma.userDailyPresence.updateMany({
- where: { userId, dayUtc },
- data: {
+ await prisma.userDailyPresence.upsert({
+ where: { userId_dayUtc: { userId, dayUtc } },
+ create: { userId, dayUtc, connections: 1, firstSeenAt: now, lastSeenAt: now },
+ update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
},
})
- if (touched.count === 0) {
- await prisma.userDailyPresence
- .create({ data: { userId, dayUtc, connections: 1, firstSeenAt: now, lastSeenAt: now } })
- .catch(swallowUniqueViolation)
- }
}
/**
@@ -48,13 +43,30 @@ export async function touchUserOnlineDay(
*/
export async function recordRemoteUsage(userId: string, machineId: string, now: Date): Promise<void> {
const dayUtc = utcDayStart(now)
- const touched = await prisma.userDailyRemoteUsage.updateMany({
- where: { userId, machineId, dayUtc },
- data: { lastSeenAt: now, sessions: { increment: 1 } },
+ await prisma.userDailyRemoteUsage.upsert({
+ where: { userId_machineId_dayUtc: { userId, machineId, dayUtc } },
+ create: { userId, machineId, dayUtc, sessions: 1, firstSeenAt: now, lastSeenAt: now },
+ update: { lastSeenAt: now, sessions: { increment: 1 } },
+ })
+}
+
+/**
+ * Mark a user's device online for the UTC day containing `now`, mirroring `touchUserOnlineDay`
+ * for the device-ws relay (src/lib/deviceWs.ts) instead of web-ws.
+ */
+export async function touchDeviceOnlineDay(
+ userId: string,
+ deviceId: string,
+ now: Date,
+ opts: { isNewConnection: boolean },
+): Promise<void> {
+ const dayUtc = utcDayStart(now)
+ await prisma.userDailyDevicePresence.upsert({
+ where: { userId_deviceId_dayUtc: { userId, deviceId, dayUtc } },
+ create: { userId, deviceId, dayUtc, connections: 1, firstSeenAt: now, lastSeenAt: now },
+ update: {
+ lastSeenAt: now,
+ ...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
+ },
})
- if (touched.count === 0) {
- await prisma.userDailyRemoteUsage
- .create({ data: { userId, machineId, dayUtc, sessions: 1, firstSeenAt: now, lastSeenAt: now } })
- .catch(swallowUniqueViolation)
- }
}
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index e3d876511..a820d24a5 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -25,6 +25,8 @@ import type { Frame } from './tunnel.js'
import { transcribe, MAX_PCM, normalizeLang } from './stt.js'
import { prisma } from './prisma.js'
import { deviceService } from '../services/index.js'
+import { touchDeviceOnlineDay } from './dailyTracking.js'
+import { utcDayKey } from '../types/analytics.js'
import { agentLimit, recordCreatedAgent } from './agentTracker.js'
import { env } from '../config/env.js'
import { logger } from '../utils/logger.js'
@@ -451,13 +453,31 @@ function relay(device: WebSocket, opts: RelayOpts): void {
let presenceDeviceId: string | null = null
let controlUnsub: (() => void) | null = null
let machineListUnsub: (() => void) | null = null
+ // Daily device presence: mark today online on first presence start for this connection, and
+ // re-check on the existing 15s refresh tick / on close so a connection spanning UTC midnight
+ // gets counted for the new day too (mirrors webWs.ts's touchUserOnlineDay/touchPresence). The
+ // guard only advances on a SUCCESSFUL write, so a transient DB failure gets retried on the next
+ // tick instead of being silently skipped for the rest of the day.
+ let lastDevicePresenceDayKey: string | null = null
+ const touchDevicePresence = (id: string, isNewConnection: boolean): void => {
+ const now = new Date()
+ const dayKey = utcDayKey(now)
+ if (!isNewConnection && dayKey === lastDevicePresenceDayKey) return
+ touchDeviceOnlineDay(userId, id, now, { isNewConnection })
+ .then(() => { lastDevicePresenceDayKey = dayKey })
+ .catch((err) => logger.warn('device presence tracking failed', { userId, deviceId: id, error: String(err) }))
+ }
const startPresence = (id: string): void => {
if (closed || presenceDeviceId === id) return
presenceDeviceId = id
void setDevicePresence(id, connToken)
void publishDeviceStatus(userId, { deviceId: id, online: true })
+ touchDevicePresence(id, true)
if (presenceTimer) clearInterval(presenceTimer)
- presenceTimer = setInterval(() => { void setDevicePresence(id, connToken) }, DEVICE_PRESENCE_REFRESH_MS)
+ presenceTimer = setInterval(() => {
+ void setDevicePresence(id, connToken)
+ touchDevicePresence(id, false)
+ }, DEVICE_PRESENCE_REFRESH_MS)
// Control channel: a revoke must reach the device even when it's parked on the machine PICKER
// (no hub attach → the machine-targeted pushDeviceRevoked can't reach it). Deliver the frame the
// firmware already handles (wipe token + reboot to pair screen), then close the socket so a
@@ -821,6 +841,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {
if (gone) void publishDeviceStatus(userId, { deviceId: id, online: false, lastSeenAt: seenAt.toISOString() })
})
void prisma.deviceBinding.update({ where: { deviceId: id }, data: { lastSeenAt: seenAt } }).catch(() => { /* best effort */ })
+ touchDevicePresence(id, false)
}
for (const [, unsub] of statusSubs) unsub()
statusSubs.clear()
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index fb33e588a..140bff2e5 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -122,18 +122,19 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
try { ws.send(JSON.stringify({ type: 'connected', payload: { userId: user.sub } })) } catch { /* ignore */ }
// Daily presence: mark today online now, and re-check on the existing 30s re-seed tick / on
- // disconnect so a connection spanning UTC midnight gets counted for the new day too.
- let lastPresenceDayKey: string | null = utcDayKey(new Date())
- touchUserOnlineDay(user.sub, new Date(), { isNewConnection: true })
- .catch((err) => logger.warn('presence tracking failed', { userId: user.sub, error: String(err) }))
- const touchPresenceIfDayChanged = (): void => {
+ // disconnect so a connection spanning UTC midnight gets counted for the new day too. The guard
+ // only advances on a SUCCESSFUL write, so a transient DB failure gets retried on the next tick
+ // instead of being silently skipped for the rest of the day.
+ let lastPresenceDayKey: string | null = null
+ const touchPresence = (isNewConnection: boolean): void => {
const now = new Date()
const dayKey = utcDayKey(now)
- if (dayKey === lastPresenceDayKey) return
- lastPresenceDayKey = dayKey
- touchUserOnlineDay(user.sub, now, { isNewConnection: false })
+ if (!isNewConnection && dayKey === lastPresenceDayKey) return
+ touchUserOnlineDay(user.sub, now, { isNewConnection })
+ .then(() => { lastPresenceDayKey = dayKey })
.catch((err) => logger.warn('presence tracking failed', { userId: user.sub, error: String(err) }))
}
+ touchPresence(true)
// An unattached socket (user parked on the Machines page, no agent selected) holds no hub client, so a
// registry-driven sweep can't see it — it would be killed by LB idle timeouts, or never reaped when
@@ -216,7 +217,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
if (!deviceSeedTimer) {
deviceSeedTimer = setInterval(() => {
void seedDeviceStatuses().catch(() => { /* ignore */ })
- touchPresenceIfDayChanged()
+ touchPresence(false)
}, DEVICE_RESEED_MS)
}
await seedDeviceStatuses()
@@ -464,7 +465,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
if (deviceStatusUnsub) { deviceStatusUnsub(); deviceStatusUnsub = null }
if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }
if (deviceE2eePairUnsub) { deviceE2eePairUnsub(); deviceE2eePairUnsub = null }
- touchPresenceIfDayChanged()
+ touchPresence(false)
logger.info('web user disconnected', { userId: user.sub, machineId: currentAgentId ?? undefined })
}
ws.on('close', cleanup)