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.

presence: count the TUI, the mobile app and the web, not only the desktop app

0xken15c39f32d8d185
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 6e82a09ae..cd11b8ca5 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -569,6 +569,30 @@ model UserDailyPresence {
@@map("user_daily_presence")
}
+/// Per-day record of a user on a surface other than the desktop app — `UserDailyPresence` stays the
+/// desktop app's alone. One row per (user, surface, UTC day); DAU is a distinct `userId`.
+/// `surface`: 'tui' (`harness tui`, reported by the local daemon like a desktop window: adapter-ws
+/// `app_presence { surface: 'tui' }`, src/lib/adapterWs.ts), 'mobile' / 'web' (the app's and the
+/// browser's own web-ws sockets, declared with `?client=` — src/lib/webWs.ts; the daemon's relay
+/// socket declares nothing and is never counted). `connections` = sessions opened that day (for
+/// mobile/web one per machine socket); a session spanning midnight gives the next day `0`.
+/// No `machineId`: mobile and web hold a socket per machine they look at, and it is one person.
+model UserDailyClientPresence {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ userId String
+ surface String
+ dayUtc DateTime
+ connections Int @default(0)
+ firstSeenAt DateTime
+ lastSeenAt DateTime
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([userId, surface, dayUtc])
+ @@index([surface, dayUtc])
+ @@map("user_daily_client_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 {
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 83767e789..a4294f15d 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, touchUserOnlineDay, type PresenceWriteState } from './dailyTracking.js'
+import { presenceTracker, presenceWriteDue, recordTurnStarted, touchClientOnlineDay, touchMachineOnlineDay, touchUserOnlineDay, type PresenceWriteState } from './dailyTracking.js'
import { countryCodeFromHeaders } from './clientGeo.js'
import { recordCreatedAgent, recordDeletedAgent } from './agentTracker.js'
import type { Frame } from './tunnel.js'
@@ -300,22 +300,19 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// 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. The row is keyed by THIS machine too, so the same person
// on a second computer lands in a second row rather than in this one.
- 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, machineId, 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 })
- }
+ const userPresenceFloors = { pingFloorMs: USER_PRESENCE_WRITE_MS, openFloorMs: USER_PRESENCE_OPEN_MS }
+ const touchUserPresence = presenceTracker(
+ (now, isNewConnection) => touchUserOnlineDay(userId, machineId, now, { isNewConnection }),
+ (kind, err) => logger.warn('user presence tracking failed', { machineId, userId, kind, error: String(err) }),
+ userPresenceFloors,
+ )
+ // `harness tui` on this computer: the daemon reports it like a window but names the surface, and it
+ // is kept out of the desktop app's table (`user_daily_client_presence`, schema.prisma).
+ const touchTuiPresence = presenceTracker(
+ (now, isNewConnection) => touchClientOnlineDay(userId, 'tui', now, { isNewConnection }),
+ (kind, err) => logger.warn('tui presence tracking failed', { machineId, userId, kind, error: String(err) }),
+ userPresenceFloors,
+ )
// 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
@@ -437,9 +434,11 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// 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
+ const { kind, surface } = (app.payload ?? {}) as { kind?: unknown; surface?: unknown }
if (typeof kind !== 'string' || !APP_PRESENCE_KINDS.has(kind)) return
- touchUserPresence(kind as 'open' | 'ping')
+ // No surface = the desktop app (every daemon before this field, and the desktop window now).
+ if (surface === 'tui') touchTuiPresence(kind as 'open' | 'ping')
+ else touchUserPresence(kind as 'open' | 'ping')
return
}
// The machine appending to its account's device key log (lib/deviceKeyLog.ts): its own key, or a
diff --git a/backend/src/lib/dailyTracking.test.ts b/backend/src/lib/dailyTracking.test.ts
index b55815b9c..ae59b7263 100644
--- a/backend/src/lib/dailyTracking.test.ts
+++ b/backend/src/lib/dailyTracking.test.ts
@@ -5,6 +5,7 @@ const db = vi.hoisted(() => ({
machinePresenceUpsert: vi.fn(),
agentPresenceUpsert: vi.fn(),
devicePresenceUpsert: vi.fn(),
+ clientPresenceUpsert: vi.fn(),
}))
vi.mock('./prisma.js', () => ({
@@ -13,10 +14,11 @@ vi.mock('./prisma.js', () => ({
machineDailyPresence: { upsert: db.machinePresenceUpsert },
agentDailyPresence: { upsert: db.agentPresenceUpsert },
userDailyDevicePresence: { upsert: db.devicePresenceUpsert },
+ userDailyClientPresence: { upsert: db.clientPresenceUpsert },
},
}))
-import { presenceWriteDue, recordTurnStarted, touchDeviceOnlineDay, touchMachineOnlineDay, touchUserOnlineDay } from './dailyTracking.js'
+import { presenceTracker, presenceWriteDue, recordTurnStarted, touchClientOnlineDay, touchDeviceOnlineDay, touchMachineOnlineDay, touchUserOnlineDay } from './dailyTracking.js'
import { utcDayStart } from '../types/analytics.js'
describe('touchUserOnlineDay', () => {
@@ -51,6 +53,72 @@ describe('touchUserOnlineDay', () => {
})
})
+describe('touchClientOnlineDay', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ db.clientPresenceUpsert.mockResolvedValue({})
+ })
+
+ it('upserts the (user, surface, UTC day) row — no machine — and only an open counts a connection', async () => {
+ const now = new Date('2026-10-07T08:00:00.000Z')
+ await touchClientOnlineDay('user-1', 'mobile', now, { isNewConnection: true })
+ await touchClientOnlineDay('user-1', 'mobile', now, { isNewConnection: false })
+
+ const [open, ping] = db.clientPresenceUpsert.mock.calls.map((c) => c[0])
+ expect(open.where).toEqual({ userId_surface_dayUtc: { userId: 'user-1', surface: 'mobile', dayUtc: utcDayStart(now) } })
+ expect(open.create).toEqual({ userId: 'user-1', surface: 'mobile', dayUtc: utcDayStart(now), connections: 1, firstSeenAt: now, lastSeenAt: now })
+ expect(open.update).toEqual({ lastSeenAt: now, connections: { increment: 1 } })
+ expect(ping.update).toEqual({ lastSeenAt: now })
+ expect(ping.create.connections).toBe(0)
+ })
+})
+
+describe('presenceTracker', () => {
+ const floors = { pingFloorMs: 5 * 60_000, openFloorMs: 10_000 }
+ const flush = () => new Promise((r) => setTimeout(r, 0))
+
+ it('writes an open at once, holds pings to the floor, and never two writes at a time', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(new Date('2026-10-07T08:00:00.000Z'))
+ const writes: boolean[] = []
+ let release: () => void = () => {}
+ const write = vi.fn((_now: Date, isNew: boolean) => {
+ writes.push(isNew)
+ return new Promise<void>((r) => { release = r })
+ })
+ const touch = presenceTracker(write, vi.fn(), floors)
+
+ touch('open')
+ touch('ping') // a write is in flight
+ expect(writes).toEqual([true])
+ release(); await flush()
+
+ touch('ping') // within the floor
+ expect(writes).toEqual([true])
+ vi.setSystemTime(new Date('2026-10-07T08:05:00.000Z'))
+ touch('ping')
+ expect(writes).toEqual([true, false])
+ release(); await flush()
+
+ touch('open') // a reconnect storm is not a session per dial
+ vi.setSystemTime(new Date('2026-10-07T08:05:05.000Z'))
+ touch('open')
+ expect(writes).toEqual([true, false, true])
+ vi.useRealTimers()
+ })
+
+ it('hands a failed write to onError, and the next ping is still due', async () => {
+ const onError = vi.fn()
+ const write = vi.fn(async () => { throw new Error('mongo down') })
+ const touch = presenceTracker(write, onError, floors)
+ touch('ping')
+ await flush()
+ expect(onError).toHaveBeenCalledWith('ping', expect.any(Error))
+ touch('ping')
+ expect(write).toHaveBeenCalledTimes(2)
+ })
+})
+
describe('touchDeviceOnlineDay', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.ts
index 52afecd29..ec5f7a4a4 100644
--- a/backend/src/lib/dailyTracking.ts
+++ b/backend/src/lib/dailyTracking.ts
@@ -1,6 +1,6 @@
/**
* Presence / remote-usage daily tracking — write path for `UserDailyPresence`,
- * `UserDailyRemoteUsage`, `UserDailyDevicePresence`, `MachineDailyPresence` and
+ * `UserDailyClientPresence`, `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
* device-ws/adapter-ws relays (src/lib/deviceWs.ts, src/lib/adapterWs.ts) plus the p2p_offer tap on
@@ -162,3 +162,59 @@ export function presenceWriteDue(last: PresenceWriteState, now: Date, minInterva
if (utcDayKey(now) !== last.dayKey) return true
return now.getTime() - last.wroteAt >= minIntervalMs
}
+
+/** Surfaces other than the desktop app whose person is counted (`user_daily_client_presence`). */
+export type ClientSurface = 'tui' | 'mobile' | 'web'
+export const CLIENT_SURFACES: ReadonlySet<string> = new Set<ClientSurface>(['tui', 'mobile', 'web'])
+
+/**
+ * `touchUserOnlineDay` for the other surfaces, one row per (user, surface, day): the TUI reported by
+ * the daemon like a desktop window (`app_presence { surface: 'tui' }`, src/lib/adapterWs.ts), the
+ * mobile app and the web viewer from their own web-ws sockets (src/lib/webWs.ts). No machine: the
+ * mobile app and the web hold one socket per machine they look at, and the person is the same.
+ */
+export async function touchClientOnlineDay(
+ userId: string,
+ surface: ClientSurface,
+ now: Date,
+ opts: { isNewConnection: boolean },
+): Promise<void> {
+ const dayUtc = utcDayStart(now)
+ await prisma.userDailyClientPresence.upsert({
+ where: { userId_surface_dayUtc: { userId, surface, dayUtc } },
+ create: { userId, surface, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
+ update: {
+ lastSeenAt: now,
+ ...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
+ },
+ })
+}
+
+/**
+ * The write discipline every person-presence signal shares: `open` counts a session (at most once per
+ * `openFloorMs`, so a reconnect storm is not a hundred sessions), `ping` only refreshes `lastSeenAt`
+ * and at most every `pingFloorMs` (or on a new UTC day), and one write is in flight at a time.
+ * `write` gets `isNewConnection`; failures go to `onError` — callers never await this.
+ */
+export function presenceTracker(
+ write: (now: Date, isNewConnection: boolean) => Promise<void>,
+ onError: (kind: 'open' | 'ping', err: unknown) => void,
+ { pingFloorMs, openFloorMs }: { pingFloorMs: number; openFloorMs: number },
+): (kind: 'open' | 'ping') => void {
+ const last: PresenceWriteState = { dayKey: null, wroteAt: 0 }
+ let inFlight = false
+ let lastOpenAt = 0
+ return (kind) => {
+ const now = new Date()
+ if (kind === 'ping' && (inFlight || !presenceWriteDue(last, now, pingFloorMs))) return
+ if (kind === 'open') {
+ if (now.getTime() - lastOpenAt < openFloorMs) return
+ lastOpenAt = now.getTime()
+ }
+ inFlight = true
+ write(now, kind === 'open')
+ .then(() => { last.dayKey = utcDayKey(now); last.wroteAt = now.getTime() })
+ .catch((err) => onError(kind, err))
+ .finally(() => { inFlight = false })
+ }
+}
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 7d866e06c..6d7ba3e33 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -56,9 +56,12 @@ import {
P2pSignalRateGuard,
terminalP2pPolicy,
} from './p2pSignaling.js'
-import { recordRemoteUsage } from './dailyTracking.js'
+import { presenceTracker, recordRemoteUsage, touchClientOnlineDay } from './dailyTracking.js'
import { isBackendOnlyDownType } from './backendOnlyFrames.js'
+// How often an open mobile/web socket refreshes its person's `user_daily_client_presence` row.
+const WEB_CLIENT_PRESENCE_WRITE_MS = 5 * 60_000
+
/** Down-frames only the backend may send — see lib/backendOnlyFrames.ts. Re-exported for existing callers. */
export { BACKEND_ONLY_DOWN_TYPES } from './backendOnlyFrames.js'
@@ -89,12 +92,15 @@ export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buf
// PER-USER mode: profile validation is async, so authenticate before completing the upgrade.
void (async () => {
try {
- const requestedEnvironment = parseAutonomousEnvironment(
- new URL(req.url ?? '/api/web-ws', 'http://backend.local').searchParams.get('autonomousEnv'),
- )
+ const query = new URL(req.url ?? '/api/web-ws', 'http://backend.local').searchParams
+ const requestedEnvironment = parseAutonomousEnvironment(query.get('autonomousEnv'))
+ // Who is on the other end, as the client declares it: the mobile app and the web viewer say so;
+ // the daemon's relay (and any older client) says nothing and is never counted as a person.
+ const declared = query.get('client')
+ const surface = declared === 'mobile' || declared === 'web' ? declared : null
const user = await authenticateAccessToken(cred, requestedEnvironment)
if (socket.destroyed) return
- wss.handleUpgrade(req, socket, head, (ws) => attachUserClient(ws, user))
+ wss.handleUpgrade(req, socket, head, (ws) => attachUserClient(ws, user, surface))
} catch (err) {
if (socket.destroyed) return
const invalid = err instanceof SsoAuthError && err.code === 'INVALID_TOKEN'
@@ -112,7 +118,7 @@ export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buf
}
/** PER-USER socket: starts unattached; `machine_select` scopes it to one owned machine at a time. */
-function attachUserClient(ws: WebSocket, user: AuthUser): void {
+function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'web' | null): void {
let client: HubClient | null = null
let currentAgentId: string | null = null
let currentBinding: Machine | null = null
@@ -128,10 +134,21 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
logger.info('web user connected', { userId: user.sub })
send({ type: 'connected', payload: { userId: user.sub } })
- // 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).
+ // The desktop app never dials this socket — the local daemon does, one per FOREIGN machine it relays —
+ // so it writes no `user_daily_presence` (that is the app's `app_presence` through adapter-ws,
+ // lib/adapterWs.ts). The mobile app and the web viewer DO dial it themselves and declare it
+ // (`?client=`): their person is counted in `user_daily_client_presence`, a session per socket, then
+ // `lastSeenAt` every WEB_CLIENT_PRESENCE_WRITE_MS while it stays open (so it lags by at most that).
+ let presenceTimer: ReturnType<typeof setInterval> | null = null
+ if (surface) {
+ const touchPresence = presenceTracker(
+ (now, isNewConnection) => touchClientOnlineDay(user.sub, surface, now, { isNewConnection }),
+ (kind, err) => logger.warn('client presence tracking failed', { userId: user.sub, surface, kind, error: String(err) }),
+ { pingFloorMs: WEB_CLIENT_PRESENCE_WRITE_MS, openFloorMs: 0 },
+ )
+ touchPresence('open')
+ presenceTimer = setInterval(() => touchPresence('ping'), WEB_CLIENT_PRESENCE_WRITE_MS)
+ }
// 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
@@ -511,6 +528,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
if (closed) return
closed = true
releaseLiveness()
+ if (presenceTimer) { clearInterval(presenceTimer); presenceTimer = null }
client?.detach()
client = null
currentBinding = null
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 68a7c6394..d4447ebee 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2420,6 +2420,37 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('reports the TUI as its own surface, and a tool as no one', async () => {
+ vi.useFakeTimers()
+ const socket = relaySocket('token')
+ const sink = { sendFrame: () => true, sendBinary: () => true }
+ const presence = (ws: InstanceType<typeof wsMock.MockWebSocket>) => parseSent(ws)
+ .filter((m) => (m.frame as { type?: string } | undefined)?.type === 'app_presence')
+ .map((m) => (m.frame as { payload: Record<string, unknown> }).payload)
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+
+ // A tool (`harness pair`, the MCP server) is not a person at a window: nothing, now or on the tick.
+ expect(socket.registerLocalClient('local:tool', sink, { tool: true })).toBe(true)
+ vi.advanceTimersByTime(60_000)
+ expect(presence(ws)).toEqual([])
+
+ // The TUI names its surface; the desktop app's frame stays exactly as it was.
+ expect(socket.registerLocalClient('local:tui', sink, { surface: 'tui' })).toBe(true)
+ expect(socket.registerLocalClient('local:app', sink)).toBe(true)
+ expect(presence(ws)).toEqual([{ kind: 'open', surface: 'tui' }, { kind: 'open' }])
+
+ // Each pings for itself while it stays — and only it, once the other has gone.
+ vi.advanceTimersByTime(60_000)
+ expect(presence(ws).slice(2)).toEqual([{ kind: 'ping' }, { kind: 'ping', surface: 'tui' }])
+ await socket.unregisterLocalClient('local:app')
+ vi.advanceTimersByTime(60_000)
+ expect(presence(ws).slice(4)).toEqual([{ kind: 'ping', surface: 'tui' }])
+
+ await socket.stop()
+ })
+
it('reports commander presence only when it crosses zero', async () => {
const socket = relaySocket('token')
const changes: boolean[] = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index deb2c11d8..7622ac7e0 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,5 +1,5 @@
import type { PurgeAgentService } from './lib/purgeAgentService.js'
-import { SHARE_REQUESTS, TEAMS_REQUESTS, type Asker, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
+import { SHARE_REQUESTS, TEAMS_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
import { ServiceUnavailableError } from './core/serviceHost.js'
import type { ViewerStreams } from './core/viewerStreams.js'
import type { ActivityFrame } from './lib/turnActivity.js'
@@ -96,6 +96,8 @@ export class BackendSocket {
* this computer — not presence, not a window to push to, and never what wakes the pair brain.
*/
private readonly toolClients = new Set<string>()
+ /** The windows that are `harness tui`, not the desktop app: each surface is its own presence. */
+ private readonly tuiClients = new Set<string>()
private terminalStreams: TerminalStreamManager | null = null
private onStatus: (connected: boolean) => void
/** Cross-instance commander (device) client count, as the gateway reads it from the backend. */
@@ -320,7 +322,7 @@ export class BackendSocket {
this.gatewayPort = gateway
if (!this.requestsOpen) gateway.holdRequests()
if (this.thisComputerOnly) gateway.serveThisComputerOnly()
- gateway.localClients(this.localClients.size)
+ gateway.localClients(this.localWindows())
}
get gateway(): GatewayPort | null { return this.gatewayPort }
@@ -596,17 +598,25 @@ export class BackendSocket {
}
/** Attach one authenticated loopback desktop client to the same RPC and event plane as cloud web. */
- registerLocalClient(connId: string, sink: LocalClientSink, opts: { tool?: boolean } = {}): boolean {
+ registerLocalClient(connId: string, sink: LocalClientSink, opts: { tool?: boolean; surface?: WindowSurface } = {}): boolean {
if (!isLocalClientId(connId) || this.localClients.has(connId)) return false
this.localClients.set(connId, sink)
- this.gatewayPort?.localClients(this.localClients.size)
- if (opts.tool) { this.toolClients.add(connId); return true }
+ if (opts.tool) this.toolClients.add(connId)
+ else if (opts.surface === 'tui') this.tuiClients.add(connId)
+ this.gatewayPort?.localClients(this.localWindows())
+ if (opts.tool) return true
// The window is the person's session: the backend counts it, now or when the link next comes up.
- this.gatewayPort?.windowOpened()
+ this.gatewayPort?.windowOpened(opts.surface ?? 'desktop')
this.onLocalClient?.(connId, true)
return true
}
+ /** The windows attached now, per surface; tools are not windows. */
+ private localWindows(): LocalWindows {
+ const windows = this.localClients.size - this.toolClients.size
+ return { desktop: windows - this.tuiClients.size, tui: this.tuiClients.size }
+ }
+
/** A loopback client that said it is a tool (`harness pair`, the MCP server), not a window. */
isToolClient(connId: string): boolean { return this.toolClients.has(connId) }
@@ -625,11 +635,12 @@ export class BackendSocket {
async unregisterLocalClient(connId: string): Promise<void> {
if (!this.localClients.delete(connId)) return
if (!this.toolClients.delete(connId)) this.onLocalClient?.(connId, false)
+ this.tuiClients.delete(connId)
this.rowStateWindows.delete(connId)
this.viewerStreams?.closed(connId); this.ownerCommands.closeConnection(connId); this.onConnectionClosed?.(connId)
// The last one leaving before any link could hear it attach: nothing happened, as far as the backend
// is concerned, and the gateway does not tell a later link otherwise.
- this.gatewayPort?.localClients(this.localClients.size)
+ this.gatewayPort?.localClients(this.localWindows())
this.downChains.delete(connId)
await this.terminalStreams?.closeConnection(connId, 'local client disconnected', false)
}
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 8d79df76e..8e8707ab9 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1015,6 +1015,19 @@ export type BackendNotice =
| { type: 'device_keys_changed' }
/** What the core asks of the gateway: everything bound for a remote client, and the link's state. */
+/** What a person has open on this computer: the desktop app, or `harness tui`. Each is its own presence. */
+export type WindowSurface = 'desktop' | 'tui'
+export type LocalWindows = Record<WindowSurface, number>
+export const WINDOW_SURFACES: readonly WindowSurface[] = ['desktop', 'tui']
+/** A surface off the core↔gateway pipe: anything but `tui` is the desktop app. */
+export const windowSurfaceOf = (value: unknown): WindowSurface => (value === 'tui' ? 'tui' : 'desktop')
+/** Window counts off the core↔gateway pipe; anything unreadable is none. */
+export const localWindowsOf = (value: unknown): LocalWindows => {
+ const counts = (value ?? {}) as Partial<Record<WindowSurface, unknown>>
+ const count = (n: unknown): number => (typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.floor(n) : 0)
+ return { desktop: count(counts.desktop), tui: count(counts.tui) }
+}
+
export interface GatewayPort {
/** Dial the backend: this daemon is signed in. */
connect(): void
@@ -1045,9 +1058,10 @@ export interface GatewayPort {
observer(connId: string, type: string, payload: Record<string, unknown>): boolean
/** A window opened on this computer: the backend counts it as the person's session at once, or when
* the link next comes up. */
- windowOpened(): void
- /** How many processes on this computer are attached, windows and tools. */
- localClients(count: number): void
+ windowOpened(surface: WindowSurface): void
+ /** The windows attached on this computer, per surface — tools (`harness pair`, the MCP server) are
+ * not windows and are not counted. */
+ localClients(windows: LocalWindows): void
/** A local connection's request the gateway answers (the E2EE pairings), answered back to it through
* `GatewayEvents.toLocal`. */
local(connId: string, frame: Record<string, unknown>): Promise<void>
diff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.ts
index e2ae96d99..f6154c8d9 100644
--- a/cli/src/core/gatewayLink.spec.ts
+++ b/cli/src/core/gatewayLink.spec.ts
@@ -52,7 +52,7 @@ describe('the gateway in its own process, as the core sees it', () => {
const { link, sent, kinds } = setup()
link.port.connect()
link.port.holdRequests()
- link.port.localClients(2)
+ link.port.localClients({ desktop: 1, tui: 1 })
link.ops.wifiService(true)
link.ops.account({ machineId: 'm1', signIn: null })
link.ops.reachable(['m2'])
@@ -61,7 +61,7 @@ describe('the gateway in its own process, as the core sees it', () => {
expect(kinds()).toEqual(['start'])
expect(sent[0]).toEqual({
kind: 'start', machineId: 'm1', computerId: 'c1', autonomousEnv: 'prod', signedIn: true,
- requestsOpen: false, dial: 'connect', localClients: 2, wifiService: true, reachable: ['m2'],
+ requestsOpen: false, dial: 'connect', localClients: { desktop: 1, tui: 1 }, wifiService: true, reachable: ['m2'],
})
link.port.openRequests()
link.port.serveThisComputerOnly()
@@ -90,7 +90,7 @@ describe('the gateway in its own process, as the core sees it', () => {
expect(link.port.observer('observer:1', 'observer_frame', { b: 2 })).toBe(true)
expect(link.port.device('phone-1', 'autonomous_device_result', { c: 3 })).toBe(true)
link.port.deviceClient('phone-1', 'PUB')
- link.port.windowOpened()
+ link.port.windowOpened('tui')
await link.port.local('local:w', { type: 'e2ee_pairings_list', payload: {} })
expect(link.port.terminalBinary('phone-1', bytesOf('hi'))).toBe(true)
// An id the binary frame cannot carry: refused, never sent half-framed.
diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.ts
index 3737e4719..7a575d279 100644
--- a/cli/src/core/gatewayLink.ts
+++ b/cli/src/core/gatewayLink.ts
@@ -22,7 +22,7 @@ import { decodeTerminalLocal, encodeTerminalLocal } from '../lib/terminalBinary.
import { answerAccountQuery } from './accountQueries.js'
import { LANE_OFF } from './api.js'
import type {
- BackendNotice, GatewayEvents, GatewayOps, GatewayPort, GatewayRefusal, GatewayStatus, HttpAnswer, LaneSeal,
+ BackendNotice, GatewayEvents, LocalWindows, GatewayOps, GatewayPort, GatewayRefusal, GatewayStatus, HttpAnswer, LaneSeal,
RemoteClient, RemoteRole, RemoteTransport, WindowRelay, WindowRelaySession, WindowRelaySink,
} from './api.js'
import type { ServiceFrame } from './serviceLinks.js'
@@ -86,7 +86,7 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
// What the gateway is told again whenever it connects.
let requestsOpen = true
let dial: 'connect' | 'local' | null = null
- let localClients = 0
+ let localClients: LocalWindows = { desktop: 0, tui: 0 }
let wifiService = false
let reachable: string[] | null = null
/** The remote clients the gateway registered, to forget each when it goes. */
@@ -131,8 +131,8 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
return !!bytes && deps.notifyBinary(bytes)
},
observer: (connId, type, payload) => up && linkUp && send('observer', { connId, type, payload }),
- windowOpened: () => { send('windowOpened') },
- localClients: (count) => { localClients = count; send('localClients', { count }) },
+ windowOpened: (surface) => { send('windowOpened', { surface }) },
+ localClients: (windows) => { localClients = windows; send('localClients', { windows }) },
local: async (connId, frame) => { send('localFrame', { connId, frame }) },
device: (connId, type, payload) => reachableClient(connId) && send('device', { connId, type, payload }),
deviceClient: (connId, identity) => { send('deviceClient', { connId, identity }) },
diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.ts
index 4680acae9..278a818b0 100644
--- a/cli/src/gateway/gateway.ts
+++ b/cli/src/gateway/gateway.ts
@@ -14,7 +14,7 @@
* E2EE_REQUIRED. backendSocket.spec.ts and gateway/gateway.spec.ts hold each of them.
*/
import { env } from '../config/env.js'
-import type { GatewayEvents, GatewayPort, RemoteRole, RemoteTransport } from '../core/api.js'
+import { WINDOW_SURFACES, type GatewayEvents, type GatewayPort, type LocalWindows, type RemoteRole, type RemoteTransport, type WindowSurface } from '../core/api.js'
import { deviceDump } from '../lib/autonomous-device/dump.js'
import type { AuthSessionManager } from '../lib/authSession.js'
import { shouldReplayCommander } from '../lib/commanderReplay.js'
@@ -81,7 +81,7 @@ export class RelayGateway implements GatewayPort {
private requestsOpen = true
private openRequestGate: () => void = () => {}
private requestGate: Promise<void> = Promise.resolve()
- private localClientCount = 0
+ private localWindows: LocalWindows = { desktop: 0, tui: 0 }
private readonly directDeviceSinks = new Map<string, (frame: Frame) => void>()
private readonly directDevicePins = new Map<string, string>()
/** The Wi-Fi device sessions whose app said hello to the device service (in the core), by connection:
@@ -121,7 +121,7 @@ export class RelayGateway implements GatewayPort {
status: (connected) => this.core.status(connected),
revoked: () => this.core.revoked(),
busy: () => this.core.busy(),
- localClients: () => this.localClientCount,
+ localClients: () => this.localWindows,
},
})
this.e2ee = new E2eeManager({
@@ -208,11 +208,11 @@ export class RelayGateway implements GatewayPort {
this.openRequestGate()
}
- windowOpened(): void { this.link.sendAppPresence('open') }
+ windowOpened(surface: WindowSurface): void { this.link.sendAppPresence('open', surface) }
- localClients(count: number): void {
- this.localClientCount = count
- if (count === 0) this.link.noLocalClients()
+ localClients(windows: LocalWindows): void {
+ this.localWindows = windows
+ for (const surface of WINDOW_SURFACES) if (windows[surface] === 0) this.link.noLocalClients(surface)
}
// ── out, to remote clients ───────────────────────────────────────────────────────────────────────
diff --git a/cli/src/gateway/gatewayProcess.spec.ts b/cli/src/gateway/gatewayProcess.spec.ts
index 2dce2abfc..46b3d53a3 100644
--- a/cli/src/gateway/gatewayProcess.spec.ts
+++ b/cli/src/gateway/gatewayProcess.spec.ts
@@ -100,7 +100,7 @@ describe('the gateway\'s process, spoken to by the core', () => {
const w = wire()
w.link.port.holdRequests()
w.link.port.connect()
- w.link.port.localClients(1)
+ w.link.port.localClients({ desktop: 1, tui: 2 })
w.link.ops.reachable(['m2'])
w.link.ops.wifiService(true)
expect(w.gateways).toHaveLength(0)
@@ -109,7 +109,7 @@ describe('the gateway\'s process, spoken to by the core', () => {
const [gateway] = w.gateways
expect(w.hosts[0]).toMatchObject({ machineId: 'machine-1', computerId: 'computer-1', autonomousEnv: 'prod', signedIn: true, account: { machineId: 'machine-1', signIn: null } })
expect(gateway.port.holdRequests).toHaveBeenCalled()
- expect(gateway.port.localClients).toHaveBeenCalledWith(1)
+ expect(gateway.port.localClients).toHaveBeenCalledWith({ desktop: 1, tui: 2 })
expect(gateway.ops.reachable).toHaveBeenCalledWith(['m2'])
expect(gateway.ops.wifiService).toHaveBeenCalledWith(true)
expect(gateway.port.connect).toHaveBeenCalled()
@@ -162,7 +162,7 @@ describe('the gateway\'s process, spoken to by the core', () => {
w.link.port.terminal('phone-1', 'terminal_ready', { streamId: STREAM })
w.link.port.terminalBinary('phone-1', clear)
w.link.port.observer('observer:1', 'observer_frame', { b: 2 })
- w.link.port.windowOpened()
+ w.link.port.windowOpened('tui')
await w.link.port.local('local:w', { type: 'e2ee_pairings_list', payload: {} })
w.link.port.device('phone-1', 'autonomous_device_result', { c: 3 })
w.link.port.deviceClient('phone-1', 'P')
@@ -180,7 +180,7 @@ describe('the gateway\'s process, spoken to by the core', () => {
expect(port.terminal).toHaveBeenCalledWith('phone-1', 'terminal_ready', { streamId: STREAM })
expect(port.terminalBinary).toHaveBeenCalledWith('phone-1', clear)
expect(port.observer).toHaveBeenCalledWith('observer:1', 'observer_frame', { b: 2 })
- expect(port.windowOpened).toHaveBeenCalled()
+ expect(port.windowOpened).toHaveBeenCalledWith('tui')
expect(port.local).toHaveBeenCalledWith('local:w', { type: 'e2ee_pairings_list', payload: {} })
expect(port.device).toHaveBeenCalledWith('phone-1', 'autonomous_device_result', { c: 3 })
expect(port.deviceClient.mock.calls).toEqual([['phone-1', 'P'], ['phone-1', null]])
diff --git a/cli/src/gateway/gatewayProcess.ts b/cli/src/gateway/gatewayProcess.ts
index c12ced56e..339dd2b93 100644
--- a/cli/src/gateway/gatewayProcess.ts
+++ b/cli/src/gateway/gatewayProcess.ts
@@ -10,7 +10,7 @@
* and the core going away stops it: a core's restart is the relay's, as it always was, so a remote client
* that kept its socket opens a new session, as it did when both ran in one process.
*/
-import type { GatewayAccount, GatewayEvents, WindowRelaySession } from '../core/api.js'
+import { localWindowsOf, windowSurfaceOf, type GatewayAccount, type GatewayEvents, type WindowRelaySession } from '../core/api.js'
import { decodeGatewayBinary, encodeGatewayBinary, GatewayBinary, GATEWAY_CALLS } from '../lib/gatewayWire.js'
import { RelayConnectError } from '../lib/relayFrames.js'
import { decodeTerminalLocal, encodeTerminalLocal } from '../lib/terminalBinary.js'
@@ -100,7 +100,7 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProces
running = started
// Held first, so that nothing the link brings in is answered before the core is ready.
if (payload.requestsOpen === false) started.port.holdRequests()
- started.port.localClients(Number(payload.localClients) || 0)
+ started.port.localClients(localWindowsOf(payload.localClients))
if (Array.isArray(payload.reachable)) started.ops.reachable(payload.reachable as string[])
if (payload.wifiService === true) started.ops.wifiService(true)
if (payload.dial === 'connect') started.port.connect()
@@ -168,8 +168,8 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProces
case 'target': port.target(connId, text(payload.type), record(payload.payload)); return
case 'terminal': port.terminal(connId, text(payload.type), record(payload.payload)); return
case 'observer': port.observer(connId, text(payload.type), record(payload.payload)); return
- case 'windowOpened': port.windowOpened(); return
- case 'localClients': port.localClients(Number(payload.count) || 0); return
+ case 'windowOpened': port.windowOpened(windowSurfaceOf(payload.surface)); return
+ case 'localClients': port.localClients(localWindowsOf(payload.windows)); return
case 'localFrame': void port.local(connId, record(payload.frame)); return
case 'device': port.device(connId, text(payload.type), record(payload.payload)); return
case 'deviceClient': port.deviceClient(connId, typeof payload.identity === 'string' ? payload.identity : null); return
diff --git a/cli/src/gateway/upstream.ts b/cli/src/gateway/upstream.ts
index 2f35b5660..47d987105 100644
--- a/cli/src/gateway/upstream.ts
+++ b/cli/src/gateway/upstream.ts
@@ -18,6 +18,7 @@
import { WebSocket } from 'ws'
import { hostname } from 'os'
import { env } from '../config/env.js'
+import { WINDOW_SURFACES, type LocalWindows, type WindowSurface } from '../core/api.js'
import { AuthSessionError, AuthSessionManager } from '../lib/authSession.js'
import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from '../lib/wsLiveness.js'
import { decodeTerminalHop, TerminalHopDirection } from '../lib/terminalBinary.js'
@@ -71,9 +72,9 @@ export interface UpstreamEvents {
revoked(): void
/** Another computer already holds this machine (HTTP 409): keep the session, stop for good. */
busy(): void
- /** How many processes on this computer are attached (windows and tools): the window's presence rides
- * the app-ping while there are any. */
- localClients(): number
+ /** The windows attached on this computer, per surface: each one's presence rides the app-ping while
+ * it has any. */
+ localClients(): LocalWindows
}
export interface UpstreamOptions {
@@ -102,11 +103,11 @@ export class UpstreamLink {
private droppedSinceLog = 0
private heartbeat: LivenessWatch | null = null
private appPing: NodeJS.Timeout | null = null
- private lastAppPresenceUpAt = 0
+ private lastAppPresenceUpAt: Record<WindowSurface, number> = { desktop: 0, tui: 0 }
// A window attached while there was no link to tell (cold start: the app dials this daemon before
// the daemon has dialed the backend; or a daemon restart under an open window). The session is
// real and must be counted once, so it is owed to the next link — not turned into a `ping`.
- private appOpenOwed = false
+ private appOpenOwed: Record<WindowSurface, boolean> = { desktop: false, tui: false }
private thisComputerOnly = false
private readonly events: UpstreamEvents
@@ -177,11 +178,15 @@ export class UpstreamLink {
// App-level ping refreshes the backend's presence key (TTL 30s). The window's presence rides
// the same tick — a fresh socket knows nothing about the window, so its first tick goes through.
- this.lastAppPresenceUpAt = 0
- if (this.appOpenOwed && this.events.localClients() > 0) this.sendAppPresence('open')
+ const windows = this.events.localClients()
+ for (const surface of WINDOW_SURFACES) {
+ this.lastAppPresenceUpAt[surface] = 0
+ if (this.appOpenOwed[surface] && windows[surface] > 0) this.sendAppPresence('open', surface)
+ }
this.appPing = setInterval(() => {
this.sendBestEffort({ t: 'ping' })
- if (this.events.localClients() > 0) this.sendAppPresence('ping')
+ const open = this.events.localClients()
+ for (const surface of WINDOW_SURFACES) if (open[surface] > 0) this.sendAppPresence('ping', surface)
}, APP_PING_MS)
})
@@ -283,25 +288,26 @@ export class UpstreamLink {
* window is attached, 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.
+ * Returns whether a frame went up. Each surface is its own presence (the TUI is not the desktop app);
+ * the desktop's frame carries no `surface`, exactly as before it existed.
*/
- sendAppPresence(kind: 'open' | 'ping'): boolean {
+ sendAppPresence(kind: 'open' | 'ping', surface: WindowSurface = 'desktop'): boolean {
const now = Date.now()
- if (kind === 'ping' && now - this.lastAppPresenceUpAt < APP_PRESENCE_UP_MS) return false
+ if (kind === 'ping' && now - this.lastAppPresenceUpAt[surface] < APP_PRESENCE_UP_MS) return false
const sent = this.sendBestEffort({
t: 'up',
webEligible: false,
commanderEligible: false,
- frame: { type: 'app_presence', payload: { kind } },
+ frame: { type: 'app_presence', payload: surface === 'desktop' ? { kind } : { kind, surface } },
})
- if (sent) this.lastAppPresenceUpAt = now
- if (kind === 'open') this.appOpenOwed = !sent
+ if (sent) this.lastAppPresenceUpAt[surface] = now
+ if (kind === 'open') this.appOpenOwed[surface] = !sent
return sent
}
- /** The last window left before any link could hear it attach: nothing happened, as far as the backend
- * is concerned, and a later link must not be told otherwise. */
- noLocalClients(): void { this.appOpenOwed = false }
+ /** The last window of `surface` left before any link could hear it attach: nothing happened, as far
+ * as the backend is concerned, and a later link must not be told otherwise. */
+ noLocalClients(surface: WindowSurface): void { this.appOpenOwed[surface] = false }
enqueue(msg: OutboundEnvelope): void {
if (this.thisComputerOnly) return
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index f639de270..ea26ab5ae 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -22,11 +22,13 @@ class FakeBackend implements LocalWsBackend {
unregisters: string[] = []
focuses: Array<[string, string | null]> = []
tools: string[] = []
+ surfaces: Array<string | undefined> = []
- registerLocalClient(connId: string, sink: LocalClientSink, opts: { tool?: boolean } = {}): boolean {
+ registerLocalClient(connId: string, sink: LocalClientSink, opts: { tool?: boolean; surface?: 'tui' } = {}): boolean {
this.connId = connId
this.sink = sink
if (opts.tool) this.tools.push(connId)
+ this.surfaces.push(opts.surface)
return true
}
async unregisterLocalClient(connId: string): Promise<void> {
@@ -101,6 +103,21 @@ describe('local CLI WebSocket', () => {
raw.destroy()
})
+ it('registers `harness tui` as its own surface, and every other window as the desktop app', async () => {
+ for (const [client, surface] of [['tui', 'tui'], [undefined, undefined], ['desktop', undefined]] as const) {
+ const backend = new FakeBackend()
+ const ws = new WebSocket(await start(backend))
+ await onceOpen(ws)
+ const connected = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, ...(client ? { client } : {}) } }))
+ await connected
+ expect(backend.surfaces).toEqual([surface])
+ ws.close()
+ await local!.close()
+ local = null
+ }
+ })
+
it('keeps notification identities on the local read and snapshot paths', async () => {
const backend = new FakeBackend(), seen = vi.fn(), unread = vi.fn()
const ws = new WebSocket(await start(backend, { onAgentSeen: seen, onAppUnread: unread }))
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 5e3d02d3d..e7e30f978 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -36,7 +36,7 @@ import type { WindowVoiceReply } from './cable/windowRoute.js'
export interface LocalWsBackend {
/** `tool`: `harness pair` or the harnessd MCP server — answered like any local client, never presence. */
- registerLocalClient: (connId: string, sink: LocalClientSink, opts?: { tool?: boolean }) => boolean
+ registerLocalClient: (connId: string, sink: LocalClientSink, opts?: { tool?: boolean; surface?: 'tui' }) => boolean
unregisterLocalClient: (connId: string) => Promise<void>
handleLocalFrame: (connId: string, frame: Frame) => void
handleLocalBinary: (connId: string, frame: TerminalBinaryClear) => Promise<void>
@@ -407,7 +407,9 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
}
if (requestedMachineId === options.machineId) {
tool = payload.tool === true
- if (!options.backend.registerLocalClient(connId, terminalSink, tool ? { tool: true } : {})) {
+ // `harness tui` says so; every other window is the desktop app. Each is its own presence.
+ const registration = tool ? { tool: true } : payload.client === 'tui' ? { surface: 'tui' as const } : {}
+ if (!options.backend.registerLocalClient(connId, terminalSink, registration)) {
close(1011, 'local registration failed')
return
}
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index 2f3e6cc6a..f2e39eef4 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -305,6 +305,9 @@ class WsConn {
'autonomousEnv': autonomousEnv,
if (_directObserver)
(observerLink ? 'link' : 'share'): observerShareId!,
+ // The browser counts its person as on the web today (backend
+ // user_daily_client_presence). Not other viewer builds: they are not the web.
+ if (!_directObserver && kIsWeb) 'client': 'web',
},
);
}
diff --git a/desktop/test/ws_conn_test.dart b/desktop/test/ws_conn_test.dart
index da8635dff..f078ef49f 100644
--- a/desktop/test/ws_conn_test.dart
+++ b/desktop/test/ws_conn_test.dart
@@ -20,6 +20,7 @@ class FakeHub {
final List<Map<String, dynamic>> frames = [];
final List<String> protocols = [];
final List<String?> environments = [];
+ final List<String?> declaredClients = [];
final Map<String, int> machineSelected = {};
final List<WebSocket> clients = [];
Map<String, dynamic> closeResponse = {'activity': 'idle'};
@@ -42,6 +43,7 @@ class FakeHub {
final protocol = request.headers.value('sec-websocket-protocol') ?? '';
hub.protocols.add(protocol);
hub.environments.add(request.uri.queryParameters['autonomousEnv']);
+ hub.declaredClients.add(request.uri.queryParameters['client']);
final ws = await WebSocketTransformer.upgrade(
request,
protocolSelector: (protocols) =>
@@ -213,6 +215,8 @@ void main() {
final result = await conn!.request('agents_list');
expect(hub.protocols, ['access-token']);
expect(hub.environments, ['prod']);
+ // A native build is not the web: no presence surface declared.
+ expect(hub.declaredClients, [null]);
expect(hub.machineSelected['m1'], 1);
expect((result['agents'] as List).first['id'], 'a1');
},
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index d96ffa6f1..477edb7ac 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -268,6 +268,8 @@ class WsConn {
queryParameters: {
...base.queryParameters,
'autonomousEnv': autonomousEnv,
+ // Counts this person as on the mobile app today (backend user_daily_client_presence).
+ 'client': 'mobile',
},
);
final channel = dialing = (connectChannel ?? WebSocketChannel.connect)(
diff --git a/mobile/test/ws/fake_relay.dart b/mobile/test/ws/fake_relay.dart
index 2b6628ffb..b03d250ef 100644
--- a/mobile/test/ws/fake_relay.dart
+++ b/mobile/test/ws/fake_relay.dart
@@ -92,7 +92,11 @@ class FakeRelay {
static Future<FakeRelay> start(E2eeIdentity machineIdentity) async =>
FakeRelay._(machineIdentity);
+ /// Every URL dialled, in order.
+ final dialledUris = <Uri>[];
+
MemoryWebSocket connect(Uri uri, {Iterable<String>? protocols}) {
+ dialledUris.add(uri);
final (client, server) = MemoryWebSocket.pair(
protocol: protocols?.firstOrNull,
);
diff --git a/mobile/test/ws/ws_conn_relay_test.dart b/mobile/test/ws/ws_conn_relay_test.dart
index bc707caad..e40c4a575 100644
--- a/mobile/test/ws/ws_conn_relay_test.dart
+++ b/mobile/test/ws/ws_conn_relay_test.dart
@@ -111,6 +111,11 @@ void main() {
ConnectionStatus.connected,
]);
expect(conn.endpointKey, 'cloud:${relay.url}:test');
+ // Counted as the mobile app today (backend user_daily_client_presence).
+ expect(relay.dialledUris.single.queryParameters, {
+ 'autonomousEnv': 'test',
+ 'client': 'mobile',
+ });
},
);
diff --git a/tui/src/daemon.rs b/tui/src/daemon.rs
index 77802ac6d..fa4b99461 100644
--- a/tui/src/daemon.rs
+++ b/tui/src/daemon.rs
@@ -117,7 +117,8 @@ impl Link {
Err(_) => { emit(MachineEvent::Failed(RpcError::new("TIMEOUT", "the daemon did not answer"))); return }
};
let (mut write, mut read) = ws.split();
- let select = json!({ "type": "machine_select", "payload": { "machineId": id, "localProtocolVersion": 1 } });
+ // `client` makes this its own presence, not the desktop app's (cli localWsServer, backend presence).
+ let select = json!({ "type": "machine_select", "payload": { "machineId": id, "localProtocolVersion": 1, "client": "tui" } });
if write.send(Message::text(select.to_string())).await.is_err() {
emit(MachineEvent::Failed(RpcError::new("DISCONNECTED", "")));
return;