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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: implement daily user presence and remote usage tracking in web-ws relay
0xken155f18be32c5d2
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex ebd3cb5f3..e15ab98c6 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -419,3 +419,40 @@ model AnalyticsMachineState {@@index([userId])@@map("analytics_machine_states")}++/// Presence/remote-usage tracking — separate from the Analytics family above (not opt-in, not+/// collector-reported; derived directly from the web-ws relay in src/lib/webWs.ts).++/// Per-day record of whether a user's desktop app was connected to the web-ws relay. One row per+/// (user, UTC day). A connection spanning midnight produces a row for each day it touches.+model UserDailyPresence {+ id String @id @default(auto()) @map("_id") @db.ObjectId+ userId String+ dayUtc DateTime+ connections Int @default(0)+ firstSeenAt DateTime+ lastSeenAt DateTime+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([userId, dayUtc])+ @@map("user_daily_presence")+}++/// Per-day record of whether a user actually established a remote p2p connection to stream a+/// terminal (signaled by a p2p_offer frame passing through the web-ws relay), scoped to the machine.+model UserDailyRemoteUsage {+ id String @id @default(auto()) @map("_id") @db.ObjectId+ userId String+ machineId String+ dayUtc DateTime+ sessions Int @default(0)+ firstSeenAt DateTime+ lastSeenAt DateTime+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([userId, machineId, dayUtc])+ @@index([userId, dayUtc])+ @@map("user_daily_remote_usage")+}diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.tsnew file mode 100644index 000000000..8fc961e01--- /dev/null+++ b/backend/src/lib/dailyTracking.ts@@ -0,0 +1,60 @@+/**+ * 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.+ *+ * Both 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+ * open connection finds the day has changed (`isNewConnection: false`, just touches `lastSeenAt`).+ */+export async function touchUserOnlineDay(+ userId: string,+ now: Date,+ opts: { isNewConnection: boolean },+): Promise<void> {+ const dayUtc = utcDayStart(now)+ const touched = await prisma.userDailyPresence.updateMany({+ where: { userId, dayUtc },+ data: {+ 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)+ }+}++/**+ * Record that a user actually established a remote p2p connection (a `p2p_offer` frame passed+ * through the relay) to `machineId` on the UTC day containing `now`.+ */+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 } },+ })+ 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/webWs.ts b/backend/src/lib/webWs.tsindex 3ec6ceb8a..fb33e588a 100644--- a/backend/src/lib/webWs.ts+++ b/backend/src/lib/webWs.ts@@ -49,6 +49,8 @@ import {P2pSignalRateGuard,terminalP2pPolicy,} from './p2pSignaling.js'+import { touchUserOnlineDay, recordRemoteUsage } from './dailyTracking.js'+import { utcDayKey } from '../types/analytics.js'const wss = new WebSocketServer({noServer: true,@@ -119,6 +121,20 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {logger.info('web user connected', { userId: user.sub })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 => {+ const now = new Date()+ const dayKey = utcDayKey(now)+ if (dayKey === lastPresenceDayKey) return+ lastPresenceDayKey = dayKey+ touchUserOnlineDay(user.sub, now, { isNewConnection: false })+ .catch((err) => logger.warn('presence tracking failed', { userId: user.sub, error: String(err) }))+ }+// 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// dead. This used to be a second heartbeat loop here, carefully disabled while attached so the two@@ -198,7 +214,10 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {if (closed) { deviceStatusUnsub(); deviceStatusUnsub = null; return }}if (!deviceSeedTimer) {- deviceSeedTimer = setInterval(() => { void seedDeviceStatuses().catch(() => { /* ignore */ }) }, DEVICE_RESEED_MS)+ deviceSeedTimer = setInterval(() => {+ void seedDeviceStatuses().catch(() => { /* ignore */ })+ touchPresenceIfDayChanged()+ }, DEVICE_RESEED_MS)}await seedDeviceStatuses()}@@ -351,6 +370,12 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {try { ws.send(JSON.stringify({ type: 'p2p_transport_error', payload: { code: 'P2P_SIGNAL_REJECTED' } })) } catch { /* ignore */ }return}+ // Remote-usage signal: a p2p_offer actually starts a new p2p session (vs. the ICE/abort+ // frames that follow one), so it's the one point that means "used remote to stream terminal".+ if (type === 'p2p_offer' && currentBinding) {+ recordRemoteUsage(user.sub, currentBinding.machineId, new Date())+ .catch((err) => logger.warn('remote usage tracking failed', { userId: user.sub, machineId: currentBinding?.machineId, error: String(err) }))+ }}if (type === 'machine_select') {const machineId = (frame.payload as { machineId?: unknown } | undefined)?.machineId@@ -439,6 +464,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {if (deviceStatusUnsub) { deviceStatusUnsub(); deviceStatusUnsub = null }if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }if (deviceE2eePairUnsub) { deviceE2eePairUnsub(); deviceE2eePairUnsub = null }+ touchPresenceIfDayChanged()logger.info('web user disconnected', { userId: user.sub, machineId: currentAgentId ?? undefined })}ws.on('close', cleanup)