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: desktop app presence pings relayed via CLI daemon

0xken1533734116cf22
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index e074cec44..6c4649508 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -424,8 +424,12 @@ model AnalyticsMachineState {
/// collector-reported; derived directly from the relays: web-ws in src/lib/webWs.ts, device-ws in
/// src/lib/deviceWs.ts, adapter-ws in src/lib/adapterWs.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.
+/// Per-day record of whether a user had the desktop app open. One row per (user, UTC day). The
+/// source is the app's own `app_presence` ping to its local `harness` daemon, which the daemon
+/// forwards over adapter-ws (src/lib/adapterWs.ts) — NOT the web-ws upgrade, which the app never
+/// performs itself (only the daemon does, per foreign machine it relays) and which therefore missed
+/// every single-machine user. `connections` = times the app opened its local socket that day; a
+/// session spanning midnight produces a row for each day it touches with `connections: 0`.
model UserDailyPresence {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 70b5b9041..2d33c8c67 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -25,7 +25,7 @@ import {
import { trackSocketLiveness } from './hub.js'
import { guardedSend, guardedSendJson } from './wsSend.js'
import { attachNodeRole, PRESENCE_TTL_SEC } from './nodeRole.js'
-import { presenceWriteDue, recordTurnStarted, touchMachineOnlineDay, type PresenceWriteState } from './dailyTracking.js'
+import { presenceWriteDue, recordTurnStarted, touchMachineOnlineDay, touchUserOnlineDay, type PresenceWriteState } from './dailyTracking.js'
import { recordCreatedAgent, recordDeletedAgent } from './agentTracker.js'
import type { Frame } from './tunnel.js'
import { logger } from '../utils/logger.js'
@@ -82,6 +82,20 @@ const CLIENT_VERSION_RE = /^[A-Za-z0-9._+-]{1,64}$/
// day costs ~300 upserts, 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 desktop app pings its local daemon every
+// 30s while its loopback socket is up, the daemon forwards at most one `app_presence` up-frame a
+// minute, and this is the floor between two Mongo writes for the `ping` kind. `open` (the app just
+// connected its local socket) always writes — it is what `connections` counts. The web-ws upgrade
+// used to be the source, but the desktop app never dials web-ws directly (only the daemon does, and
+// only to relay a foreign machine), so a single-machine user was invisible there.
+const USER_PRESENCE_WRITE_MS = 5 * 60_000
+// `open` is not floored by the interval above (each one IS a session), but it is floored on its own:
+// the window reconnects its local socket a few times a minute at worst during a daemon restart, and
+// an adapter sending more than that is looping or lying — either way not a session per frame, and
+// not a Mongo upsert per frame.
+const USER_PRESENCE_OPEN_MS = 10_000
+const APP_PRESENCE_KINDS = new Set(['open', 'ping'])
+
// `turn_started` tap (agent/machine daily presence). `agentId` is a plain token the CLI derives from
// its registry (a UUID, or the engine's own session id as fallback), so it is bounded and
// character-restricted before it becomes a Mongo index key — an oversized or exotic value would
@@ -258,6 +272,25 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
.catch((err) => logger.warn('machine presence tracking failed', { machineId, kind, error: String(err) }))
.finally(() => { machinePresenceInFlight = false })
}
+ // Same shape for the person behind the app: `open` bypasses the interval the way `connect` does
+ // above, `ping` is rate-floored. `userId` is the machine's owner — the only person a desktop app
+ // on this computer can be signed in as.
+ const lastUserPresence: PresenceWriteState = { dayKey: null, wroteAt: 0 }
+ let userPresenceInFlight = false
+ let lastUserOpenAt = 0
+ const touchUserPresence = (kind: 'open' | 'ping'): void => {
+ const now = new Date()
+ if (kind === 'ping' && (userPresenceInFlight || !presenceWriteDue(lastUserPresence, now, USER_PRESENCE_WRITE_MS))) return
+ if (kind === 'open') {
+ if (now.getTime() - lastUserOpenAt < USER_PRESENCE_OPEN_MS) return
+ lastUserOpenAt = now.getTime()
+ }
+ userPresenceInFlight = true
+ touchUserOnlineDay(userId, now, { isNewConnection: kind === 'open' })
+ .then(() => { lastUserPresence.dayKey = utcDayKey(now); lastUserPresence.wroteAt = now.getTime() })
+ .catch((err) => logger.warn('user presence tracking failed', { machineId, userId, kind, error: String(err) }))
+ .finally(() => { userPresenceInFlight = false })
+ }
// The node role — down subscription, presence, `__clients` resync, node_status — is shared with
// every other backer of a machine and lives in nodeRole.ts. Only the delivery and teardown are
@@ -375,6 +408,15 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
})
return
}
+ // The desktop app's own presence ping, relayed by the daemon (cli localWsServer → backendSocket
+ // sendAppPresence). Bookkeeping only — absorbed here, never published: no client has any use for
+ // it and an unknown frame type must not reach the firmware.
+ if (app.type === 'app_presence') {
+ const kind = (app.payload as { kind?: unknown } | undefined)?.kind
+ if (typeof kind !== 'string' || !APP_PRESENCE_KINDS.has(kind)) return
+ touchUserPresence(kind as 'open' | 'ping')
+ return
+ }
// Hub tap (mirrors managerWs): keep `machine_agents` in sync from the adapter's agent
// lifecycle frames. Needed so the device voice path's agent-ownership check
// (deviceWs: `machineAgent.findFirst`) recognizes remote tmux sessions.
diff --git a/backend/src/lib/dailyTracking.test.ts b/backend/src/lib/dailyTracking.test.ts
index 1fb334ae4..533ab1eb4 100644
--- a/backend/src/lib/dailyTracking.test.ts
+++ b/backend/src/lib/dailyTracking.test.ts
@@ -1,20 +1,51 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const db = vi.hoisted(() => ({
+ userPresenceUpsert: vi.fn(),
machinePresenceUpsert: vi.fn(),
agentPresenceUpsert: vi.fn(),
}))
vi.mock('./prisma.js', () => ({
prisma: {
+ userDailyPresence: { upsert: db.userPresenceUpsert },
machineDailyPresence: { upsert: db.machinePresenceUpsert },
agentDailyPresence: { upsert: db.agentPresenceUpsert },
},
}))
-import { presenceWriteDue, recordTurnStarted, touchMachineOnlineDay } from './dailyTracking.js'
+import { presenceWriteDue, recordTurnStarted, touchMachineOnlineDay, touchUserOnlineDay } from './dailyTracking.js'
import { utcDayStart } from '../types/analytics.js'
+describe('touchUserOnlineDay', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ db.userPresenceUpsert.mockResolvedValue({})
+ })
+
+ it('an app `open` upserts the (user, UTC day) row and bumps connections', async () => {
+ const now = new Date('2026-09-16T10:15:30.000Z')
+ await touchUserOnlineDay('user-1', now, { isNewConnection: true })
+
+ expect(db.userPresenceUpsert).toHaveBeenCalledTimes(1)
+ const call = db.userPresenceUpsert.mock.calls[0][0]
+ expect(call.where).toEqual({ userId_dayUtc: { userId: 'user-1', dayUtc: utcDayStart(now) } })
+ expect(call.create).toEqual({
+ userId: 'user-1', dayUtc: utcDayStart(now), connections: 1, firstSeenAt: now, lastSeenAt: now,
+ })
+ expect(call.update).toEqual({ lastSeenAt: now, connections: { increment: 1 } })
+ })
+
+ it('an app `ping` only touches lastSeenAt — a session spanning midnight opens no connection that day', async () => {
+ const now = new Date('2026-09-16T00:00:20.000Z')
+ await touchUserOnlineDay('user-1', now, { isNewConnection: false })
+
+ const call = db.userPresenceUpsert.mock.calls[0][0]
+ expect(call.update).toEqual({ lastSeenAt: now })
+ expect(call.create.connections).toBe(0)
+ })
+})
+
describe('touchMachineOnlineDay', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.ts
index a0d02252f..354e4fb87 100644
--- a/backend/src/lib/dailyTracking.ts
+++ b/backend/src/lib/dailyTracking.ts
@@ -3,8 +3,8 @@
* `UserDailyRemoteUsage`, `UserDailyDevicePresence`, `MachineDailyPresence` and
* `AgentDailyPresence` (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/adapter-ws relays (src/lib/webWs.ts, src/lib/deviceWs.ts, src/lib/adapterWs.ts),
- * not from a collector upload.
+ * device-ws/adapter-ws relays (src/lib/deviceWs.ts, src/lib/adapterWs.ts) plus the p2p_offer tap on
+ * web-ws (src/lib/webWs.ts), not from a collector upload.
*
* 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
@@ -12,18 +12,20 @@
* 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.
+ * heartbeat/ping, p2p_offer) — callers must not await them inline.
*/
import { prisma } from './prisma.js'
import { utcDayKey, utcDayStart } from '../types/analytics.js'
/**
- * 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`).
+ * Mark a user online for the UTC day containing `now`. The signal is the desktop app's own
+ * `app_presence` ping, relayed by its local `harness` daemon over adapter-ws (src/lib/adapterWs.ts):
+ * `isNewConnection: true` when the app just opened its loopback socket to the daemon (bumps
+ * `connections`), `false` for the periodic ping (just touches `lastSeenAt`, at most every
+ * USER_PRESENCE_WRITE_MS). Not the web-ws upgrade — the app never dials that itself.
*
- * `connections` counts connections OPENED on that day: a touch that is the first write of a new
- * UTC day but is not a connect (a session spanning midnight) creates the row with `connections: 0`,
+ * `connections` counts app sessions OPENED on that day: a touch that is the first write of a new
+ * UTC day but is not an open (a session spanning midnight) creates the row with `connections: 0`,
* so summing the column across days never double-counts one long session. Same rule for every
* `touch*OnlineDay` below.
*/
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 08be0f388..3bb58c7e6 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -53,8 +53,7 @@ import {
P2pSignalRateGuard,
terminalP2pPolicy,
} from './p2pSignaling.js'
-import { touchUserOnlineDay, recordRemoteUsage } from './dailyTracking.js'
-import { utcDayKey } from '../types/analytics.js'
+import { recordRemoteUsage } from './dailyTracking.js'
const wss = createWss(WS_LIMITS.web, { echoFirstProtocol: true })
@@ -122,20 +121,10 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
logger.info('web user connected', { userId: user.sub })
send({ type: 'connected', payload: { userId: user.sub } })
- // 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. 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 (!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)
+ // No daily-presence write here. This socket is not the person: the desktop app never dials it (the
+ // local daemon does, one per FOREIGN machine it relays), so counting upgrades measured relay
+ // reconnects and missed every single-machine user. `user_daily_presence` is fed by the app's own
+ // `app_presence` ping through the daemon's adapter-ws instead (lib/adapterWs.ts).
// 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
@@ -235,7 +224,6 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
if (!deviceSeedTimer) {
deviceSeedTimer = setInterval(() => {
void seedDeviceStatuses().catch(() => { /* ignore */ })
- touchPresence(false)
}, DEVICE_RESEED_MS)
}
await seedDeviceStatuses()
@@ -510,7 +498,6 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
if (deviceStatusUnsub) { deviceStatusUnsub(); deviceStatusUnsub = null }
if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }
if (deviceE2eePairUnsub) { deviceE2eePairUnsub(); deviceE2eePairUnsub = null }
- touchPresence(false)
logger.info('web user disconnected', { userId: user.sub, machineId: currentAgentId ?? undefined })
}
ws.on('close', cleanup)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 70703e10d..fcc74386d 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -990,6 +990,35 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('forwards the window\'s presence: open at once, ping once a minute, nothing while offline', async () => {
+ vi.useFakeTimers()
+ const socket = new BackendSocket('token')
+ const presence = (ws: InstanceType<typeof wsMock.MockWebSocket>) => parseSent(ws)
+ .filter((m) => (m.frame as { type?: string } | undefined)?.type === 'app_presence')
+
+ // Signed out / not yet dialed: dropped, never queued behind real frames.
+ expect(socket.sendAppPresence('open')).toBe(false)
+ socket.connect()
+ const ws = wsMock.instances[0]
+ expect(socket.sendAppPresence('ping')).toBe(false)
+ ws.open()
+ expect(ws.sent.filter((s) => s.includes('app_presence'))).toHaveLength(0)
+
+ expect(socket.sendAppPresence('open')).toBe(true)
+ // 30s later the window pings again — inside the floor, held back.
+ vi.advanceTimersByTime(30_000)
+ expect(socket.sendAppPresence('ping')).toBe(false)
+ vi.advanceTimersByTime(30_000)
+ expect(socket.sendAppPresence('ping')).toBe(true)
+ // A second window opening is a session in its own right, floor or not.
+ expect(socket.sendAppPresence('open')).toBe(true)
+ expect(presence(ws).map((m) => (m.frame as { payload: { kind: string } }).payload.kind)).toEqual(['open', 'ping', 'open'])
+ // Bookkeeping about the person, for the backend alone: never fanned out to a client.
+ expect(presence(ws)[0]).toMatchObject({ t: 'up', webEligible: false, commanderEligible: false })
+
+ await socket.stop()
+ })
+
it('reports commander presence only when it crosses zero', async () => {
const socket = new BackendSocket('token')
const changes: boolean[] = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 3a4b80754..846721aca 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -103,6 +103,10 @@ export type RecentProvider = (sessionId: string, n: number) => Array<{ kind: str
const APP_PING_MS = 15_000
+// Floor between two `app_presence` up-frames. The window pings this daemon every 30s; the backend
+// only needs to hear about it about once a minute (it floors its own Mongo write at five). `open`
+// is never held back — it is the one that counts as a session in `user_daily_presence`.
+const APP_PRESENCE_UP_MS = 60_000
// How long the opening handshake may take before the attempt is abandoned and retried. `ws` waits
// forever by default, and the heartbeat below only starts on 'open' — so a TCP connection that came
// up while the network was flapping but never got its upgrade answered sat in CONNECTING for hours,
@@ -306,6 +310,7 @@ export class BackendSocket {
private droppedSinceLog = 0
private heartbeat: LivenessWatch | null = null
private appPing: NodeJS.Timeout | null = null
+ private lastAppPresenceUpAt = 0
private readonly downChains = new Map<string, Promise<void>>()
private readonly localClients = new Map<string, LocalClientSink>()
private terminalStreams: TerminalStreamManager | null = null
@@ -605,6 +610,8 @@ export class BackendSocket {
// App-level ping refreshes the backend's presence key (TTL 30s).
this.appPing = setInterval(() => this.sendBestEffort({ t: 'ping' }), APP_PING_MS)
+ // A fresh socket knows nothing about the window; let its next ping through at once.
+ this.lastAppPresenceUpAt = 0
})
ws.on('message', (raw, isBinary) => {
@@ -819,6 +826,26 @@ export class BackendSocket {
this.enqueue({ t: 'up', webEligible: false, commanderEligible: true, frame: this.e2ee.wrapCommander(frame) })
}
+ /**
+ * The desktop window is open on this computer (localWsServer `app_presence`): tell the backend, which
+ * turns it into the person's `user_daily_presence` row. `open` goes up at once, `ping` at most once
+ * per APP_PRESENCE_UP_MS. Best-effort and plaintext on purpose: it is bookkeeping about the person,
+ * not data, and a daemon that is signed out (no backend dial) or between reconnects simply drops it
+ * rather than queueing a stale "was open" behind real frames. Returns whether a frame went up.
+ */
+ sendAppPresence(kind: 'open' | 'ping'): boolean {
+ const now = Date.now()
+ if (kind === 'ping' && now - this.lastAppPresenceUpAt < APP_PRESENCE_UP_MS) return false
+ const sent = this.sendBestEffort({
+ t: 'up',
+ webEligible: false,
+ commanderEligible: false,
+ frame: { type: 'app_presence', payload: { kind } },
+ })
+ if (sent) this.lastAppPresenceUpAt = now
+ return sent
+ }
+
/** Attach one authenticated loopback desktop client to the same RPC and event plane as cloud web. */
registerLocalClient(connId: string, sink: LocalClientSink): boolean {
if (!isLocalClientId(connId) || this.localClients.has(connId)) return false
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 01022c122..ad02cd895 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3217,6 +3217,9 @@ async function runForeground(session: AuthSession): Promise<void> {
// The window's swarms. Relayed to the dial as its own list — the dial names the one on screen above
// the agent and offers the rest — and, through setSwarms, what makes the desk strict: a present
// window with an empty swarm is an empty carousel, not the whole machine.
+ // The window's "I am open" — the only desk fact that goes UP. Throttled and dropped-when-offline
+ // inside sendAppPresence, so a guest daemon costs nothing here.
+ onAppPresence: (kind) => { backend.sendAppPresence(kind) },
onAppSwarms: (swarms) => {
cableHostRef?.setSwarms(swarms)
void cableRef?.syncSwarms()
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 27ac51932..e30471335 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -212,6 +212,36 @@ describe('local CLI WebSocket', () => {
ws.close()
})
+ it('hands the window\'s presence ping to the daemon, and keeps it off the wire', async () => {
+ const backend = new FakeBackend()
+ const kinds: string[] = []
+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
+ local = attachLocalWsServer(server, {
+ machineId,
+ backend,
+ onAppPresence: (kind) => kinds.push(kind),
+ })
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
+ const ws = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`)
+ await onceOpen(ws)
+ const connected = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))
+ await connected
+
+ ws.send(JSON.stringify({ type: 'app_presence', payload: { kind: 'open' } }))
+ ws.send(JSON.stringify({ type: 'app_presence', payload: { kind: 'ping' } }))
+ // Not a kind the backend knows: dropped here rather than forwarded as a guess.
+ ws.send(JSON.stringify({ type: 'app_presence', payload: { kind: 'closed' } }))
+ ws.send(JSON.stringify({ type: 'app_presence' }))
+ ws.send(JSON.stringify({ type: 'terminal_open', payload: { agentId: 'agent-opened' } }))
+ await vi.waitFor(() => expect(backend.frames).toHaveLength(1))
+
+ expect(kinds).toEqual(['open', 'ping'])
+ // The machine never sees any of it — the daemon forwards presence on its own adapter socket.
+ expect(backend.frames.map((frame) => frame.type)).toEqual(['terminal_open'])
+ ws.close()
+ })
+
it('reports only explicit voice focus and clears by originating connection', async () => {
const backend = new FakeBackend()
const states: Array<{ machine: string; agent: string | null; conn: string }> = []
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 345745070..236cb6bc5 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -33,6 +33,8 @@ export interface LocalWsBackend {
handleLocalBinary: (connId: string, frame: TerminalBinaryClear) => Promise<void>
}
+export type AppPresenceKind = 'open' | 'ping'
+
export interface LocalWsServerOptions {
machineId: string
backend: LocalWsBackend
@@ -47,6 +49,12 @@ export interface LocalWsServerOptions {
onAppFocus?: (machineId: string, agentId: string) => void
/** Every agent the window currently has a tile for, across all its machines. */
onAppPanes?: (agentIds: string[]) => void
+ /**
+ * The window is open: `open` once when it connects this socket, `ping` every 30s after. The one fact
+ * about this desk the backend does want (it is how a person's day gets counted, see backendSocket
+ * sendAppPresence) — so it is the daemon's to forward, throttled, and never the machine's to see.
+ */
+ onAppPresence?: (kind: AppPresenceKind) => void
/**
* The window's swarms — its named groups of agents, one of them on screen. The whole list each time,
* and `null` when the window goes away, so the daemon never keeps describing tabs nobody can see.
@@ -413,6 +421,13 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
// Focus is local desk state and must never be forwarded to a remote machine.
return
}
+ if (parsed?.type === 'app_presence') {
+ const kind = (parsed.payload as Record<string, unknown> | undefined)?.kind
+ if (kind === 'open' || kind === 'ping') options.onAppPresence?.(kind)
+ // Like app_focus: about this desk, never the machine's business — a remote daemon would
+ // only drop it as an unknown frame anyway.
+ return
+ }
// Preserve the old dial fallback; terminal streams never establish voice focus.
if (parsed?.type === 'terminal_open' && typeof agentId === 'string' && agentId) {
options.onAppFocus?.(boundMachineId, agentId)
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 9f1779e98..3932fe216 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -288,6 +288,7 @@ class AppNotifier extends ChangeNotifier {
final AuthSession session;
AppConfig config;
late ApiClient api;
+
/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
/// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call
/// site reads the same in both.
@@ -379,6 +380,12 @@ class AppNotifier extends ChangeNotifier {
// (agent_synced/agent_created/agent_renamed/agent_deleted) that normally keep it live — catches the
// rare case a push event was dropped. Runs silently: see _syncAgentsIfChanged.
final Map<String, Timer> _agentSyncTimers = {};
+ // "This window is open" — the one fact about the desk that goes past the daemon, to the backend,
+ // where it becomes the person's day in `user_daily_presence`. Sent only to THIS computer's daemon
+ // (a relayed machine's daemon would drop it as an unknown frame, and the account is the same
+ // either way). `open` once when the local socket connects, `ping` every [appPresenceInterval]
+ // after; see _startAppPresence.
+ final Map<String, Timer> _appPresenceTimers = {};
// Keeps the local `harness` daemon alive for the whole app run — started once after the first
// successful bootstrap (see `ensureCliDaemonReady`), cancelled on dispose. Cancelling only stops this
// Dart-side loop; the daemon itself self-daemonizes and must keep running after the app quits.
@@ -498,11 +505,9 @@ class AppNotifier extends ChangeNotifier {
final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;
return target == null ||
target.panes.length < maxPanes ||
- target.panes.any(
- (p) =>
- p.machineId == entry.machineId &&
- p.agentId == entry.agentId,
- );
+ target.panes.any(
+ (p) => p.machineId == entry.machineId && p.agentId == entry.agentId,
+ );
}
bool _canReopenSwarm(ClosedSwarm saved) {
@@ -1196,6 +1201,7 @@ class AppNotifier extends ChangeNotifier {
static const offlineRetryInterval = Duration(seconds: 5);
static const agentSyncInterval = Duration(seconds: 60);
+ static const appPresenceInterval = Duration(seconds: 30);
MachineState? stateOf(String machineId) => machineStates[machineId];
@@ -1532,6 +1538,7 @@ class AppNotifier extends ChangeNotifier {
unawaited(_applyNodeStatus(machine, true));
unawaited(_loadMachineData(machine, force: true));
_startAgentSyncTimer(machineId);
+ if (machine.isLocalMachine) _startAppPresence(machineId);
}
@visibleForTesting
@@ -2413,6 +2420,7 @@ class AppNotifier extends ChangeNotifier {
_daemonSupervisionTimer?.cancel();
_daemonSupervisionTimer = null;
_cliEndpoint = null;
+ _stopAllAppPresence();
unawaited(_pool?.closeAll());
_pool = null;
_lastError = message;
@@ -2653,6 +2661,7 @@ class AppNotifier extends ChangeNotifier {
_stopAllOfflineRetries();
_stopAllLinkRetries();
_stopAllAgentSyncTimers();
+ _stopAllAppPresence();
// Tiles go, the saved layout stays: signing out and back in is the same
// person at the same desk, and the file is only read once machines exist.
await _closeAllPanes(persist: false);
@@ -2732,41 +2741,48 @@ class AppNotifier extends ChangeNotifier {
onAuthFailure: _signedOutAtRuntime,
onLocalFailure: _onLocalFailure,
onEvent: _handleEvent,
- onStatus: (machineId, nextStatus) {
- final machine = machineStates[machineId];
- if (machine == null) return;
- machine.connectionStatus = nextStatus;
- if (nextStatus == ConnectionStatus.connected) {
- _onMachineConnected(machineId, machine);
- } else if (nextStatus == ConnectionStatus.reconnecting ||
- nextStatus == ConnectionStatus.disconnected) {
- _stopAgentSyncTimer(machineId);
- _clearMachineActivity(machine);
- if (machine.isLocalMachine) {
- machine.transportMode = MachineTransportMode.localOffline;
- }
- // Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open
- // terminal (if any) so the connected branch above can reattach it, for every machine — this
- // used to be local-only, which is why a remote machine's terminal never came back on its own
- // after `harness start` on that machine, even though the guide screen promised it would.
- //
- // NOT while the machine is unlinked. NO_PEER_LINK is the local CLI failing a lookup in its
- // own peer table (remoteRelay.ts `dial`) before anything is dialled, so neither that close
- // nor the one `_startLinkRetry`'s `closeMachine` fires every few seconds says anything about
- // whether the OTHER computer is up — our socket never reaches it. Forcing nodeOnline false
- // here overwrote the REST `/api/machines` status, the one signal that does, and painted
- // every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on
- // purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is
- // set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).
- if (!machine.needsLink) {
- unawaited(_applyNodeStatus(machine, false));
- }
- }
- notifyListeners();
- },
+ onStatus: _onConnectionStatus,
);
}
+ @visibleForTesting
+ void connectionStatusForTest(String machineId, ConnectionStatus status) =>
+ _onConnectionStatus(machineId, status);
+
+ void _onConnectionStatus(String machineId, ConnectionStatus nextStatus) {
+ final machine = machineStates[machineId];
+ if (machine == null) return;
+ machine.connectionStatus = nextStatus;
+ if (nextStatus == ConnectionStatus.connected) {
+ _onMachineConnected(machineId, machine);
+ } else if (nextStatus == ConnectionStatus.reconnecting ||
+ nextStatus == ConnectionStatus.disconnected) {
+ _stopAgentSyncTimer(machineId);
+ _stopAppPresence(machineId);
+ _clearMachineActivity(machine);
+ if (machine.isLocalMachine) {
+ machine.transportMode = MachineTransportMode.localOffline;
+ }
+ // Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open
+ // terminal (if any) so the connected branch above can reattach it, for every machine — this
+ // used to be local-only, which is why a remote machine's terminal never came back on its own
+ // after `harness start` on that machine, even though the guide screen promised it would.
+ //
+ // NOT while the machine is unlinked. NO_PEER_LINK is the local CLI failing a lookup in its
+ // own peer table (remoteRelay.ts `dial`) before anything is dialled, so neither that close
+ // nor the one `_startLinkRetry`'s `closeMachine` fires every few seconds says anything about
+ // whether the OTHER computer is up — our socket never reaches it. Forcing nodeOnline false
+ // here overwrote the REST `/api/machines` status, the one signal that does, and painted
+ // every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on
+ // purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is
+ // set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).
+ if (!machine.needsLink) {
+ unawaited(_applyNodeStatus(machine, false));
+ }
+ }
+ notifyListeners();
+ }
+
/// The machine list is being fetched and there is nothing to show meanwhile.
///
/// Only the FIRST fetch sets it: a refresh over a list already on screen
@@ -2954,6 +2970,7 @@ class AppNotifier extends ChangeNotifier {
_stopOfflineRetry(entry.key);
_stopLinkRetry(entry.key);
_stopAgentSyncTimer(entry.key);
+ _stopAppPresence(entry.key);
}
}
machineStates.removeWhere((id, _) => !visible.contains(id));
@@ -3067,6 +3084,49 @@ class AppNotifier extends ChangeNotifier {
_agentSyncTimers.clear();
}
+ /// Tell this computer's daemon the window is open: `open` now, then a `ping` every
+ /// [appPresenceInterval] for as long as the local socket stays up. Fire-and-forget on the
+ /// ready socket only (like app_focus) — a ping that finds the socket down is simply lost, and
+ /// the reconnect's own `open` says everything it would have.
+ void _startAppPresence(String machineId) {
+ if (_appPresenceTimers.containsKey(machineId)) return;
+ _sendAppPresence(machineId, 'open');
+ _appPresenceTimers[machineId] = Timer.periodic(appPresenceInterval, (_) {
+ if (!machineStates.containsKey(machineId)) {
+ _stopAppPresence(machineId);
+ return;
+ }
+ _sendAppPresence(machineId, 'ping');
+ });
+ }
+
+ void _sendAppPresence(String machineId, String kind) {
+ if (_disposed) return;
+ // The socket that reported `connected` (or the fixture standing in for it) — never one dialed
+ // for the purpose: this runs on a timer, and a tick that lands after the pool dropped the
+ // machine must not resurrect it.
+ final connection = connectionForTest != null
+ ? _conn(machineId)
+ : _pool?[machineId];
+ if (connection == null) return;
+ unawaited(
+ connection
+ .sendTerminalFrame('app_presence', {'kind': kind})
+ .catchError((_) => false),
+ );
+ }
+
+ void _stopAppPresence(String machineId) {
+ _appPresenceTimers.remove(machineId)?.cancel();
+ }
+
+ void _stopAllAppPresence() {
+ for (final timer in _appPresenceTimers.values) {
+ timer.cancel();
+ }
+ _appPresenceTimers.clear();
+ }
+
/// Silent safety-net reconciliation, ticked every [agentSyncInterval] while a machine is connected.
/// Only writes/notifies if the fetched list actually differs from what's already shown — a steady
/// state where push events (agent_synced et al.) have kept everything in sync produces zero visible
@@ -4831,6 +4891,7 @@ class AppNotifier extends ChangeNotifier {
}
_persistLayout();
_stopAgentSyncTimer(machineId);
+ _stopAppPresence(machineId);
machineStates.remove(machineId);
machines.removeWhere((m) => m.machineId == machineId);
if (selectedMachineId == machineId) selectedMachineId = null;
@@ -6417,6 +6478,7 @@ class AppNotifier extends ChangeNotifier {
_stopAllOfflineRetries();
_stopAllLinkRetries();
_stopAllAgentSyncTimers();
+ _stopAllAppPresence();
_clearAllTurnActivity();
for (final pane in allPanes) {
pane.session?.removeListener(notifyListeners);
diff --git a/desktop/test/machine_loading_test.dart b/desktop/test/machine_loading_test.dart
index 545107adf..42a9b0a68 100644
--- a/desktop/test/machine_loading_test.dart
+++ b/desktop/test/machine_loading_test.dart
@@ -57,6 +57,7 @@ class _Connection extends WsConn {
bool refuseTheme = false;
final timeouts = <String, Duration>{};
final sent = <String>[];
+ final sentPayloads = <Map<String, dynamic>>[];
Completer<void>? readiness;
@override
@@ -97,6 +98,7 @@ class _Connection extends WsConn {
Map<String, dynamic> payload,
) async {
sent.add(type);
+ sentPayloads.add({'type': type, 'payload': payload});
return true;
}
}
@@ -120,7 +122,13 @@ void main() {
app.machines = [_machine];
app.machineStates['m'] = machine;
});
- tearDown(() => app.dispose());
+ // A widget test must have no timer left when its tree is torn down, which is before tearDown
+ // runs — those tests dispose the app themselves and say so here.
+ var disposedInTest = false;
+ tearDown(() {
+ if (!disposedInTest) app.dispose();
+ disposedInTest = false;
+ });
test('agent inventory and capabilities are requested together', () async {
final load = app.reloadMachineData('m');
@@ -271,6 +279,45 @@ void main() {
expect(app.panes, isEmpty);
});
+ group('the window\'s presence reaches this computer\'s daemon', () {
+ Iterable<String> kinds() => connection.sentPayloads
+ .where((f) => f['type'] == 'app_presence')
+ .map((f) => f['payload']['kind'] as String);
+
+ testWidgets(
+ 'says open on connect and pings every interval until the socket drops',
+ (tester) async {
+ machine.localOnly = true;
+ app.onMachineConnectedForTest('m');
+ await tester.pump();
+ expect(kinds(), ['open']);
+
+ await tester.pump(AppNotifier.appPresenceInterval);
+ await tester.pump(AppNotifier.appPresenceInterval);
+ expect(kinds(), ['open', 'ping', 'ping']);
+
+ // The daemon went away: nothing is pinged into the void, and the reconnect will say `open`.
+ app.connectionStatusForTest('m', ConnectionStatus.disconnected);
+ await tester.pump(AppNotifier.appPresenceInterval * 3);
+ expect(kinds(), hasLength(3));
+ app.dispose();
+ disposedInTest = true;
+ },
+ );
+
+ testWidgets(
+ 'is not sent to a relayed machine — its daemon is not this desk',
+ (tester) async {
+ app.onMachineConnectedForTest('m');
+ await tester.pump();
+ await tester.pump(AppNotifier.appPresenceInterval * 2);
+ expect(kinds(), isEmpty);
+ app.dispose();
+ disposedInTest = true;
+ },
+ );
+ });
+
group('pane colours reach the daemon', () {
tearDown(() {
grid.AppTheme.palette.value = HarnessPalette.graphite;