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.

Merge batch 11-04 b0916: #2878 (#2882)

0xken151790cc8baadf
diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.ts
index 1fa20900d..2e315d9e3 100644
--- a/backend/integration/workerIndexPlans.test.ts
+++ b/backend/integration/workerIndexPlans.test.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
import type { PrismaClient } from '@prisma/client'
+import { stableId } from '../src/superTabs/model.js'
import { planDatabase, plan, profiled, reads } from './plans.test-support.js'
// Roadmap Phase 3.7: the worker's hourly people rollup and minute billing sync read through an index that bounds them. A
@@ -9,6 +10,7 @@ import { planDatabase, plan, profiled, reads } from './plans.test-support.js'
let replica: MongoMemoryReplSet
let db: PrismaClient
let rollupPeople: typeof import('../src/services/ProductUsagePeopleRollupService.js')['rollupPeople']
+let turnMark: typeof import('../src/lib/dailyTracking.js')['turnMark']
let billing: typeof import('../src/services/MachineBillingWorkerService.js')['machineBillingWorkerService']
const DAY = 86_400_000
const NOW = Date.parse('2026-10-29T08:00:00Z')
@@ -20,6 +22,7 @@ beforeAll(async () => {
process.env.DATABASE_URL = uri
rollupPeople = (await import('../src/services/ProductUsagePeopleRollupService.js')).rollupPeople
billing = (await import('../src/services/MachineBillingWorkerService.js')).machineBillingWorkerService
+ turnMark = (await import('../src/lib/dailyTracking.js')).turnMark
})
afterAll(async () => {
await (await import('../src/lib/prisma.js')).prisma.$disconnect()
@@ -45,6 +48,51 @@ describe('the hourly people rollup', () => {
})
})
+describe('a turn on a Mac, Swarm agent or own session', () => {
+ // `first`: the terminal it started in, whose id it keeps as its own after a rebind (superTabs/commands.ts agent.rebind).
+ const agentRow = (machineId: string, harnessId: string, deleted: boolean, first = harnessId) => ({ id: randomUUID(), tabId: randomUUID(), key: stableId(machineId, first),
+ version: 1, changedAt: new Date(NOW), deleted, ordinal: 1, data: { harnessId }, machineId, machineOwnerId: 'owner', contributorId: 'owner' })
+
+ it('tells a live Swarm agent from a removed one and from the same session id on another Mac', async () => {
+ await db.swarmAgent.createMany({ data: [agentRow('mac-a', 'live', false), agentRow('mac-a', 'removed', true)] })
+ expect(await turnMark('mac-a', 'live', false)).toEqual({ hosting: true })
+ expect(await turnMark('mac-a', 'removed', false)).toEqual({ worked: true })
+ expect(await turnMark('mac-b', 'live', false)).toEqual({ worked: true })
+ expect(await turnMark('mac-a', 'own-session', false)).toEqual({ worked: true })
+ })
+
+ it('follows a rebound Swarm agent to its current terminal, and leaves the one it left to the owner', async () => {
+ await db.swarmAgent.create({ data: agentRow('mac-r', 'new-terminal', false, 'first-terminal') })
+ expect(await turnMark('mac-r', 'new-terminal', false)).toEqual({ hosting: true })
+ expect(await turnMark('mac-r', 'first-terminal', false)).toEqual({ worked: true })
+ })
+
+ it('reads only the live agents of that machine, by the machine and deleted index', async () => {
+ await db.swarmAgent.createMany({ data: [agentRow('mac-p', 'a', false), agentRow('mac-p', 'one', false), agentRow('mac-p', 'gone', true),
+ ...Array.from({ length: 20 }, (_, i) => agentRow('mac-elsewhere', `other-${i}`, false))] })
+ const entries = await profiled(db, () => turnMark('mac-p', 'one', false))
+ const rows = reads(entries, 'SwarmAgent', ['machineId', 'deleted'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(2)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ machineId: 1, deleted: 1/)
+ })
+
+ it('reads a row from before the hosting mark as not hosting, and a marked one as hosting, in the rollup', async () => {
+ const day = new Date(today - 5 * DAY)
+ const fields = { dayUtc: { $date: day.toISOString() }, surfaces: ['cli'], signupDay: { $date: day.toISOString() }, staff: false,
+ expiresAt: { $date: new Date(day.getTime() + 40 * DAY).toISOString() } }
+ await db.$runCommandRaw({ insert: 'product_usage_activity', documents: [
+ { ...fields, subject: 'before-hosting', worked: true },
+ { ...fields, subject: 'hosting', worked: false, hosting: true },
+ ] })
+ await rollupPeople(new Date(NOW))
+ const total = async (metric: string) => (await db.productUsageTotal.findUnique({ where: { dayUtc_metric: { dayUtc: day, metric } } }))?.value
+ expect(await total('people_hosting')).toBe(1)
+ expect(await total('people_working')).toBe(1)
+ expect(await total('people_active')).toBe(2)
+ })
+})
+
describe('the minute billing sync', () => {
// The (billingStatus, externalSubscriptionStatus, externalSubscriptionEndAt) index serves it although the status is not in the
// filter: Mongo seeks to each status's end-time range, so it reads only the subscriptions it returns, and a few keys per
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 40e9a4a7b..277cccf11 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -580,6 +580,9 @@ model ProductUsageActivity {
dayUtc DateTime
surfaces String[]
worked Boolean @default(false)
+ /// A Swarm agent's turn ran on this person's Mac that day. Not `worked`, which is only their own sessions' turns. Set only when true;
+ /// absent on rows from before 2026-11-04.
+ hosting Boolean?
signupDay DateTime
staff Boolean
expiresAt DateTime
diff --git a/backend/src/analytics/dailyProductPeople.test.ts b/backend/src/analytics/dailyProductPeople.test.ts
index 611e28cb0..f7f7f200d 100644
--- a/backend/src/analytics/dailyProductPeople.test.ts
+++ b/backend/src/analytics/dailyProductPeople.test.ts
@@ -20,3 +20,11 @@ it('reports DAU per day and retention cells with numerator, denominator and imma
expect(p.retention.working.find(c => c.day === '2026-10-11')!.d1).toEqual({ returned: 3, percent: 75 })
expect(p.retention.new.find(c => c.day === '2026-10-11')!.d1).toEqual({ returned: 0, percent: null }) // no denominator
})
+
+it('shows hosting apart from working, and says what working now means', () => {
+ const p = dailyProductPeople([r('2026-10-11', 'people_active', 10), r('2026-10-11', 'people_working', 4), r('2026-10-11', 'people_hosting', 3)],
+ 3, new Date('2026-10-14T01:00:00Z'))
+ expect(p.daily.find(d => d.day === '2026-10-11')).toMatchObject({ working: 4, hosting: 3 })
+ expect(p.definitions.working).toMatch(/own session/)
+ expect(p.definitions.hosting).toMatch(/Swarm agent/)
+})
diff --git a/backend/src/analytics/dailyProductPeople.ts b/backend/src/analytics/dailyProductPeople.ts
index d40c6bffe..2f092d7db 100644
--- a/backend/src/analytics/dailyProductPeople.ts
+++ b/backend/src/analytics/dailyProductPeople.ts
@@ -25,11 +25,12 @@ export function dailyProductPeople(rows: Row[], days: number, now: Date) {
definitions: {
population: 'People whose account shares product usage, staff excluded. A lower bound for all users.',
active: 'Any signed-in client reached Harness that UTC day; an app left open across midnight counts on both days.',
- working: 'At least one agent turn started that day. Prefer working retention: it is not inflated by open apps.',
+ working: 'At least one agent turn their own session started that day. Prefer working retention: it is not inflated by open apps or by Swarm agents on their Mac.',
+ hosting: 'At least one Swarm agent turn ran on a Mac they own that day. A daily count, with no returns.',
returns: 'Dn: in the cohort on day C and back on C+n (same surface for a surface cohort). null until C+n has ended.',
},
daily: dayList.filter(day => get(day, 'people_active') !== null).map(day => ({
- day, active: get(day, 'people_active'), working: get(day, 'people_working'), new: get(day, 'people_new'),
+ day, active: get(day, 'people_active'), working: get(day, 'people_working'), hosting: get(day, 'people_hosting'), new: get(day, 'people_new'),
staff: get(day, 'people_staff_active'),
surfaces: Object.fromEntries(ACTIVITY_SURFACES.map(s => [s, get(day, `people_active_${s}`)])),
})),
diff --git a/backend/src/analytics/peopleCounters.test.ts b/backend/src/analytics/peopleCounters.test.ts
index b0d842f37..8aa0ebd65 100644
--- a/backend/src/analytics/peopleCounters.test.ts
+++ b/backend/src/analytics/peopleCounters.test.ts
@@ -63,3 +63,34 @@ it('never rewrites a day whose marks may be expiring, so its totals cannot shrin
expect(Object.keys(c).filter(k => k.startsWith('2026-10-01:'))).toEqual([])
expect(c['2026-10-02:people_active']).toBe(1) // C+9 is the last day C=10-02 is rewritten
})
+
+// A Swarm agent's turn on someone's Mac is hosting, never that person working (Dee, 2026-11-04).
+it('counts hosting apart from working, with no returns of its own, and staff apart', () => {
+ const c = asMap(peopleCounters([
+ m('host', '2026-10-10', { hosting: true }),
+ m('both', '2026-10-10', { hosting: true, worked: true }),
+ m('own', '2026-10-10', { worked: true }),
+ m('old', '2026-10-10', { hosting: null }),
+ m('staff', '2026-10-10', { hosting: true, staff: true }),
+ ], new Date('2026-10-12T10:00:00Z')))
+ expect(c['2026-10-10:people_hosting']).toBe(2)
+ expect(c['2026-10-10:people_working']).toBe(2)
+ expect(c['2026-10-10:people_active']).toBe(4)
+ expect(c['2026-10-10:people_hosting_d1_returned']).toBeUndefined()
+ expect(PEOPLE_METRICS).toContain('people_hosting')
+})
+
+it('takes a day of hosting alone as no working return, in D1 or D7, and still an active one', () => {
+ const marks = [
+ m('a', '2026-10-01', { worked: true }), m('b', '2026-10-01', { worked: true }),
+ m('a', '2026-10-02', { worked: true }), m('b', '2026-10-02', { hosting: true }),
+ m('a', '2026-10-08', { hosting: true }), m('b', '2026-10-08', { worked: true }),
+ m('h', '2026-10-01', { hosting: true }), m('h', '2026-10-02', { worked: true }), m('h', '2026-10-08', { worked: true }),
+ ]
+ const c = asMap(peopleCounters(marks, new Date('2026-10-09T00:30:00Z')))
+ expect(c['2026-10-01:people_working']).toBe(2)
+ expect(c['2026-10-01:people_working_d1_returned']).toBe(1)
+ expect(c['2026-10-01:people_working_d7_returned']).toBe(1)
+ expect(c['2026-10-01:people_active_d1_returned']).toBe(3)
+ expect(c['2026-10-01:people_active_d7_returned']).toBe(3)
+})
diff --git a/backend/src/analytics/peopleCounters.ts b/backend/src/analytics/peopleCounters.ts
index 6d26b9547..665ec33ff 100644
--- a/backend/src/analytics/peopleCounters.ts
+++ b/backend/src/analytics/peopleCounters.ts
@@ -2,12 +2,12 @@ import { ACTIVITY_DAYS, ACTIVITY_SURFACES } from '../types/productUsageActivity.
const DAY = 86_400_000
export const PEOPLE_RETURN_DAYS = [1, 2, 3, 7] as const
-export interface ActivityMark { subject: string; dayUtc: Date; surfaces: string[]; worked: boolean; signupDay: Date; staff: boolean }
+export interface ActivityMark { subject: string; dayUtc: Date; surfaces: string[]; worked: boolean; hosting?: boolean | null; signupDay: Date; staff: boolean }
type Counter = { day: string; metric: string; value: number }
const KINDS = ['active', 'working', 'new', ...ACTIVITY_SURFACES.map(s => `active_${s}`)] as const
export const PEOPLE_METRICS: readonly string[] = [
- 'people_active', 'people_working', 'people_new', 'people_staff_active',
+ 'people_active', 'people_working', 'people_hosting', 'people_new', 'people_staff_active',
...ACTIVITY_SURFACES.map(s => `people_active_${s}`),
...KINDS.flatMap(kind => PEOPLE_RETURN_DAYS.map(n => `people_${kind}_d${n}_returned`)),
]
@@ -17,16 +17,17 @@ const dayKey = (d: Date) => d.toISOString().slice(0, 10)
/** Distinct people per ended UTC day and their D1/D2/D3/D7 returns. Staff count only as staff. */
export function peopleCounters(marks: ActivityMark[], now: Date): Counter[] {
const today = Math.floor(now.getTime() / DAY) * DAY
- type Person = { surfaces: Set<string>; worked: boolean; isNew: boolean }
+ type Person = { surfaces: Set<string>; worked: boolean; hosting: boolean; isNew: boolean }
const byDay = new Map<number, Map<string, Person>>()
const staffByDay = new Map<number, Set<string>>()
for (const mark of marks) {
const day = Math.floor(mark.dayUtc.getTime() / DAY) * DAY
if (mark.staff) { (staffByDay.get(day) ?? staffByDay.set(day, new Set()).get(day)!).add(mark.subject); continue }
const people = byDay.get(day) ?? byDay.set(day, new Map()).get(day)!
- const person = people.get(mark.subject) ?? { surfaces: new Set<string>(), worked: false, isNew: false }
+ const person = people.get(mark.subject) ?? { surfaces: new Set<string>(), worked: false, hosting: false, isNew: false }
for (const s of mark.surfaces) person.surfaces.add(s)
person.worked ||= mark.worked
+ person.hosting ||= mark.hosting === true
person.isNew ||= Math.floor(mark.signupDay.getTime() / DAY) * DAY === day
people.set(mark.subject, person)
}
@@ -43,6 +44,8 @@ export function peopleCounters(marks: ActivityMark[], now: Date): Counter[] {
const count = (kind: string) => [...people.values()].filter(p => inKind(p, kind)).length
out.push({ day: key, metric: 'people_active', value: people.size })
out.push({ day: key, metric: 'people_working', value: count('working') })
+ // One daily count, with no returns: hosting says a Mac ran Swarm agents, not that a person came back.
+ out.push({ day: key, metric: 'people_hosting', value: [...people.values()].filter(p => p.hosting).length })
out.push({ day: key, metric: 'people_new', value: count('new') })
out.push({ day: key, metric: 'people_staff_active', value: staffByDay.get(day)?.size ?? 0 })
for (const s of ACTIVITY_SURFACES) out.push({ day: key, metric: `people_active_${s}`, value: count(`active_${s}`) })
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 8d11a36ea..a5c31edc2 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -567,7 +567,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
const now = new Date()
const agentId = typeof f.agentId === 'string' && TURN_AGENT_ID_RE.test(f.agentId) ? f.agentId : undefined
if (agentId && allowTurnWrite(now.getTime())) {
- void recordTurnStarted(userId, machineId, agentId, now)
+ void recordTurnStarted(userId, machineId, agentId, now, team)
.catch((err) => logger.warn('turn tracking failed', { machineId, agentId, error: String(err) }))
}
}
diff --git a/backend/src/lib/dailyTracking.test.ts b/backend/src/lib/dailyTracking.test.ts
index 3bdb23fe1..62295e467 100644
--- a/backend/src/lib/dailyTracking.test.ts
+++ b/backend/src/lib/dailyTracking.test.ts
@@ -2,13 +2,17 @@ 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())
+const swarmAgentFind = vi.hoisted(() => vi.fn())
+const warn = vi.hoisted(() => vi.fn())
vi.mock('./productUsage.js', () => ({ recordRelayUsage: record, markActivity: mark }))
-vi.mock('./prisma.js', () => ({ prisma: { machine: { update: machineUpdate } } }))
+vi.mock('./prisma.js', () => ({ prisma: { machine: { update: machineUpdate }, swarmAgent: { aggregateRaw: swarmAgentFind } } }))
+vi.mock('../utils/logger.js', () => ({ logger: { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
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)
machineUpdate.mockReset(); machineUpdate.mockResolvedValue({})
+ swarmAgentFind.mockReset(); swarmAgentFind.mockResolvedValue([]); warn.mockReset()
})
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')
@@ -202,3 +206,42 @@ it('keeps Harness OS and Orange Pi connections separate without storing identity
['account', now, 'relay_harness-os_opens'], ['account', now, 'relay_harness-os-pi_opens'],
])
})
+
+// A Swarm agent's turn on someone's Mac is hosting, never that person working (Dee, 2026-11-04).
+describe('a turn is marked by who started it', () => {
+ const now = new Date('2026-11-04T12:00:00Z')
+
+ it('marks an own session\'s turn as worked', async () => {
+ await recordTurnStarted('owner', 'mac', 'own-session', now)
+ expect(mark.mock.calls).toEqual([['owner', now, { worked: true }]])
+ })
+
+ it('marks a Swarm agent\'s turn as hosting, not worked, found by its machine and current terminal', async () => {
+ swarmAgentFind.mockResolvedValue([{ _id: 'row' }])
+ await recordTurnStarted('owner', 'mac', 'swarm-session', now)
+ expect(mark.mock.calls).toEqual([['owner', now, { hosting: true }]])
+ expect(swarmAgentFind.mock.calls[0]![0].pipeline[0]).toEqual({ $match: { machineId: 'mac', deleted: false, 'data.harnessId': 'swarm-session' } })
+ })
+
+ it('marks a Team account\'s turn as hosting without reading anything: it runs only Swarm agents', async () => {
+ await recordTurnStarted('owner', 'team-mac', 'any', now, true)
+ expect(mark.mock.calls).toEqual([['owner', now, { hosting: true }]])
+ expect(swarmAgentFind).not.toHaveBeenCalled()
+ })
+
+ it('marks neither when it cannot tell, says so without ids, and still counts the turn', async () => {
+ swarmAgentFind.mockRejectedValue(new Error('down'))
+ await expect(recordTurnStarted('PRIVATE_OWNER', 'PRIVATE_MACHINE', 'PRIVATE_AGENT', now)).resolves.toBeUndefined()
+ expect(mark).not.toHaveBeenCalled()
+ expect(record.mock.calls.map(c => c[2])).toEqual(['relay_turns_started'])
+ expect(warn).toHaveBeenCalledOnce()
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('PRIVATE_')
+ })
+
+ it('counts the turn in the relay total whichever mark it gets', async () => {
+ swarmAgentFind.mockResolvedValue([{ _id: 'row' }])
+ await recordTurnStarted('owner', 'mac', 'swarm-session', now)
+ await recordTurnStarted('owner', 'team-mac', 'any', now, true)
+ expect(record.mock.calls.map(c => c[2])).toEqual(['relay_turns_started', 'relay_turns_started'])
+ })
+})
diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.ts
index 7ebf3bb3d..ea3e83e5d 100644
--- a/backend/src/lib/dailyTracking.ts
+++ b/backend/src/lib/dailyTracking.ts
@@ -8,6 +8,7 @@ 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'
+import { logger } from '../utils/logger.js'
export interface PresenceTouchOpts { isNewConnection: boolean; countryCode?: string }
@@ -31,9 +32,23 @@ export async function touchMachineOnlineDay(userId: string, machineId: string, n
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(() => {})
- await recordRelayUsage(userId, now, 'relay_turns_started')
+/** Which daily mark a turn sets: `worked` is only the person's own sessions' turns; a Swarm agent's turn on their Mac is
+ * `hosting` (Dee, 2026-11-04). A Swarm agent is found by its machine and current terminal, not its id: a rebound one keeps
+ * the id of its first terminal (superTabs/commands.ts agent.rebind). A removed one, or a terminal one left, is only the
+ * owner's session now. A Team account runs only Swarm agents, so its turns read nothing. */
+export async function turnMark(machineId: string, agentId: string, team: boolean): Promise<{ worked: true } | { hosting: true }> {
+ if (team) return { hosting: true }
+ // A plain $match: Prisma has no filter inside `data`. Reads only this machine's live agents ([machineId, deleted]).
+ const rows = await prisma.swarmAgent.aggregateRaw({ pipeline: [{ $match: { machineId, deleted: false, 'data.harnessId': agentId } }, { $limit: 1 }, { $project: { _id: 1 } }] }) as unknown as unknown[]
+ return rows.length ? { hosting: true } : { worked: true }
+}
+export async function recordTurnStarted(userId: string, machineId: string, agentId: string, now: Date, team = false): Promise<void> {
+ // Started together: a failed read costs this turn's mark, never its total. Neither mark when it cannot tell whose turn it is.
+ await Promise.all([
+ turnMark(machineId, agentId, team).then(mark => markActivity(userId, now, mark))
+ .catch(err => logger.warn('turn mark skipped: could not read whose turn it is; this turn counts in no person\'s day', { error: String(err) })),
+ recordRelayUsage(userId, now, 'relay_turns_started'),
+ ])
}
/** Last SUCCESSFUL presence write for one open socket — `dayKey` null until the first one lands. */
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index 5eea1ed12..10b6b12a3 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -636,6 +636,25 @@ describe('activity marks', () => {
expect(db.productUsageActivity.upsert.mock.calls[2][0].update).toEqual({ worked: true })
})
+ it('writes a hosting mark on the same row, apart from worked, leaving worked unset', async () => {
+ await markActivity('a', at, { hosting: true }, KEY)
+ const call = db.productUsageActivity.upsert.mock.calls[0][0]
+ expect(call.update).toEqual({ hosting: true })
+ expect(call.create).toMatchObject({ hosting: true, worked: false, surfaces: [] })
+ })
+
+ it('writes both marks for a person with both kinds of turn in a day, each once', async () => {
+ for (let i = 0; i < 2; i++) await markActivity('a', at, { hosting: true }, KEY)
+ for (let i = 0; i < 2; i++) await markActivity('a', at, { worked: true }, KEY)
+ expect(db.productUsageActivity.upsert.mock.calls.map(c => c[0].update)).toEqual([{ hosting: true }, { worked: true }])
+ })
+
+ it('writes no hosting mark while sharing is off', async () => {
+ db.productUsagePreference.findUnique.mockResolvedValue({ enabled: false, revision: 3 })
+ await markActivity('a', at, { hosting: true }, KEY)
+ expect(db.productUsageActivity.upsert).not.toHaveBeenCalled()
+ })
+
it('starts a new day at UTC midnight', async () => {
await markActivity('a', new Date('2026-10-13T23:59:59.999Z'), { surface: 'web' }, KEY)
await markActivity('a', new Date('2026-10-14T00:00:00.000Z'), { surface: 'web' }, KEY)
diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.ts
index 098d2a585..470bf4743 100644
--- a/backend/src/lib/productUsage.ts
+++ b/backend/src/lib/productUsage.ts
@@ -278,24 +278,24 @@ export function resetActivityMarksForTests(): void { marked.clear(); markedDay =
let activityWarnedAt = 0
/** Fire-and-forget from the relay touch points; never awaited by a socket, never throws. */
-export async function markActivity(userId: string, now: Date, mark: { surface?: ActivitySurface; worked?: boolean },
+export async function markActivity(userId: string, now: Date, mark: { surface?: ActivitySurface; worked?: boolean; hosting?: boolean },
key: string = env.PRODUCT_USAGE_SUBJECT_KEY): Promise<void> {
- if (!key || (!mark.surface && !mark.worked)) return
+ if (!key || (!mark.surface && !mark.worked && !mark.hosting)) return
try {
const dayUtc = new Date(Math.floor(now.getTime() / DAY) * DAY)
const day = dayUtc.toISOString().slice(0, 10)
if (day !== markedDay) { marked.clear(); markedDay = day }
const subject = activitySubject(userId, key)
- const seen = `${subject}|${mark.surface ?? ''}|${mark.worked ? 'w' : ''}`
+ const seen = `${subject}|${mark.surface ?? ''}|${mark.worked ? 'w' : ''}|${mark.hosting ? 'h' : ''}`
if (marked.has(seen)) return
if (!(await productUsageChoice(userId)).enabled) return
const user = await prisma.user.findUnique({ where: { id: userId }, select: { createdAt: true, email: true } })
if (!user) return
const where = { subject_dayUtc: { subject, dayUtc } }
- const update = { ...(mark.surface ? { surfaces: { push: mark.surface } } : {}), ...(mark.worked ? { worked: true } : {}) }
+ const update = { ...(mark.surface ? { surfaces: { push: mark.surface } } : {}), ...(mark.worked ? { worked: true } : {}), ...(mark.hosting ? { hosting: true } : {}) }
try {
await prisma.productUsageActivity.upsert({ where, update, create: {
- subject, dayUtc, surfaces: mark.surface ? [mark.surface] : [], worked: mark.worked === true,
+ subject, dayUtc, surfaces: mark.surface ? [mark.surface] : [], worked: mark.worked === true, ...(mark.hosting ? { hosting: true } : {}),
signupDay: new Date(Math.floor(user.createdAt.getTime() / DAY) * DAY),
staff: user.email.toLowerCase().endsWith(STAFF_EMAIL),
expiresAt: new Date(dayUtc.getTime() + ACTIVITY_DAYS * DAY),
diff --git a/backend/src/lib/teamSessionSockets.test.ts b/backend/src/lib/teamSessionSockets.test.ts
index 1c3d547be..f1aeee2fe 100644
--- a/backend/src/lib/teamSessionSockets.test.ts
+++ b/backend/src/lib/teamSessionSockets.test.ts
@@ -9,7 +9,7 @@ const m = vi.hoisted(() => ({
machineService: { resolveOrCreateForComputer: vi.fn(), resolveForTeamComputer: vi.fn() },
machineUpdate: vi.fn(), machineFindUnique: vi.fn(), userFindUnique: vi.fn(),
claim: vi.fn(), release: vi.fn(), publishUp: vi.fn(), publishPair: vi.fn(), terminalDown: vi.fn(),
- pushes: vi.fn(), appendKey: vi.fn(), nodeRole: vi.fn(),
+ pushes: vi.fn(), appendKey: vi.fn(), nodeRole: vi.fn(), recordTurn: vi.fn(),
}))
vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))
vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))
@@ -34,7 +34,7 @@ vi.mock('./hub.js', () => ({
}))
vi.mock('./dailyTracking.js', async original => ({ ...await original<typeof import('./dailyTracking.js')>(),
touchMachineOnlineDay: vi.fn(async () => {}), touchUserOnlineDay: vi.fn(async () => {}), touchClientOnlineDay: vi.fn(async () => {}),
- recordTurnStarted: vi.fn(async () => {}) }))
+ recordTurnStarted: m.recordTurn }))
import { handleAdapterUpgrade } from './adapterWs.js'
import { handleWebUpgrade } from './webWs.js'
@@ -73,6 +73,7 @@ beforeEach(() => {
m.publishUp.mockResolvedValue(undefined)
m.appendKey.mockResolvedValue({ ok: true, head: { seq: 1, hash: 'h' } })
m.nodeRole.mockResolvedValue({ touch: vi.fn(), detach: vi.fn(async () => {}) })
+ m.recordTurn.mockResolvedValue(undefined)
m.machineService.resolveForTeamComputer.mockResolvedValue({ machine: teamMac, created: false })
m.upgrade.mockReset()
m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: ownerMac, created: false })
@@ -106,6 +107,19 @@ describe('the machine socket and a team session', () => {
expect(m.upgrade).toHaveBeenCalledTimes(1)
})
+ it('tells the turn tracking a team session\'s turn from a normal sign-in\'s', async () => {
+ const turnOn = async (user: AuthUser, computer: string) => {
+ m.auth.mockResolvedValue(user)
+ const ws = new Socket()
+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))
+ handleAdapterUpgrade(adapter(computer) as never, raw() as never, Buffer.alloc(0)); await flush()
+ ws.frame({ t: 'up', frame: { type: 'turn_started', agentId: 'agent-1', payload: {} } }); await flush()
+ return m.recordTurn.mock.calls.at(-1)!
+ }
+ expect(await turnOn(team, TEAM_COMPUTER)).toEqual(['owner', 'team-mac', 'agent-1', expect.any(Date), true])
+ expect(await turnOn(owner, OWNER_COMPUTER)).toEqual(['owner', 'owner-mac', 'agent-1', expect.any(Date), false])
+ })
+
it('refuses it when its computer\'s machine is one a normal sign-in holds', async () => {
m.auth.mockResolvedValue(team)
m.machineService.resolveForTeamComputer.mockRejectedValue(new AppError('held', 403, 'TEAM_SESSION_LIMITED'))
diff --git a/backend/src/services/ProductUsagePeopleRollupService.test.ts b/backend/src/services/ProductUsagePeopleRollupService.test.ts
index c649c0c10..66b8c9e72 100644
--- a/backend/src/services/ProductUsagePeopleRollupService.test.ts
+++ b/backend/src/services/ProductUsagePeopleRollupService.test.ts
@@ -18,3 +18,12 @@ it('reads only the live window of marks and writes totals with $set, never $inc'
})
expect(JSON.stringify(db.productUsageTotal.upsert.mock.calls)).not.toContain('"x"')
})
+
+it('reads the hosting mark and writes its total', async () => {
+ db.productUsageActivity.findMany.mockResolvedValue([
+ { subject: 'x', dayUtc: new Date('2026-10-12'), surfaces: [], worked: false, hosting: true, signupDay: new Date('2026-09-01'), staff: false },
+ ])
+ await rollupPeople(new Date('2026-10-14T05:00:00Z'))
+ expect(db.productUsageActivity.findMany.mock.calls[0][0].select).toMatchObject({ hosting: true })
+ expect(db.productUsageTotal.upsert).toHaveBeenCalledWith(expect.objectContaining({ create: { dayUtc: new Date('2026-10-12'), metric: 'people_hosting', value: 1 } }))
+})
diff --git a/backend/src/services/ProductUsagePeopleRollupService.ts b/backend/src/services/ProductUsagePeopleRollupService.ts
index d4c6e7f10..5a13ee5a6 100644
--- a/backend/src/services/ProductUsagePeopleRollupService.ts
+++ b/backend/src/services/ProductUsagePeopleRollupService.ts
@@ -13,7 +13,7 @@ export async function rollupPeople(now = new Date()): Promise<number> {
// ponytail: reads every mark in that window (≤ people × 9 days); use an aggregation pipeline past ~100k rows.
const marks = await prisma.productUsageActivity.findMany({
where: { dayUtc: { gte: new Date(today - (ACTIVITY_DAYS - 1) * DAY) } },
- select: { subject: true, dayUtc: true, surfaces: true, worked: true, signupDay: true, staff: true },
+ select: { subject: true, dayUtc: true, surfaces: true, worked: true, hosting: true, signupDay: true, staff: true },
})
const counters = peopleCounters(marks, now)
for (const { day, metric, value } of counters) {
diff --git a/docs/plans/2026-11-04-own-runs-vs-hosting-plan.md b/docs/plans/2026-11-04-own-runs-vs-hosting-plan.md
new file mode 100644
index 000000000..ce22b93da
--- /dev/null
+++ b/docs/plans/2026-11-04-own-runs-vs-hosting-plan.md
@@ -0,0 +1,94 @@
+# Own agent runs vs hosting Swarm agents: implementation plan
+
+The Engineer implements this plan task by task, test first, on one branch, and opens one pull request. Nobody is asked to
+choose an execution mode. Steps use checkboxes.
+
+**Goal:** `people_working` and its returns count only agent turns a person's own sessions started. A Swarm agent's turn on
+their Mac sets a separate hosting mark, counted once a day as `people_hosting`.
+
+**Architecture:** A turn's agent is a Swarm agent when a live `SwarmAgent` row on that machine has it as its current terminal
+(`data.harnessId`), or when the turn comes from a Mac's Team account, which runs only Swarm agents. The agent's id will not
+do: a rebound agent keeps the id of its first terminal (review of this plan's first version). `recordTurnStarted` picks the mark from
+that, and `markActivity` writes it on the person's existing 10-day activity row. The rollup counts the new mark and keeps
+it out of `worked`.
+
+**Tech Stack:** TypeScript, Prisma on MongoDB, Vitest. Integration plans on `mongodb-memory-server`.
+
+**Spec:** task #2574's brief.
+
+## Global Constraints
+
+- Same privacy as today: hashed subjects, 10-day expiry, staff kept apart, aggregates only.
+- No change to presence or to the `active` mark.
+- No migration: old rows simply have no hosting mark.
+- Ships with the next backend release.
+- PR body first line: `Requested by [email protected] through Harness.`
+
+## Review Focus
+
+- A lookup that fails: credits neither mark, warns, and still counts the turn in the relay total.
+- A removed Swarm agent's tombstone: reads as not a Swarm agent, since the session on the Mac is now only the owner's.
+- The same session id on another machine: not a Swarm agent, since the read is by machine.
+- A rebound Swarm agent: hosting on its current terminal; the terminal it left is only the owner's session.
+- An old row with no `hosting` field: the rollup reads it as not hosting.
+- A person with both kinds of turn in a day: marked for both, because the once-a-day memory keeps the two marks apart.
+
+## Design
+
+- **Growth:** one optional field on `product_usage_activity`, written only when true (about 13 bytes on an average 367-byte
+ row). The existing 10-day TTL removes it, and `people_hosting` adds one row a day to `product_usage_totals`, which keeps
+ its existing expiry. 1,255 activity rows and 461 KB in production on 2026-11-04.
+- **Concurrency:** the same single-row upsert as every activity mark. Marks only ever set a field to true, so races agree.
+- **Read cost:** one indexed `SwarmAgent` read by `[machineId, deleted]` per counted turn, examining only that machine's live
+ agents. Team-account turns read nothing. Production has 10–12k turns a day, about 0.14 a second, and each already writes a
+ relay total.
+- **Scale:** at 10x, about 1.4 reads a second, each bounded by one machine's agents. The metric that warns first is backend Mongo read
+ latency. The rate cap per socket (`allowTurnWrite`) still bounds a looping machine.
+- **Compatibility:** no client changes; the frame's `agentId` is what the backend already reads. Older pods during a rollout
+ keep writing `worked`, which only prolongs today's behavior for those turns. `usage:daily` gains a `hosting` field.
+- **Migration + rollback:** none needed. An old server ignores the field. Turns marked hosting while the new server ran stay
+ uncounted as working for up to 10 days, and that is correct.
+- **Audience:** aggregates only, read as the people totals are today. The mark carries no machine or agent.
+- **Identity:** the mark is on the Mac's owner, as today, under the keyed pseudonym; hosting is the fact it now records.
+- **Failure:** a failed lookup writes no mark for that turn and logs a warning without ids. The relay total still counts it.
+- **Platforms:** backend only.
+
+## Known limits
+
+- Days marked before the release keep their inflated `worked`: old rows cannot be told apart. For 7 days after the release,
+ returns compare an old cohort with a stricter later day, so working returns dip for a reason that is not behavior. Compare
+ working returns only for cohorts that start after the release.
+- A person's own session that they shared into a Swarm, and a Buddy, are live `SwarmAgent` rows, so their turns count as
+ hosting. This errs toward a lower working number.
+- A hosting-only row still counts in `people_active`, as the brief asks: no change to the active mark. In production, 3–7 rows
+ a day have no surface at all, which bounds how many such people exist today.
+
+---
+
+### Task 1: The rollup counts hosting apart
+
+**Files:**
+- Modify: `backend/prisma/schema.prisma`, `backend/src/analytics/peopleCounters.ts`, `backend/src/analytics/dailyProductPeople.ts`, `backend/src/services/ProductUsagePeopleRollupService.ts`
+- Test: `backend/src/analytics/peopleCounters.test.ts`, `backend/src/analytics/dailyProductPeople.test.ts`, `backend/src/services/ProductUsagePeopleRollupService.test.ts`
+
+**Interfaces:**
+- Produces: `ActivityMark.hosting?: boolean | null`, the metric `people_hosting`, and `hosting` on each `usage:daily` row.
+
+- [x] Write failing tests: a hosting-only person is not working and counts in `people_hosting`; staff stay apart; a worked day followed by a hosting-only day is no D1 working return but is a D1 active return.
+- [x] Run them and watch them fail; commit.
+- [x] Add the field, the count, the rollup's select and the definitions; run them green; commit.
+
+### Task 2: The mark and the turn path
+
+**Files:**
+- Modify: `backend/src/lib/productUsage.ts`, `backend/src/lib/dailyTracking.ts`, `backend/src/lib/adapterWs.ts`
+- Test: `backend/src/lib/productUsage.test.ts`, `backend/src/lib/dailyTracking.test.ts`, `backend/src/lib/adapterRoutes.test.ts`, `backend/integration/workerIndexPlans.test.ts`
+
+**Interfaces:**
+- Consumes: the `hosting` field from Task 1.
+- Produces: `markActivity(userId, now, { surface?, worked?, hosting? })`, `turnMark(machineId, agentId, team): Promise<{ worked: true } | { hosting: true }>`, `recordTurnStarted(userId, machineId, agentId, now, team = false)`.
+
+- [x] Write failing tests for each Review Focus line, the Swarm-turn and own-turn cases, the adapter passing `team`, and the read's plan (`IXSCAN` on `machineId, deleted`).
+- [x] Run them and watch them fail; commit.
+- [x] Implement; run them green; commit.
+- [x] Run `npm test`; post red/green in a PR comment; mark the PR ready; add one review step.
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 4e4cf1fe5..3f1390394 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -53,7 +53,7 @@ their separate flow identifies the card. Openings measure dialogs, pairing count
and neither proves that the phone subsequently used a harness.
| Is measurement losing coverage? | Updated collector installation-days, pruned queues, full observation maps, unmatched app starts | Loss signals warrant caution. No signal does not prove complete collection. |
-| How many people use Harness, and do they come back? | People active / working / new per day and per app, and D1/D2/D3/D7 returns (backend rollup of 10-day pseudonymous marks) | Sharing accounts only, staff excluded; an app open across midnight counts on both days, so prefer working returns. Not available before `PRODUCT_USAGE_SUBJECT_KEY` is set. |
+| How many people use Harness, and do they come back? | People active / working / new per day and per app, and D1/D2/D3/D7 returns; people hosting Swarm agents as one daily count (backend rollup of 10-day pseudonymous marks) | Sharing accounts only, staff excluded; an app open across midnight counts on both days, so prefer working returns. Working counts only turns the person's own sessions started, since the backend release after 2026-11-04: compare working returns only for cohorts that start after it. A session shared into a Swarm, and a Buddy, count as hosting. Not available before `PRODUCT_USAGE_SUBJECT_KEY` is set. |
| What do people do on the Hub? | Page views by page and signed-out/signed-in reader, the first page of a tab's visit by where it came from (direct, search, social, internal, other; classified in the browser, the referrer is never sent), clicks and submits (search, sort, like, comment, share, fork, follow, report, sign-in prompt, publish), and how long a harness page stayed visible (under 10 s, 10 s–1 min, over 1 min). A shared link (`/s/:id`, the web app) counts the same way: the page drawn by reader, what it showed (live, owner offline, private, no access, failed), how long a live harness stayed visible, and its clicks (comments, comment posted, sign-in, retry, Download app, product page), plus once when its live viewer draws | Unlinked daily totals of views, entries, clicks and dwell buckets: not people, not a funnel. Public counts that can be fabricated; directional only. Browsers sending Global Privacy Control or Do Not Track, and signed-in readers who turned sharing off, are not counted. The website's server strips cookies and auth before forwarding. |
Desktop setup and sign-in counts are enabled by default, with no onboarding checkbox. Desktop has