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
fix(backend): each machine keeps its last-seen time again (#1951)
0xken15371590487fdf
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex bcc3713d2..78c8bd0ce 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -260,6 +260,11 @@ model Machine {// overwrite-every-connect rule as `hostname`/`clientVersion`. Null when the upgrade did not come// through Cloudflare (local dev) or the row predates the field.countryCode String?+ // When this machine's daemon was last seen on /api/adapter-ws: stamped on connect, on close, and at most every+ // MACHINE_PRESENCE_WRITE_MS while the socket stays open (adapterWs.ts), so it lags real liveness by at most+ // that. One overwritten value, never a history. Redis `machine:{id}:mgr` is still "online right now"; this+ // answers "since when is it offline". Null on rows that have not connected since the field shipped.+ lastSeenAt DateTime?// Billing lifecycle for newly-created campaign machines. Missing on old rows means legacy-active.// Grandfathered Remote machines are `not_required`; new paid Remote and managed machines move pending -> active only after// checkout verification. A cancelled paid subscription stays active until its period end, thendiff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex e79d125f5..7d02e5e6c 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -87,10 +87,10 @@ const APP_STATES = new Set(['open', 'closed', 'missing'])// semver-ish token (or longer than 64 chars) is dropped rather than stored.const CLIENT_VERSION_RE = /^[A-Za-z0-9._+-]{1,64}$/-// Daily presence (`machine_daily_presence`): how often an OPEN adapter socket refreshes its row's-// `lastSeenAt`. Rides the node role's existing 15s heartbeat (plus every app ping) rather than a-// timer of its own — this is just the floor between two Mongo writes, so a machine that is up all-// day costs ~300 upserts, not ~6000. Connect and close always write regardless.+// How often an OPEN adapter socket refreshes `machines.lastSeenAt`. Rides the node role's existing 15s+// heartbeat (plus every app ping) rather than a timer of its own — this is just the floor between two+// Mongo writes, so a machine that is up all day costs ~300 updates, not ~6000. Connect and close always+// write regardless.const MACHINE_PRESENCE_WRITE_MS = 5 * 60_000// Daily presence of the PERSON (`user_daily_presence`): the daemon reports its own loopback clients —@@ -308,8 +308,8 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c.catch(() => null))?.gridName ?? nullsend({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: currentName?.trim() || seededName, gridName } } })- // Daily presence row for the machine, mirroring the user/device variants in webWs/deviceWs. The- // guard only advances on a SUCCESSFUL write, so a transient DB failure is retried on the next+ // The machine's last-seen stamp (plus the fleet's connect total), mirroring the user/device variants in+ // webWs/deviceWs. The guard only advances on a SUCCESSFUL write, so a transient DB failure is retried on the next// heartbeat instead of being silently skipped until the interval elapses again. Heartbeats also// skip while a write is still in flight: `onHeartbeat` fires from two 15s sources (node role// interval + app ping), and before the connect write lands `presenceWriteDue` would say "due" —diff --git a/backend/src/lib/dailyTracking.test.ts b/backend/src/lib/dailyTracking.test.tsindex 2485bcf1c..3bdb23fe1 100644--- a/backend/src/lib/dailyTracking.test.ts+++ b/backend/src/lib/dailyTracking.test.ts@@ -1,10 +1,15 @@import { beforeEach, describe, expect, it, vi } from 'vitest'const record = vi.hoisted(() => vi.fn())const mark = vi.hoisted(() => vi.fn())+const machineUpdate = vi.hoisted(() => vi.fn())vi.mock('./productUsage.js', () => ({ recordRelayUsage: record, markActivity: mark }))+vi.mock('./prisma.js', () => ({ prisma: { machine: { update: machineUpdate } } }))import { CLIENT_SURFACES, TUI_SURFACES, mobileOpenMetrics, presenceTracker, presenceWriteDue, recordRemoteUsage, recordTurnStarted, touchClientOnlineDay, touchDeviceOnlineDay, touchMachineOnlineDay, touchUserOnlineDay } from './dailyTracking.js'-beforeEach(() => { record.mockReset(); record.mockResolvedValue(undefined); mark.mockReset(); mark.mockResolvedValue(undefined) })+beforeEach(() => {+ record.mockReset(); record.mockResolvedValue(undefined); mark.mockReset(); mark.mockResolvedValue(undefined)+ machineUpdate.mockReset(); machineUpdate.mockResolvedValue({})+})it('forwards only the choice identity and a fixed metric, never device, agent or location', async () => {const now = new Date('2026-10-13T12:00:00Z')await touchUserOnlineDay('account', 'PRIVATE_MACHINE', now, { isNewConnection: true })@@ -73,6 +78,30 @@ it('idle heartbeats add no relay totals but keep the person active', async () =>expect(mark.mock.calls).toEqual([['a', now, { surface: 'desktop' }], ['a', now, { surface: 'tui' }]])})+describe('a machine\'s last-seen time', () => {+ const now = new Date('2026-10-28T09:00:00Z')++ it('is stamped on the machine\'s own record on a connect and on every write after it', async () => {+ await touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: true, countryCode: 'VN' })+ await touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: false })+ expect(machineUpdate.mock.calls).toEqual([+ [{ where: { machineId: 'machine-1' }, data: { lastSeenAt: now } }],+ [{ where: { machineId: 'machine-1' }, data: { lastSeenAt: now } }],+ ])+ })++ it('rejects when the stamp fails, so the socket\'s next heartbeat tries again', async () => {+ machineUpdate.mockRejectedValue(new Error('mongo down'))+ await expect(touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: false })).rejects.toThrow('mongo down')+ })++ it('is stamped even when the connect total fails', async () => {+ record.mockRejectedValue(new Error('totals down'))+ await expect(touchMachineOnlineDay('account', 'machine-1', now, { isNewConnection: true })).rejects.toThrow('totals down')+ expect(machineUpdate).toHaveBeenCalledWith({ where: { machineId: 'machine-1' }, data: { lastSeenAt: now } })+ })+})+it('marks the person, not the machine, agent or device', async () => {const now = new Date('2026-10-13T12:00:00Z')await touchUserOnlineDay('account', 'PRIVATE_MACHINE', now, { isNewConnection: true })diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.tsindex ba210e487..7ebf3bb3d 100644--- a/backend/src/lib/dailyTracking.ts+++ b/backend/src/lib/dailyTracking.ts@@ -1,11 +1,13 @@/** Relay signals contribute daily fleet totals and, while sharing is on, a person's 10-day activity* mark (lib/productUsage.ts markActivity). Operational live presence stays in Redis.- * No machine, agent or device history is written here. Older row types remain readable- * during their bounded expiry window; their historical metrics must not be mixed with these totals.+ * No machine, agent or device history is written here: the one machine fact kept is the overwritten+ * `machines.lastSeenAt`. Older row types remain readable during their bounded expiry window; their+ * historical metrics must not be mixed with these totals.*/import { utcDayKey } from '../types/analytics.js'import { releaseBucket } from '../types/productHealthContract.js'import { markActivity, recordRelayUsage, type RelayUsageMetric } from './productUsage.js'+import { prisma } from './prisma.js'export interface PresenceTouchOpts { isNewConnection: boolean; countryCode?: string }@@ -20,8 +22,14 @@ export async function recordRemoteUsage(userId: string, _machineId: string, now:export async function touchDeviceOnlineDay(userId: string, _deviceId: string, now: Date, opts: PresenceTouchOpts): Promise<void> {if (opts.isNewConnection) await recordRelayUsage(userId, now, 'relay_device_connections')}-export async function touchMachineOnlineDay(userId: string, _machineId: string, now: Date, opts: PresenceTouchOpts): Promise<void> {- if (opts.isNewConnection) await recordRelayUsage(userId, now, 'relay_machine_connections')+/** Stamps the machine's own `lastSeenAt` on every call — the caller floors heartbeats — and counts a connect.+ * Both writes start together, so a failed total never costs the stamp; either failure rejects, so the+ * caller's floor does not advance and its next heartbeat retries. */+export async function touchMachineOnlineDay(userId: string, machineId: string, now: Date, opts: PresenceTouchOpts): Promise<void> {+ await Promise.all([+ prisma.machine.update({ where: { machineId }, data: { lastSeenAt: now } }),+ opts.isNewConnection ? recordRelayUsage(userId, now, 'relay_machine_connections') : undefined,+ ])}export async function recordTurnStarted(userId: string, _machineId: string, _agentId: string, now: Date): Promise<void> {void markActivity(userId, now, { worked: true }).catch(() => {})