The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Hub: count what readers do, and fix what the review found (#1409)
Jacob Pham6acbd7a054c6
diff --git a/backend/README.md b/backend/README.mdindex 9a361a7b5..4fee69d47 100644--- a/backend/README.md+++ b/backend/README.md@@ -311,7 +311,10 @@ mix, completion rate, runtime, or token cost.The expanded measurement contract adds fixed app-flow and feature-use counts, D28 and calendar-monthinstallation returns, and voluntary task outcomes. Native signed-out setup is a separate explicitsession opt-in at `POST /api/product-usage/setup`; it rejects credentials and arbitrary fields and-has a process-wide admission budget without storing IP addresses. Web signed-out reporting is disabled.+has a process-wide admission budget without storing IP addresses. Web app signed-out setup reporting+is disabled. Anonymous Hub totals arrive at `POST /api/product-usage/hub`, forwarded by the website's+server without cookies or auth; the route accepts only the Hub vocabulary (`src/lib/hubMetricsContract.ts`)+and has its own admission budget.Daily reports keep these populations separate, show unmatched outcomes and measurement loss, andcompare only mature periods. See [measurement definitions and runtime bounds](../docs/product-measurement.md).Deploy this additive allowlist before releasing the new clients. This change does not add identitydiff --git a/backend/src/analytics/dailyHubUsage.test.ts b/backend/src/analytics/dailyHubUsage.test.tsnew file mode 100644index 000000000..f32926b0f--- /dev/null+++ b/backend/src/analytics/dailyHubUsage.test.ts@@ -0,0 +1,38 @@+import { expect, it } from 'vitest'+import { dailyHubUsage } from './dailyHubUsage.js'+const r = (day: string, metric: string, value: number) => ({ dayUtc: new Date(day), metric, value })+const now = new Date('2026-10-14T01:00:00Z')++it('says the Hub is not collected, and keeps a day without reports null instead of zero', () => {+ const hub = dailyHubUsage([r('2026-10-13', 'turns_started', 3), r('2026-10-13', 'setup_desktop_sign_in_ok', 1)], 2, now)+ expect(hub.status).toBe('not collected')+ expect(hub.daily.map(d => d.totals)).toEqual([null, null])+ expect(hub.definitions.population).toContain('not people')+})++it('splits views by reader, counts entries, actions and dwell, and keeps both sides of each ratio', () => {+ const hub = dailyHubUsage([+ r('2026-10-13', 'hub_view_harness_visitor', 30), r('2026-10-13', 'hub_view_harness_member', 10),+ r('2026-10-13', 'hub_view_feed_visitor', 50), r('2026-10-13', 'hub_entry_search', 12), r('2026-10-13', 'hub_entry_direct', 8),+ r('2026-10-13', 'hub_fork', 4), r('2026-10-13', 'hub_share_copy', 2),+ r('2026-10-13', 'hub_sign_in_prompt_shown', 20), r('2026-10-13', 'hub_sign_in_prompt_click', 5),+ r('2026-10-13', 'hub_harness_dwell_over_1m', 7), r('2026-10-13', 'hub_harness_dwell_over_1m', 1),+ r('2026-10-13', 'PRIVATE_CANARY', 1), r('2026-10-13', 'hub_like', -1),+ r('2026-10-14', 'hub_view_feed_member', 1),+ ], 2, now)+ expect(hub.status).toBe('collected')+ const [ended, today] = hub.daily+ expect(ended).toMatchObject({ day: '2026-10-13', period: 'ended; late reports possible' })+ expect(ended.totals).toMatchObject({+ views: { harness: { visitor: 30, member: 10 }, feed: { visitor: 50, member: 0 }, fork: { visitor: 0, member: 0 } },+ entries: { search: 12, direct: 8, social: 0 },+ actions: { fork: 4, share_copy: 2, like: 0 },+ harnessDwell: { under_10s: 0, over_1m: 8 },+ forkClicksPerHarnessView: { numerator: 4, denominator: 40, ratio: 0.1 },+ signInClicksPerPromptShown: { numerator: 5, denominator: 20, ratio: 0.25 },+ })+ expect(today).toMatchObject({ day: '2026-10-14', period: 'incomplete', totals: { views: { feed: { member: 1 } } } })+ // No denominator is no ratio, not zero or infinity.+ expect(today.totals?.forkClicksPerHarnessView).toEqual({ numerator: 0, denominator: 0, ratio: null })+ expect(JSON.stringify(hub)).not.toContain('PRIVATE_CANARY')+})diff --git a/backend/src/analytics/dailyHubUsage.ts b/backend/src/analytics/dailyHubUsage.tsnew file mode 100644index 000000000..ff8f30b8c--- /dev/null+++ b/backend/src/analytics/dailyHubUsage.ts@@ -0,0 +1,55 @@+import { HUB_ACTIONS, HUB_DWELL, HUB_ENTRY_SOURCES, HUB_METRICS, HUB_READERS, HUB_VIEW_PAGES } from '../lib/hubMetricsContract.js'++const DAY = 86_400_000+type Row = { dayUtc: Date; metric: string; value: number }+type Ratio = { numerator: number; denominator: number; ratio: number | null }+const readable = new Set<string>(HUB_METRICS)++/** Two unlinked daily totals side by side; a click can come from a view counted on another day. */+const ratio = (numerator: number, denominator: number): Ratio =>+ ({ numerator, denominator, ratio: denominator > 0 ? Math.round(numerator / denominator * 1000) / 1000 : null })++const pick = <K extends string>(keys: readonly K[], name: (key: K) => string, c: Record<string, number>) =>+ Object.fromEntries(keys.map(key => [key, c[name(key)] ?? 0])) as Record<K, number>++/** One day's Hub totals, or null when no Hub report arrived: missing is not zero. */+function hubDay(c: Record<string, number> | undefined) {+ if (!c) return null+ const views = Object.fromEntries(HUB_VIEW_PAGES.map(page =>+ [page, pick(HUB_READERS, reader => `hub_view_${page}_${reader}`, c)])) as Record<typeof HUB_VIEW_PAGES[number], Record<typeof HUB_READERS[number], number>>+ const actions = pick(HUB_ACTIONS, action => `hub_${action}`, c)+ return {+ views, entries: pick(HUB_ENTRY_SOURCES, source => `hub_entry_${source}`, c), actions,+ harnessDwell: pick(HUB_DWELL, bucket => `hub_harness_dwell_${bucket}`, c),+ forkClicksPerHarnessView: ratio(actions.fork, views.harness.visitor + views.harness.member),+ signInClicksPerPromptShown: ratio(actions.sign_in_prompt_click, actions.sign_in_prompt_shown),+ }+}++/** The `hub` section of `usage:daily`: anonymous totals the website's server forwards. Visits and clicks, never people. */+export function dailyHubUsage(rows: Row[], days: number, now: Date) {+ const today = Math.floor(now.getTime() / DAY) * DAY+ const byDay = new Map<string, Record<string, number>>()+ for (const row of rows) {+ if (!readable.has(row.metric) || !Number.isSafeInteger(row.value) || row.value < 0) continue+ const day = row.dayUtc.toISOString().slice(0, 10)+ const counts = byDay.get(day) ?? {}+ counts[row.metric] = (counts[row.metric] ?? 0) + row.value+ byDay.set(day, counts)+ }+ return {+ status: byDay.size ? 'collected' as const : 'not collected' as const,+ definitions: {+ population: 'Hub page views, visit entries, clicks and dwell buckets from browsers, as unlinked daily totals. These are visits and clicks, not people, and not a funnel. Browsers with Global Privacy Control or Do Not Track, and signed-in readers who turned sharing off, are not counted.',+ views: 'A Hub page drawn, once per navigation; visitor is signed out, member signed in.',+ entries: 'The first Hub page of a browser tab\'s visit, by where it came from, classified in the browser; no referrer is sent.',+ harnessDwell: 'How long a harness page stayed visible, once per view.',+ ratios: 'Two separate daily totals divided; a click can follow a view counted on another day. Keep the numerator and denominator.',+ trust: 'Public, credential-free counts: they can be fabricated. Directional only; no margins are kept, so no suppression applies.',+ },+ daily: Array.from({ length: days }, (_, i) => {+ const stamp = today - (days - 1 - i) * DAY, day = new Date(stamp).toISOString().slice(0, 10)+ return { day, period: stamp === today ? 'incomplete' : 'ended; late reports possible', totals: hubDay(byDay.get(day)) }+ }),+ }+}diff --git a/backend/src/lib/hubMetricsContract.ts b/backend/src/lib/hubMetricsContract.tsnew file mode 100644index 000000000..bcc104382--- /dev/null+++ b/backend/src/lib/hubMetricsContract.ts@@ -0,0 +1,31 @@+/**+ * The Hub's anonymous usage counters: fixed daily totals only, no cookies, identifiers, URLs, content+ * or per-person history. The website's server forwards them to `POST /api/product-usage/hub` with+ * cookies and auth stripped; its test imports this file directly, so keep it free of imports.+ */++/** Hub pages counted when drawn, once per navigation. */+export const HUB_VIEW_PAGES = ['feed', 'harness', 'creator', 'publish', 'notifications', 'fork'] as const+/** Who drew the page: signed out (`visitor`) or signed in (`member`). */+export const HUB_READERS = ['visitor', 'member'] as const+/** Where the first Hub page of a browser tab's visit came from, classified in the browser; the referrer is never sent. */+export const HUB_ENTRY_SOURCES = ['direct', 'search', 'social', 'internal', 'other'] as const+/** How long a harness page stayed visible, once per view. */+export const HUB_DWELL = ['under_10s', '10s_to_1m', 'over_1m'] as const+/** One per click or submit. `get_app`: Explore's link to the Harness desktop app. */+export const HUB_ACTIONS = [+ 'feed_search', 'feed_category', 'feed_sort_newest', 'feed_sort_popular', 'feed_sort_trending', 'feed_more', 'card_open',+ 'like', 'comment_post', 'comments_open', 'files_open', 'fullscreen',+ 'share_open', 'share_copy', 'share_x', 'share_facebook', 'share_linkedin', 'share_sheet',+ 'fork', 'fork_need_app', 'follow', 'report',+ 'sign_in_prompt_shown', 'sign_in_prompt_click', 'get_app', 'publish_started', 'publish_ok', 'publish_failed',+] as const+export const HUB_METRICS = [+ ...HUB_VIEW_PAGES.flatMap(page => HUB_READERS.map(reader => `hub_view_${page}_${reader}` as const)),+ ...HUB_ENTRY_SOURCES.map(source => `hub_entry_${source}` as const),+ ...HUB_ACTIONS.map(action => `hub_${action}` as const),+ ...HUB_DWELL.map(bucket => `hub_harness_dwell_${bucket}` as const),+] as const+export type HubMetric = typeof HUB_METRICS[number]+export const HUB_REPORT_MAX_COUNTERS = 48+export const HUB_REPORT_MAX_VALUE = 1000diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.tsindex f2cd91cbc..34203c8ac 100644--- a/backend/src/lib/productUsage.test.ts+++ b/backend/src/lib/productUsage.test.ts@@ -262,6 +262,22 @@ it('setup ingestion never reads an account and expires after yesterday', async (expect(await ingestSetupUsage({ ...setup, day: '2026-10-12' }, now)).toMatchObject({ accepted: true })})+it('Hub totals share the setup path: unlinked receipt, atomic totals, a retried receipt counts once', async () => {+ const hub = { id: report.id, day: report.day, counters: { hub_view_harness_visitor: 3, hub_fork: 1 } }+ expect(await ingestSetupUsage(hub, now)).toEqual({ accepted: true })+ expect(db.productUsagePreference.findUnique).not.toHaveBeenCalled()+ expect(db.$runCommandRaw.mock.calls[0][0].updates).toEqual([+ { q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'hub_view_harness_visitor' }, u: { $inc: { value: 3 } }, upsert: true },+ { q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'hub_fork' }, u: { $inc: { value: 1 } }, upsert: true },+ ])+ db.$runCommandRaw.mockClear()+ db.productUsageReceipt.create.mockRejectedValue({ code: 'P2002' })+ db.productUsageReceipt.findUnique.mockResolvedValue({ id: report.id })+ expect(await ingestSetupUsage(hub, now)).toEqual({ accepted: true })+ expect(db.$runCommandRaw).not.toHaveBeenCalled()+ expect(await ingestSetupUsage({ ...hub, day: '2026-10-11' }, now)).toMatchObject({ reason: 'EXPIRED' })+})+it('keeps anonymous transport and the phone opt-in unchanged while Desktop evolves independently', () => {expect(readFileSync(new URL('../../../desktop/lib/measurement/setup_transport.dart', import.meta.url), 'utf8')).toBe(readFileSync(new URL('../../../mobile/lib/measurement/setup_transport.dart', import.meta.url), 'utf8'))diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.tsindex 0ba02a59d..57741c2d6 100644--- a/backend/src/lib/productUsage.ts+++ b/backend/src/lib/productUsage.ts@@ -46,7 +46,7 @@ export async function ingestProductUsage(userId: string, report: ProductUsageRep}export interface SetupUsageReport { id: string; day: string; counters: Record<string, number> }-/** Only the dedicated route's narrow schema may call this. No account/authentication lookup. */+/** Only the dedicated signed-out routes' narrow schemas (setup, Hub) may call this. No account/authentication lookup. */export async function ingestSetupUsage(report: SetupUsageReport, now = new Date()) {const age = Math.floor(now.getTime() / DAY) * DAY - Date.parse(report.day + 'T00:00:00Z')if (!validDay(report.day, now) || age > DAY) return { accepted: false, reason: 'EXPIRED' }diff --git a/backend/src/middlewares/authMiddleware.test.ts b/backend/src/middlewares/authMiddleware.test.tsindex bdb8517ec..05bb52331 100644--- a/backend/src/middlewares/authMiddleware.test.ts+++ b/backend/src/middlewares/authMiddleware.test.ts@@ -99,7 +99,9 @@ describe('control-plane SSO auth middleware', () => {})})-it('exempts only the exact credential-free setup endpoint from authentication', () => {+it('exempts only the exact credential-free setup and Hub endpoints from authentication', () => {expect(shouldSkipAuth('/api/product-usage/setup')).toBe(true)- for (const path of ['/api/product-usage/report', '/api/product-usage/settings', '/api/product-usage/setup/extra']) expect(shouldSkipAuth(path)).toBe(false)+ expect(shouldSkipAuth('/api/product-usage/hub')).toBe(true)+ for (const path of ['/api/product-usage/report', '/api/product-usage/settings', '/api/product-usage/setup/extra',+ '/api/product-usage/hub/extra']) expect(shouldSkipAuth(path)).toBe(false)})diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.tsindex 33ab9160f..f81eec0da 100644--- a/backend/src/middlewares/authMiddleware.ts+++ b/backend/src/middlewares/authMiddleware.ts@@ -22,6 +22,8 @@ export function shouldSkipAuth(url: string): boolean {path === '/api/health' ||// Explicitly enabled, credential-free setup totals; its own schema and workload budget apply.path === '/api/product-usage/setup' ||+ // Hub totals the website's server forwards with cookies and auth stripped; same rules as setup.+ path === '/api/product-usage/hub' ||// Web-driven SSO login (pre-session): /authorize returns the SSO URL, /exchange trades the code// for the SSO access token, /logout-url returns the SSO end-session URL. All fetched by web XHR.path === '/api/auth/authorize' ||diff --git a/backend/src/productUsageReport.ts b/backend/src/productUsageReport.tsindex f537cf618..996eee14a 100644--- a/backend/src/productUsageReport.ts+++ b/backend/src/productUsageReport.ts@@ -5,15 +5,18 @@ import { DAILY_PRODUCT_METRICS, dailyProductUsage } from './analytics/dailyProduimport { dailyProductReview } from './analytics/dailyProductReview.js'import { dailyProductPeople } from './analytics/dailyProductPeople.js'import { PEOPLE_METRICS } from './analytics/peopleCounters.js'+import { dailyHubUsage } from './analytics/dailyHubUsage.js'+import { HUB_METRICS } from './lib/hubMetricsContract.js'const days = Number(process.argv[2] ?? 14)if (!Number.isInteger(days) || days < 1 || days > 90) throw new Error('Choose 1–90 days')const db = new PrismaClient()try {const today = Math.floor(Date.now() / 86400000) * 86400000+ const metrics = [...DAILY_PRODUCT_METRICS, ...PEOPLE_METRICS, ...HUB_METRICS]const rows = await db.productUsageTotal.findMany({// Four-week cohorts need their full follow-up; calendar-month comparisons need both prior months.- where: { dayUtc: { gte: new Date(today - 92 * 86400000), lt: new Date(today + 86400000) }, metric: { in: [...DAILY_PRODUCT_METRICS, ...PEOPLE_METRICS] } },- select: { dayUtc: true, metric: true, value: true }, orderBy: [{ dayUtc: 'asc' }, { metric: 'asc' }], take: 93 * (DAILY_PRODUCT_METRICS.length + PEOPLE_METRICS.length),+ where: { dayUtc: { gte: new Date(today - 92 * 86400000), lt: new Date(today + 86400000) }, metric: { in: metrics } },+ select: { dayUtc: true, metric: true, value: true }, orderBy: [{ dayUtc: 'asc' }, { metric: 'asc' }], take: 93 * metrics.length,})const breakdowns = await db.productUsageTotal.findMany({where: { dayUtc: { gte: new Date(today - (days - 1) * 86400000), lt: new Date(today + 86400000) }, metric: { startsWith: 'breakdown:' } },@@ -29,7 +32,8 @@ try {weekly: 'Monday–Sunday UTC; compare weekly_returning_installations in a complete week with weekly_working_installations in the preceding complete week.',outcomes: 'Matched observed turn ends and interruptions, not task success. Missing or interrupted telemetry is not a failed task.',relay: 'Legacy relay event totals are separate; never add them to the client counters.',+ hub: 'Anonymous Hub visits and clicks from browsers are a separate population again; never add them to app, daemon or people counts.',coverage: 'New local counters need updated clients. Delayed/offline reports and privacy changes can affect counts; today is incomplete.',- }, ...dailyProductUsage(rows, days, new Date()), review: dailyProductReview(rows, new Date()), people: dailyProductPeople(rows, days, new Date()), health: { ...dailyProductHealth([...rows, ...breakdowns], new Date()), breakdownReadLimitReached: breakdowns.length === 50000 } }, null, 2))+ }, ...dailyProductUsage(rows, days, new Date()), review: dailyProductReview(rows, new Date()), people: dailyProductPeople(rows, days, new Date()), hub: dailyHubUsage(rows, days, new Date()), health: { ...dailyProductHealth([...rows, ...breakdowns], new Date()), breakdownReadLimitReached: breakdowns.length === 50000 } }, null, 2))} catch { console.error('Could not read aggregate product usage. Check the read-only connection and schema.'); process.exitCode = 1 }finally { await db.$disconnect() }diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.tsindex 7223e09d3..5efa7145b 100644--- a/backend/src/routes/productUsage.test.ts+++ b/backend/src/routes/productUsage.test.ts@@ -5,6 +5,7 @@ const methods = vi.hoisted(() => ({ ingestProductUsage: vi.fn(), ingestSetupUsagvi.mock('../lib/productUsage.js', () => methods)import { productUsageRoutes } from './productUsage.js'import { PRODUCT_USAGE_METRICS, PRODUCT_USAGE_MAX_COUNT } from '../types/productUsage.js'+import { HUB_METRICS, HUB_REPORT_MAX_COUNTERS, HUB_REPORT_MAX_VALUE } from '../lib/hubMetricsContract.js'let app: ReturnType<typeof Fastify>beforeEach(async () => {vi.resetAllMocks()@@ -217,6 +218,70 @@ it('bounds untrusted setup writes independently of signed-in reports', async ()expect(await Promise.all(pending)).toEqual([200, 200, 200, 200])})+const hub = { schemaVersion: 1, id: good.id, day: good.day, counters: { hub_view_harness_visitor: 3, hub_entry_search: 1, hub_fork: 1, hub_harness_dwell_over_1m: 2 } }+const sendHub = (payload: unknown = hub, headers = {}) => app.inject({ method: 'POST', url: '/api/product-usage/hub', payload: payload as Record<string, unknown>, headers })+it('accepts anonymous Hub totals through the setup receipt path without an account lookup', async () => {+ expect((await sendHub()).statusCode).toBe(200)+ expect(methods.ingestSetupUsage).toHaveBeenCalledExactlyOnceWith(hub)+ expect(methods.productUsageChoice).not.toHaveBeenCalled()+ expect(methods.ingestProductUsage).not.toHaveBeenCalled()+ // The whole vocabulary fits one report under the key cap and body limit at the largest values,+ // so the cap cannot be exceeded with valid names until the vocabulary outgrows it.+ const all = { ...hub, counters: Object.fromEntries(HUB_METRICS.map(k => [k, HUB_REPORT_MAX_VALUE])) }+ expect(HUB_METRICS.length).toBeLessThanOrEqual(HUB_REPORT_MAX_COUNTERS)+ expect(Buffer.byteLength(JSON.stringify(all))).toBeLessThan(4096)+ expect((await sendHub(all)).statusCode).toBe(200)+})+it('refuses Hub reports with credentials, foreign or malformed counters, or extra fields, without echoing them', async () => {+ for (const headers of [{ authorization: 'fixture' }, { cookie: 'PRIVATE_CANARY' }]) expect((await sendHub(hub, headers)).statusCode).toBe(400)+ for (const payload of [{ ...hub, counters: {} },+ { ...hub, counters: { PRIVATE_CANARY: 1 } }, { ...hub, counters: { hub_view_harness_PRIVATE_CANARY: 1 } },+ // Signed-in and setup counters have their own routes; they never arrive as anonymous Hub totals.+ { ...hub, counters: { turns_started: 1 } }, { ...hub, counters: { setup_desktop_sign_in_started: 1 } },+ { ...hub, counters: { hub_fork: 0 } }, { ...hub, counters: { hub_fork: HUB_REPORT_MAX_VALUE + 1 } }, { ...hub, counters: { hub_fork: 1.5 } },+ { ...hub, day: '2026-10-1' }, { ...hub, day: 'PRIVATE_CANARY' }, { ...hub, id: 'PRIVATE_CANARY' }, { ...hub, schemaVersion: 2 },+ { ...hub, url: 'https://PRIVATE_CANARY' }, { ...hub, referrer: 'PRIVATE_CANARY' }, { ...hub, consent: true }]) {+ const response = await sendHub(payload)+ expect(response.statusCode).toBe(400)+ expect(response.body).not.toContain('PRIVATE_CANARY')+ }+ expect(methods.ingestSetupUsage).not.toHaveBeenCalled()+ // Nor do Hub counters ride the signed-in or setup reports.+ expect((await submit({ ...good, counters: { hub_fork: 1 } })).statusCode).toBe(400)+ expect((await sendSetup({ ...setup, counters: { hub_fork: 1 } })).statusCode).toBe(400)+})+it('does not reflect a Hub storage error', async () => {+ methods.ingestSetupUsage.mockRejectedValue(new Error('PRIVATE_CANARY'))+ const response = await sendHub()+ expect(response.statusCode).toBe(503)+ expect(response.body).not.toContain('PRIVATE_CANARY')+})+it('bounds Hub writes with a budget of their own, so they never starve setup measurement', async () => {+ let finish!: (value: unknown) => void+ const done = new Promise(resolve => { finish = resolve })+ methods.ingestSetupUsage.mockReturnValue(done)+ const pending = Array.from({ length: 4 }, () => sendHub().then((r: { statusCode: number }) => r.statusCode))+ await vi.waitFor(() => expect(methods.ingestSetupUsage).toHaveBeenCalledTimes(4))+ const busy = await sendHub()+ expect(busy.statusCode).toBe(429)+ expect(busy.json().error.code).toBe('USAGE_UNAVAILABLE')+ const setupWhileHubBusy = sendSetup()+ await vi.waitFor(() => expect(methods.ingestSetupUsage).toHaveBeenCalledTimes(5))+ finish({ accepted: true })+ expect(await Promise.all(pending)).toEqual([200, 200, 200, 200])+ expect((await setupWhileHubBusy).statusCode).toBe(200)+})+it('caps Hub writes per minute', async () => {+ vi.useFakeTimers({ now: new Date('2026-10-13T12:00:00Z'), toFake: ['Date'] })+ try {+ for (let i = 0; i < 240; i++) expect((await sendHub()).statusCode).toBe(200)+ expect((await sendHub()).statusCode).toBe(429)+ expect((await sendSetup()).statusCode).toBe(200)+ vi.setSystemTime(new Date('2026-10-13T12:01:00Z'))+ expect((await sendHub()).statusCode).toBe(200)+ } finally { vi.useRealTimers() }+})+it('feedback reduces a voluntary fixed choice to one unlinked, retry-safe count', async () => {const request = { method: 'POST' as const, url: '/api/product-usage/feedback', headers: { authorization: 'fixture' }, payload: { id: good.id, answer: 'useful' } }expect((await app.inject(request)).statusCode).toBe(200)diff --git a/backend/src/routes/productUsage.ts b/backend/src/routes/productUsage.tsindex 569e5bff1..d3ceb1180 100644--- a/backend/src/routes/productUsage.ts+++ b/backend/src/routes/productUsage.ts@@ -2,6 +2,7 @@ import type { FastifyInstance } from 'fastify'import { z } from 'zod'import { ingestProductUsage, ingestSetupUsage, productUsageChoice, setProductUsageChoice } from '../lib/productUsage.js'import { PRODUCT_FEEDBACK, PRODUCT_USAGE_MAX_COUNT, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_SETUP_METRICS } from '../types/productUsage.js'+import { HUB_METRICS, HUB_REPORT_MAX_COUNTERS, HUB_REPORT_MAX_VALUE } from '../lib/hubMetricsContract.js'import { releaseBucket } from '../types/productHealthContract.js'import { sendError, sendSuccess } from '../utils/response.js'@@ -11,18 +12,17 @@ const contextSchema = z.strictObject({platform: z.enum(['macos', 'linux', 'windows', 'ios', 'android', 'other']),channel: z.enum(['production', 'development']),})+const daySchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/)export const productUsageReportSchema = z.strictObject({context: contextSchema.optional(),- schemaVersion: z.literal(1), revision: z.number().int().nonnegative(), id: z.uuid(),- day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ schemaVersion: z.literal(1), revision: z.number().int().nonnegative(), id: z.uuid(), day: daySchema,counters: z.partialRecord(z.enum(PRODUCT_USAGE_METRICS), z.number().int().min(0).max(PRODUCT_USAGE_MAX_COUNT)),})const feedbackSchema = z.strictObject({ id: z.uuid(), answer: z.enum(PRODUCT_FEEDBACK) })const choiceSchema = z.strictObject({ enabled: z.boolean() })const setupFields = {- schemaVersion: z.literal(1), id: z.uuid(),- day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ schemaVersion: z.literal(1), id: z.uuid(), day: daySchema,counters: z.partialRecord(z.enum(PRODUCT_USAGE_SETUP_METRICS), z.number().int().min(1).max(1000)).refine(c => Object.keys(c).length > 0 && Object.keys(c).length <= 32),}@@ -37,6 +37,26 @@ export const setupUsageSchema = z.union([.refine(report => DEFAULT_SETUP_PREFIXES.some(prefix =>Object.keys(report.counters).every(key => key.startsWith(prefix)))),])+// Hub totals forwarded by the website's server, cookies and auth stripped. Their own vocabulary+// only: no signed-in or setup counter can arrive this way, and none of these through those routes.+export const hubUsageSchema = z.strictObject({+ schemaVersion: z.literal(1), id: z.uuid(), day: daySchema,+ counters: z.partialRecord(z.enum(HUB_METRICS), z.number().int().min(1).max(HUB_REPORT_MAX_VALUE))+ .refine(c => Object.keys(c).length > 0 && Object.keys(c).length <= HUB_REPORT_MAX_COUNTERS),+})++/** A process-wide budget for untrusted signed-out counts, without collecting IPs or cookies.+ * Each route gets its own, so Hub traffic can never starve setup and sign-in measurement. */+function writeBudget(perMinute: number, inFlight: number) {+ let minuteWindow = 0, requests = 0, running = 0+ return async <T>(write: () => Promise<T>): Promise<T | 'busy'> => {+ const minute = Math.floor(Date.now() / 60_000)+ if (minute !== minuteWindow) { minuteWindow = minute; requests = 0 }+ if (requests >= perMinute || running >= inFlight) return 'busy'+ requests++; running+++ try { return await write() } finally { running-- }+ }+}const REPORT_METRICS = new Set<string>(PRODUCT_USAGE_METRICS)const SETUP_METRICS = new Set<string>(PRODUCT_USAGE_SETUP_METRICS)@@ -56,9 +76,8 @@ function withoutUnknownCounters(body: unknown, allowed: Set<string>): { body: un}export async function productUsageRoutes(app: FastifyInstance): Promise<void> {- // A process-wide budget bounds untrusted pre-sign-in counts without collecting IPs or cookies.// Exhaustion loses measurement only; it never shares a gate with sign-in or product traffic.- let setupWindow = 0, setupRequests = 0, setupInFlight = 0+ const setupBudget = writeBudget(120, 4), hubBudget = writeBudget(240, 4)// Parser errors can contain a piece of malformed JSON. Keep this plugin's errors out of the// generic logger/response handler, including failures before the route's schema check runs.app.setErrorHandler((error, _req, reply) => {@@ -70,13 +89,22 @@ export async function productUsageRoutes(app: FastifyInstance): Promise<void> {if (req.headers.authorization || req.headers.cookie) return sendError(reply, 'Setup reports must omit credentials', 'INVALID_SETUP_REPORT', 400)const parsed = setupUsageSchema.safeParse(withoutUnknownCounters(req.body, SETUP_METRICS).body)if (!parsed.success) return sendError(reply, 'Invalid setup report', 'INVALID_SETUP_REPORT', 400)- const minute = Math.floor(Date.now() / 60_000)- if (minute !== setupWindow) { setupWindow = minute; setupRequests = 0 }- if (setupRequests >= 120 || setupInFlight >= 4) return sendError(reply, 'Setup measurement busy', 'USAGE_UNAVAILABLE', 429)- setupRequests++; setupInFlight++- try { return sendSuccess(reply, await ingestSetupUsage(parsed.data)) }- catch { return sendError(reply, 'Setup measurement unavailable', 'USAGE_UNAVAILABLE', 503) }- finally { setupInFlight-- }+ try {+ const result = await setupBudget(() => ingestSetupUsage(parsed.data))+ if (result === 'busy') return sendError(reply, 'Setup measurement busy', 'USAGE_UNAVAILABLE', 429)+ return sendSuccess(reply, result)+ } catch { return sendError(reply, 'Setup measurement unavailable', 'USAGE_UNAVAILABLE', 503) }+ })+ // The same unlinked receipt, atomic totals and today-or-yesterday rule as setup; no account lookup.+ app.post('/api/product-usage/hub', { bodyLimit: 4096 }, async (req, reply) => {+ if (req.headers.authorization || req.headers.cookie) return sendError(reply, 'Hub reports must omit credentials', 'INVALID_HUB_REPORT', 400)+ const parsed = hubUsageSchema.safeParse(req.body)+ if (!parsed.success) return sendError(reply, 'Invalid Hub report', 'INVALID_HUB_REPORT', 400)+ try {+ const result = await hubBudget(() => ingestSetupUsage(parsed.data))+ if (result === 'busy') return sendError(reply, 'Hub measurement busy', 'USAGE_UNAVAILABLE', 429)+ return sendSuccess(reply, result)+ } catch { return sendError(reply, 'Hub measurement unavailable', 'USAGE_UNAVAILABLE', 503) }})app.get('/api/product-usage/settings', async (req, reply) => {if (!req.user?.sub) return sendError(reply, 'Unauthorized', 'UNAUTHORIZED', 401)diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex 5f7068170..6f535d8a9 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -24,6 +24,7 @@ automatically proven improvement. Changes still need review, tests and a deliber| Are the phone's side pages used? | Find and Computers opens, by a sideways swipe on the terminal or by a button (Computers' row in Settings, its link on a long wait at home) | Which page and which way, nothing more. Find's key and screen-reader actions are not counted; a swipe that lets Find go back opened nothing. || 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. |+| 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) | 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 hasone “Share product usage data” switch in Experimental, with no separate Privacy page or feedback@@ -41,13 +42,17 @@ account at the next sign-in before phone sharing resumes; an unreadable choice iaccount preference is remembered for the next signed-out launch. With nowhere to keep the opt-out(tests, the sample) it starts off. Neither native setup transport sends credentials/cookies or replays earlier actions.Setup state already visible when sharing becomes enabled can start an observation; duration then-begins at that observation, not necessarily at installation start. Web pre-sign-in collection stays-disabled because that transport cannot guarantee omitted cookies. These untrusted setup counts are+begins at that observation, not necessarily at installation start. The web app's pre-sign-in setup+collection stays disabled because a browser request to the backend cannot guarantee omitted cookies.+The Hub's counters are the one web exception: the browser sends them to the website's own server,+which forwards them to the backend without cookies or auth, so the backend never sees a browser+credential (see the Hub endpoint below). These untrusted setup counts area separate population from signed-in app/daemon reports; older clients and opt-outs affect coverage. Theyshow observed friction at each step, **not** unique signup conversion or a linked user funnel.Reproduce those paths with test accounts and synthetic inputs. No screen recordings,click trails, stable analytics identifiers, locations, content or arbitrary properties are added.-The exact counter vocabulary is in [productUsage.ts](../backend/src/types/productUsage.ts).+The exact counter vocabulary is in [productUsage.ts](../backend/src/types/productUsage.ts); the Hub's is in+[hubMetricsContract.ts](../backend/src/lib/hubMetricsContract.ts).Daemon reports combine participating signed-in installations, including staff and both environments.App reports are surface-specific operation totals; never add them to daemon or relay counts.@@ -71,7 +76,10 @@ excluded from release/platform margins so a return's release cannot be mistaken`health` in `usage:daily` reports consented setup/workspace/first-work/first-response milestones,coarse waits, request-source reconciliation, explicit composer-work D1/D7/D28 cohorts, weekly work-day-bins, process health, and collector loss/rejection/late-report signals. Milestones describe local+bins, process health, and collector loss/rejection/late-report signals. `hub` reports the Hub's+daily views by page and reader, entries, clicks and dwell buckets, with fork clicks per harness view+and sign-in prompt clicks per prompt shown as numerator, denominator and ratio; a day without Hub+reports is null, not zero. These are visits and clicks, not people. Milestones describe localapp episodes, can cross UTC days, and do not establish a joined signup conversion rate. First-workcohorts use explicit composer messages; terminal keystrokes and automatic work remain unclassified.Weekly bins cover completed weeks from installations that report again, so non-returners can be missing.@@ -194,6 +202,17 @@ concurrent writes per server process. No IP-based analytics or new rate-limit idExhaustion drops measurement rather than affecting sign-in. Public counts remain susceptible tofabrication; they are directional diagnostics, not trusted account acquisition metrics.+`POST /api/product-usage/hub` takes only the Hub vocabulary: no setup, app or daemon counter, and+no Hub counter through those routes. It carries a random receipt, the UTC day (today or yesterday)+and at most 48 counters of 1–1,000 each, nothing else: no URL, page id, referrer, harness, creator,+search text or identifier. The website's server forwards it with cookies and auth stripped; the+backend rejects auth/cookie headers, limits bodies to 4 KiB and admits at most 240 writes/minute and+four concurrent writes per server process, a budget of its own so Hub traffic cannot starve setup+or sign-in measurement. The browser skips counting under Global Privacy Control or Do Not Track; the+website's server drops a signed-in reader's counts when that account's sharing is off. A view is a+page drawn, once per navigation; an entry is the first Hub page of a tab's visit; dwell is counted+once per harness view. The same totals can come from one visitor or many.+Both ingestion paths atomically add only UTC-day/metric totals plus an unlinked random retry receipt.Fast database write conflicts retry that complete transaction up to three times with short jitter,rechecking the sharing choice each time. No retry starts after the first second; existing transaction@@ -275,6 +294,11 @@ carrying a counter it does not know (a phone page opening, a `request_phone_*` cstop when it is off. Old clients stop contributing individual daily histories when the backend changes;the historical reporting command will no longer be a current-usage source.+Hub counters roll out backend first, then website: an older backend has no `/api/product-usage/hub`+route and loses whatever the website sends it, and a backend that does not know a Hub counter+refuses the whole report, so a new Hub counter also ships backend first. Then check that a browser+with Global Privacy Control and a signed-in reader with sharing off send nothing.+People counts roll out in this order: deploy the backend without `PRODUCT_USAGE_SUBJECT_KEY` (no marksare written); release desktop, phone and CLI with the updated "See what's shared" text; then set the key(32+ random characters, in the Helm secret). The first D1 is available two days later, D7 eight daysdiff --git a/website/public/robots.txt b/website/public/robots.txtindex 2076489f9..9190d1078 100644--- a/website/public/robots.txt+++ b/website/public/robots.txt@@ -1,4 +1,9 @@User-agent: *Allow: /+# Built for one reader on request, not pages to keep: a project's ZIP, its fork snapshot, and the API.+Disallow: /api/+Disallow: /hub/*/download+Disallow: /hub/*/snapshotSitemap: https://harness.autonomous.ai/sitemap.xml+Sitemap: https://harness.autonomous.ai/hub/sitemap.xmldiff --git a/website/src/app/api/hub-usage/route.spec.ts b/website/src/app/api/hub-usage/route.spec.tsnew file mode 100644index 000000000..d9348e5e0--- /dev/null+++ b/website/src/app/api/hub-usage/route.spec.ts@@ -0,0 +1,43 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';+import { POST } from './route';++const report = { schemaVersion: 1, id: '0f8fad5b-d9cb-469f-a165-70867728950e', day: '2026-10-19', counters: { hub_like: 2 } };+const send = (headers: Record<string, string> = {}, body = JSON.stringify(report)) =>+ POST(new Request('https://harness.example/api/hub-usage', { method: 'POST', body, headers: { 'content-type': 'application/json', ...headers } }));++afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });++describe('Hub usage on its way to the backend', () => {+ it('forwards a visitor’s counts with no cookie or sign-in', async () => {+ vi.stubEnv('COMMUNITY_API_URL', 'http://127.0.0.1:54882');+ const fetcher = vi.fn(async () => Response.json({ success: true })); vi.stubGlobal('fetch', fetcher);+ expect((await send({ cookie: 'rid=campaign' })).status).toBe(204);+ const [url, init] = fetcher.mock.calls[0] as unknown as [URL, RequestInit];+ expect(String(url)).toBe('http://127.0.0.1:54882/api/product-usage/hub');+ expect(Object.keys(init.headers as Record<string, string>)).toEqual(['Content-Type']);+ expect(JSON.parse(String(init.body))).toEqual(report);+ });+ it('checks a member’s sharing first, and leaves them out when it is off or cannot be read', async () => {+ vi.stubEnv('COMMUNITY_API_URL', 'http://127.0.0.1:54882');+ const fetcher = vi.fn()+ .mockResolvedValueOnce(Response.json({ success: true, data: { enabled: true, revision: 1 } }))+ .mockResolvedValueOnce(Response.json({ success: true }))+ .mockResolvedValueOnce(Response.json({ success: true, data: { enabled: false, revision: 2 } }))+ .mockResolvedValueOnce(Response.json({ success: false }, { status: 401 }));+ vi.stubGlobal('fetch', fetcher);+ await send({ authorization: 'Bearer member' });+ expect(String(fetcher.mock.calls[0][0])).toBe('http://127.0.0.1:54882/api/product-usage/settings');+ expect(fetcher.mock.calls[0][1].headers.Authorization).toBe('Bearer member');+ expect(fetcher.mock.calls[1][1].headers).toEqual({ 'Content-Type': 'application/json' });+ await send({ authorization: 'Bearer off' });+ await send({ authorization: 'Bearer expired' });+ expect(fetcher).toHaveBeenCalledTimes(4);+ });+ it('refuses what is not a report, and never fails the page when the Hub is down', async () => {+ const fetcher = vi.fn(async () => { throw new Error('down'); }); vi.stubGlobal('fetch', fetcher);+ expect((await send({}, 'not json')).status).toBe(400);+ expect((await send({}, 'x'.repeat(4097))).status).toBe(413);+ expect((await send()).status).toBe(204);+ });+});diff --git a/website/src/app/api/hub-usage/route.ts b/website/src/app/api/hub-usage/route.tsnew file mode 100644index 000000000..d052a8b67--- /dev/null+++ b/website/src/app/api/hub-usage/route.ts@@ -0,0 +1,35 @@+import { communityApiOrigin } from '@/lib/community/server';++/**+ * The Hub's usage counts on their way to the backend (`POST /api/product-usage/hub`). The backend+ * takes them only without credentials, so they leave here with no cookie or sign-in: the sign-in a+ * browser sends is used only to leave out a reader who turned sharing off, and a preference that+ * cannot be read leaves them out too. The backend checks the counters themselves.+ */+const noContent = () => new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } });++async function sharingOn(authorization: string): Promise<boolean> {+ try {+ const response = await fetch(new URL('/api/product-usage/settings', communityApiOrigin()), {+ headers: { Authorization: authorization, Accept: 'application/json' }, redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(3000),+ });+ if (!response.ok) return false;+ return (await response.json())?.data?.enabled === true;+ } catch { return false; }+}++export async function POST(request: Request): Promise<Response> {+ const text = await request.text();+ if (text.length > 4096) return new Response(null, { status: 413 });+ let report: unknown;+ try { report = JSON.parse(text); } catch { return new Response(null, { status: 400 }); }+ const authorization = request.headers.get('authorization');+ if (authorization && !await sharingOn(authorization)) return noContent();+ try {+ await fetch(new URL('/api/product-usage/hub', communityApiOrigin()), {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(report),+ redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(5000),+ });+ } catch { /* Measurement is lost, never the reader's page. */ }+ return noContent();+}diff --git a/website/src/app/hub/[id]/fork/page.tsx b/website/src/app/hub/[id]/fork/page.tsxindex 6f402b0a5..9c47fdc96 100644--- a/website/src/app/hub/[id]/fork/page.tsx+++ b/website/src/app/hub/[id]/fork/page.tsx@@ -6,17 +6,30 @@ import { harnessPath } from '@/lib/community/slug';import { Header } from '../../components/Header';import { ForkButton } from '../../components/ForkButton';import { HarnessTags } from '../../components/HarnessTags';+import { HubView } from '../../components/HubView';+import { privateMetadata } from '../../privatePage';import styles from '../../community.module.css';+/** A step on the way to a fork, not a page of its own to find: the harness's page is. */+export const metadata = privateMetadata('Make it yours');++/** The harness, null once it is not published, or 'down' when the Hub cannot be reached right now. */+async function readForFork(id: string) {+ try { return await getPublicHarness(id, { viewerOnly: true }); } catch { return 'down' as const; }+}+export default async function ForkPage({ params }: { params: Promise<{ id: string }> }) {- const { id } = await params, harness = await getPublicHarness(id, { viewerOnly: true });+ const { id } = await params, harness = await readForFork(id);if (!harness) notFound();+ if (harness === 'down') return <><Header /><main className={`${styles.wrap} ${styles.fork}`}>+ <h1>Make it yours.</h1><p className={styles.notice} role="alert">The Hub could not be reached just now. <a href={`/hub/${id}/fork`}>Try again</a></p>+ </main></>;const path = harnessPath(harness);- return <><Header /><main className={`${styles.wrap} ${styles.fork}`}>+ return <><Header /><HubView page="fork" /><main className={`${styles.wrap} ${styles.fork}`}><Link href={path} className={styles.back}><ArrowLeft /> {harness.title}</Link><h1>Make it yours.</h1><p className={styles.forkIntro}>Open this project in Harness. The files and published conversation come with it. Your version stays private until you publish.</p><div className={styles.forkColumns}><div>{harness.cover && <img src={harness.cover} alt="" width={900} height={600} />}<h2>{harness.title}</h2><HarnessTags harness={harness} /></div>- <div><ForkButton harness={harness} /><h2>New to Harness?</h2><p><Link className={styles.textLink} href="/download" target="_blank" rel="noopener">Install the desktop app</Link>, then return here and open your fork. Harness prepares the project and its viewer for you.</p><p className={styles.notice}>Your browser may ask to open Harness. Choose Open to continue. Use the latest desktop version with community links.</p><details><summary>Get the source files</summary><p><a className={styles.textLink} href={`${path}/download`}>Download a ZIP</a> if you want to use a different editor.</p></details></div>+ <div><ForkButton harness={harness} onForkPage /><h2>New to Harness?</h2><p><Link className={styles.textLink} href="/download" target="_blank" rel="noopener">Install the desktop app</Link>, then return here and open your fork. Harness prepares the project and its viewer for you.</p><p className={styles.notice}>Your browser may ask to open Harness. Choose Open to continue. Use the latest desktop version with community links.</p><details><summary>Get the source files</summary><p><a className={styles.textLink} href={`${path}/download`}>Download a ZIP</a> if you want to use a different editor.</p></details></div></div></main></>;}diff --git a/website/src/app/hub/[id]/page.tsx b/website/src/app/hub/[id]/page.tsxindex 80cbfdd63..387278a8f 100644--- a/website/src/app/hub/[id]/page.tsx+++ b/website/src/app/hub/[id]/page.tsx@@ -23,11 +23,12 @@ const shareImage = (harness: OpenHarness) => harness.cover && !harness.cover.endexport async function generateMetadata({ params }: Props): Promise<Metadata> {const harness = await readHarness((await params).id);- if (!harness) return { title: 'Open harness' };+ // Not read here (unpublished, a staging publication, or a slow Hub): nothing for a search engine to keep.+ if (!harness) return { title: 'Open harness', robots: { index: false } };const image = shareImage(harness), title = harness.title, description = harness.description;return {title, description, alternates: { canonical: harnessPath(harness) },- openGraph: { type: 'article', title, description, authors: [harness.authorName], ...(image ? { images: [{ url: image, width: 900, height: 600 }] } : {}) },+ openGraph: { type: 'article', title, description, url: harnessPath(harness), siteName: 'Harness Hub', authors: [harness.authorName], ...(image ? { images: [{ url: image, width: 900, height: 600 }] } : {}) },twitter: { card: image ? 'summary_large_image' : 'summary', title, description },};}diff --git a/website/src/app/hub/community.module.css b/website/src/app/hub/community.module.cssindex 15e1d7ad0..be1c3db41 100644--- a/website/src/app/hub/community.module.css+++ b/website/src/app/hub/community.module.css@@ -6,13 +6,13 @@.wrap{width:84%;max-width:1712px;margin:0 auto}.bar{display:flex;align-items:center;gap:26px;min-height:80px;padding:22px 0}.brand{font-weight:600;font-size:25px;letter-spacing:-1px;margin-right:22px}-.hubWord{font-weight:400;color:#999;letter-spacing:-.7px}-.feedIntro{margin-bottom:40px;color:#777}.feedIntro h1{font-size:28px;font-weight:400;color:#242424;margin-bottom:8px}-.cardSocial{display:flex;gap:18px;margin-top:12px;color:#888;font-size:12px}.cardSocial button,.cardSocial a{display:inline-flex;align-items:center;gap:6px}.cardSocial svg{height:14px;width:14px}-.creator{font-style:normal;font-size:10px;color:#777;background:#f4f4f2;padding:2px 5px}-.reply{padding-left:20px}.replyContext{display:block;color:#999;font-size:11px;margin-bottom:5px}-.page .replyButton{font-size:11px;color:#888;margin-top:8px;text-decoration:underline;text-underline-offset:3px}-.nav,.barActions{display:flex;align-items:center;gap:26px;color:#777;font-size:15px}+.hubWord{font-weight:400;color:#707070;letter-spacing:-.7px}+.feedIntro{margin-bottom:40px;color:#666}.feedIntro h1{font-size:28px;font-weight:400;color:#242424;margin-bottom:8px}+.cardSocial{display:flex;gap:18px;margin-top:12px;color:#6b6b6b;font-size:12px}.cardSocial button,.cardSocial a{display:inline-flex;align-items:center;gap:6px}.cardSocial svg{height:14px;width:14px}+.creator{font-style:normal;font-size:10px;color:#666;background:#f4f4f2;padding:2px 5px}+.reply{padding-left:20px}.replyContext{display:block;color:#707070;font-size:11px;margin-bottom:5px}+.page .replyButton{font-size:11px;color:#6b6b6b;margin-top:8px;text-decoration:underline;text-underline-offset:3px}+.nav,.barActions{display:flex;align-items:center;gap:26px;color:#666;font-size:15px}.barActions{gap:22px;margin-left:auto}.nav a,.barActions a,.barActions button{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}.nav [aria-current=page]{color:#242424}@@ -22,9 +22,9 @@.searchField{display:flex;align-items:center;gap:8px;width:min(280px,52vw);height:36px;padding:0 6px 0 12px;border:1px solid #e4e4e1;background:#fafaf9;transition:border-color .15s,background-color .15s;animation:searchOpen .18s ease-out}.searchField:focus-within{border-color:#242424;background:#fff}.searchField input{flex:1;min-width:0;height:100%;border:0;background:transparent;outline:0;color:#242424;font-size:14px}-.searchField input::placeholder{color:#999}+.searchField input::placeholder{color:#707070}.searchField input::-webkit-search-cancel-button{-webkit-appearance:none;appearance:none}-.page .searchField button{padding:4px;color:#999}+.page .searchField button{padding:4px;color:#707070}.page .searchField button:hover{color:#242424}.searchField svg{width:16px;height:16px;flex-shrink:0}@keyframes searchOpen{from{width:36px;opacity:.5}}@@ -35,29 +35,29 @@.cover{display:block;aspect-ratio:3/2;width:100%;height:auto;object-fit:cover;background:#ece9e2}.blankCover{aspect-ratio:3/2;background:#e9e4dc;display:flex;align-items:center;justify-content:center;padding:12%;font:400 clamp(25px,3vw,45px)/1.06 Georgia,serif;letter-spacing:-1px;color:#685449;overflow-wrap:anywhere}.card h2{font-size:16px;line-height:1.35;font-weight:400;margin-top:9px}-.card p{font-size:15px;line-height:1.4;color:#777;margin-top:2px}-.card small{display:block;color:#888;font-size:13px;margin-top:9px}+.card p{font-size:15px;line-height:1.4;color:#666;margin-top:2px}+.card small{display:block;color:#6b6b6b;font-size:13px;margin-top:9px}.card:hover h2{color:#6c6c6c}.icon{display:inline-flex;align-items:center;justify-content:center;padding:8px;min-width:32px;min-height:32px}.icon svg{width:17px;height:17px}-.notice{font-size:13px;color:#777;margin:0 0 30px;line-height:1.6}+.notice{font-size:13px;color:#666;margin:0 0 30px;line-height:1.6}.notice button,.notice a{text-decoration:underline;text-underline-offset:3px;margin-left:8px}-.empty{padding:60px 0;max-width:430px;color:#777}+.empty{padding:60px 0;max-width:430px;color:#666}.empty h1,.empty h2{font-size:26px;color:#242424;font-weight:400;margin-bottom:12px}.more{display:block;margin:60px auto 0;font-size:14px;padding:12px 20px}.detail{padding-top:27px;padding-bottom:70px}-.back{display:inline-flex;align-items:center;gap:8px;font-size:13px;color:#777!important;margin-bottom:27px}+.back{display:inline-flex;align-items:center;gap:8px;font-size:13px;color:#666!important;margin-bottom:27px}.back svg{width:14px;height:14px}.detailHead{display:flex;align-items:center;gap:28px;margin-bottom:31px}.identity{min-width:0}.identity h1{font-size:25px;font-weight:400;line-height:1.2;letter-spacing:-.5px;margin-bottom:9px}-.byline{display:flex;align-items:center;gap:15px;flex-wrap:wrap;font-size:13px;color:#777}+.byline{display:flex;align-items:center;gap:15px;flex-wrap:wrap;font-size:13px;color:#666}.follow{text-decoration:underline;text-underline-offset:3px}/* The reader's actions: one row of quiet 36px buttons that tint on hover and stay tinted while their panel is open, ending in Fork. */.actions{display:flex;align-items:center;gap:4px;margin-left:auto;flex-shrink:0}.actions>button,.actions>a,.actions .actionButton{display:inline-flex;align-items:center;gap:7px;height:36px;padding:0 11px;border-radius:8px;white-space:nowrap;font-size:13px;color:#555;transition:background-color .15s,color .15s}.actions>button:hover:not(:disabled),.actions>a:hover,.actions .actionButton:hover{background:#f4f4f2;color:#242424}-.actions>button[aria-pressed=true],.actions .actionButton[aria-pressed=true]{background:#efefec;color:#242424}+.actions>button[aria-pressed=true],.actions .actionButton[aria-expanded=true]{background:#efefec;color:#242424}.actions>button:focus-visible,.actions>a:focus-visible,.actions .actionButton:focus-visible,.actions .primary:focus-visible{outline:2px solid #242424;outline-offset:2px}.actions svg{width:16px;height:16px}.actions .handoff{margin-left:8px}@@ -73,25 +73,25 @@.chat{min-width:0;padding-left:29px}.chatHead{display:flex;justify-content:space-between;align-items:center;gap:14px;margin:0 0 30px;font-size:12px}.chatHead h2{font-size:13px;font-weight:600}-.chatHead span{color:#888;font-size:11px}+.chatHead span{color:#6b6b6b;font-size:11px}.transcript{font:12px/1.85 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.turn{margin-bottom:27px}-.turn small{display:block;color:#888;font:12px/1.5 Arial,Helvetica,sans-serif;margin-bottom:9px}+.turn small{display:block;color:#6b6b6b;font:12px/1.5 Arial,Helvetica,sans-serif;margin-bottom:9px}.turn p{white-space:pre-wrap}-.tool{color:#777;margin:0 0 22px;font-size:11px}+.tool{color:#666;margin:0 0 22px;font-size:11px}.tool summary{cursor:pointer}.tool p{padding-top:10px;white-space:pre-wrap}-.contextNote{font:11px/1.6 Arial,sans-serif;color:#888;margin-bottom:27px}+.contextNote{font:11px/1.6 Arial,sans-serif;color:#6b6b6b;margin-bottom:27px}.comment{padding-bottom:26px;overflow-wrap:anywhere}.commentBy{display:flex;gap:8px;align-items:center;font-size:12px;margin-bottom:9px}-.commentBy small{color:#999;margin-left:auto;font-size:11px}+.commentBy small{color:#707070;margin-left:auto;font-size:11px}.comment p{font-size:13px;line-height:1.7;white-space:pre-wrap}-.commentBy button{font-size:11px;color:#888;text-decoration:underline}+.commentBy button{font-size:11px;color:#6b6b6b;text-decoration:underline}.commentForm{margin-top:20px}.commentForm label{display:block;font-size:13px;margin-bottom:10px}.page textarea{background:#f5f5f5;border:0;border-radius:0;padding:13px;width:100%;min-height:110px;line-height:1.6;resize:vertical}.commentForm button{margin-top:10px;float:right}-.signin{font-size:13px;line-height:1.7;color:#777;margin:15px 0}+.signin{font-size:13px;line-height:1.7;color:#666;margin:15px 0}.signin a{text-decoration:underline;text-underline-offset:3px;color:#242424}.error{font-size:13px;line-height:1.6;color:#a4483f;margin:15px 0}.submitRow{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}@@ -101,49 +101,51 @@.textLink{text-decoration:underline!important;text-underline-offset:3px}.fork{max-width:1050px;padding:45px 0 100px}.fork h1,.publish h1{font-size:38px;font-weight:400;letter-spacing:-1px;line-height:1.1;margin-bottom:15px}-.forkIntro{max-width:600px;color:#777;line-height:1.7;margin-bottom:40px}+.forkIntro{max-width:600px;color:#666;line-height:1.7;margin-bottom:40px}.forkColumns{display:grid;grid-template-columns:1fr 1fr;gap:50px}.forkColumns img{width:100%;height:auto;aspect-ratio:3/2;object-fit:cover}.fork h2{font-size:17px;font-weight:400;margin:28px 0 12px}-.fork p,.fork li{font-size:14px;line-height:1.75;color:#777}+.fork p,.fork li{font-size:14px;line-height:1.75;color:#666}.fork ul{padding-left:18px;margin-bottom:20px}.fork code{display:block;padding:18px;background:#f5f5f5;margin:15px 0;font-size:12px;overflow-wrap:anywhere;white-space:pre-wrap}.steps{list-style:none;counter-reset:steps}.steps li{counter-increment:steps;margin-bottom:30px;position:relative;padding-left:32px}-.steps li:before{content:counter(steps)'.';position:absolute;left:0;color:#999}+.steps li:before{content:counter(steps)'.';position:absolute;left:0;color:#707070}.steps strong{display:block;color:#242424;font-size:16px;font-weight:400;margin-bottom:9px}.publish{padding:40px 0 100px;max-width:1120px}.publishForm{display:grid;grid-template-columns:1fr 1fr;gap:30px 45px;margin-top:36px}.field{display:flex;flex-direction:column;gap:9px;font-size:13px}.field input,.field select{border:0;background:#f5f5f5;padding:13px;min-width:0;width:100%;border-radius:0}-.field small{color:#888;font-size:11px;line-height:1.6}+.field small{color:#6b6b6b;font-size:11px;line-height:1.6}.wide{grid-column:1/-1}.publish textarea{min-height:170px;font:12px/1.7 ui-monospace,monospace}.publishPreview{margin:35px 0}.publishPreview h2{font-size:16px;font-weight:400;margin-bottom:15px}.publishPreview iframe{width:100%;height:440px;border:0;background:#f5f5f5}-.check{display:flex;gap:11px;align-items:flex-start;color:#777;font-size:13px;line-height:1.7;margin:25px 0}+.check{display:flex;gap:11px;align-items:flex-start;color:#666;font-size:13px;line-height:1.7;margin:25px 0}.check input{margin-top:5px;accent-color:#242424}-.loading{padding:70px 0;color:#777}+.loading{padding:70px 0;color:#666}@media(min-width:1900px){.viewer iframe{height:780px}}@media(max-width:1100px){.wrap{width:90%}.nav{gap:20px}.barActions{gap:18px}.chat{padding-left:22px}.identity h1{font-size:22px}.viewer iframe{height:640px}}@media(max-width:760px){.wrap{width:92%}.feed{padding-top:22px}.grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:44px 14px}.split{grid-template-columns:1fr;gap:28px;min-height:0}.chat{padding:0}.detail{padding-top:16px;padding-bottom:50px}.back{margin-bottom:14px}.detailHead{flex-wrap:wrap;gap:16px;margin-bottom:22px}.actions{margin-left:auto}.viewer iframe{height:590px}.forkColumns,.publishForm{grid-template-columns:1fr;gap:25px}.fork h1,.publish h1{font-size:32px}.page input,.page textarea,.page select{font-size:16px}}@media(max-width:480px){.grid{grid-template-columns:1fr;gap:36px}.actions{width:100%;margin-left:0}.actions>:last-child{margin-left:auto}.identity h1{font-size:23px}.viewer iframe{height:510px;height:min(560px,68svh)}.fork{padding-top:20px}.publish{padding-top:24px}.fork h1,.publish h1{font-size:28px}.publishForm{gap:25px}}.tags{display:inline-flex;gap:5px;flex-wrap:wrap;align-items:center}-.tags>span{display:inline-block;background:#f3f3f1;color:#747471;font:10px/1.5 Arial,Helvetica,sans-serif;padding:3px 7px;border-radius:3px;white-space:nowrap}+.tags>span{display:inline-block;background:#f3f3f1;color:#5f5f5c;font:10px/1.5 Arial,Helvetica,sans-serif;padding:3px 7px;border-radius:3px;white-space:nowrap}.cardMeta{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:12px}.cardMeta small{margin:0}/* Its help floats under the button, so opening the app never moves the row it sits in. */.handoff{position:relative;display:inline-flex}-.filesReview{margin:30px 0}.filesReview summary{cursor:pointer;font-size:14px}.fileRow{display:flex;align-items:center;gap:12px;margin:10px 0;font-size:12px}.fileRow code{flex:1;overflow-wrap:anywhere}.fileRow button{text-decoration:underline;color:#777}.importActions{margin:24px 0;background:#f7f7f5;padding:22px}.importActions p{color:#777;font-size:13px;margin-top:8px}+.filesReview{margin:30px 0}.filesReview summary{cursor:pointer;font-size:14px}.fileRow{display:flex;align-items:center;gap:12px;margin:10px 0;font-size:12px}.fileRow code{flex:1;overflow-wrap:anywhere}.fileRow button{text-decoration:underline;color:#666}.importActions{margin:24px 0;background:#f7f7f5;padding:22px}.importActions p{color:#666;font-size:13px;margin-top:8px}/* Phones: one sticky glass bar. Brand and actions on the first row, the tabs under them, and an open search across its own row. */@media(max-width:760px){.topbar{position:sticky;top:0;z-index:20;background:rgba(255,255,255,.82);-webkit-backdrop-filter:saturate(180%) blur(18px);backdrop-filter:saturate(180%) blur(18px);box-shadow:0 1px 0 rgba(36,36,36,.07)}.bar{flex-wrap:wrap;gap:0 16px;min-height:0;padding:4px 0 0}.bar .brand{font-size:21px;margin-right:auto}.barActions{display:contents;font-size:14px}.barActions>a,.barActions>button{order:1}.page .barActions .primary{min-height:34px;padding:6px 14px}.barActions .openApp{display:none}.nav{order:2;width:100%;gap:24px;font-size:14px}.nav a{position:relative;min-height:42px}.nav [aria-current=page]:after{content:'';position:absolute;left:0;right:0;bottom:0;height:2px;background:#242424}.barActions>.searchField{order:3;width:100%;margin:4px 0 10px;animation:none}}+/* The narrowest phones (320px): brand, search, Publish and Sign in still share the first row. */+@media(max-width:360px){.bar{gap:0 10px}.bar .brand{font-size:19px}.page .barActions .primary{padding:6px 12px}}.handoffHelp{position:absolute;top:calc(100% + 8px);left:0;z-index:5;white-space:nowrap;font-size:12px;line-height:1.5;color:#666;padding:8px 12px;border-radius:10px;background:rgba(255,255,255,.78);-webkit-backdrop-filter:saturate(180%) blur(18px);backdrop-filter:saturate(180%) blur(18px);border:1px solid rgba(36,36,36,.08);box-shadow:0 8px 24px rgba(36,36,36,.1);animation:handoffIn .18s ease-out}.actions .handoffHelp{left:auto;right:0}@keyframes handoffIn{from{opacity:0;transform:translateY(-4px)}}@media(prefers-reduced-motion:reduce){.handoffHelp{animation:none}}.handoffHelp a{margin-left:4px;color:#242424!important;text-decoration:underline;text-underline-offset:3px}-.fork details{margin-top:32px;color:#777;font-size:13px}+.fork details{margin-top:32px;color:#666;font-size:13px}.fork summary{cursor:pointer}.recording{display:block;width:100%;height:720px;object-fit:contain;background:#191b1b}@@ -167,7 +169,7 @@/* A finger swipes the row; the fades are enough there, and the arrows would take a narrow row's room. */@media(hover:none){.page .chipArrow{display:none}}.chips::-webkit-scrollbar{display:none}-.page .chips button,.page .sort button{display:inline-flex;align-items:center;padding:0;flex-shrink:0;color:#777;white-space:nowrap}+.page .chips button,.page .sort button{display:inline-flex;align-items:center;padding:0;flex-shrink:0;color:#666;white-space:nowrap}.chips span,.sort span{display:block;padding:6px 12px;font-size:13px;line-height:1.5;border-radius:999px;transition:background-color .15s,color .15s,box-shadow .15s}.page .chips button{scroll-snap-align:start}.page .chips button:last-child{margin-right:36px}@@ -187,7 +189,7 @@@media(prefers-reduced-motion:reduce){.skeleton .cover,.skeleton span{animation:none}}/* The output's full-screen control, on a slim bar under it. */.viewerBar{display:flex;justify-content:flex-end;background:#fff}-.page .viewerBar button{display:inline-flex;align-items:center;gap:6px;padding:8px 0 0;font-size:12px;color:#777}+.page .viewerBar button{display:inline-flex;align-items:center;gap:6px;padding:8px 0 0;font-size:12px;color:#666}.page .viewerBar button:hover{color:#242424}.viewerBar svg{width:14px;height:14px}.viewer:fullscreen{background:#fff}@@ -198,7 +200,7 @@.sourceFile{border-bottom:1px solid #efefed;font-size:12px}.sourceFile summary{display:flex;align-items:center;gap:12px;padding:10px 0;cursor:pointer}.sourceFile summary code{flex:1;min-width:0;overflow-wrap:anywhere}-.sourceFile summary small{color:#999;font-size:11px}+.sourceFile summary small{color:#707070;font-size:11px}.sourceFile pre{margin-bottom:12px}.forks{margin-top:70px}.forks h2{font-size:17px;font-weight:400;margin-bottom:26px}@@ -209,7 +211,7 @@.byline a,.byline button{display:inline-flex;align-items:center}@media(max-width:760px){.chat{scroll-margin-top:104px}}.authorLink:hover{text-decoration:underline}-.reportForm{display:flex;flex-direction:column;gap:2px;margin:0 0 30px;padding:18px 20px;background:#f7f7f5;font-size:13px}.reportForm .check{margin:6px 0}.reportForm small{color:#777;margin:8px 0 4px}.reportForm .submitRow{margin:8px 0 0}-.review{border-bottom:1px solid #efefed;padding:16px 0;font-size:13px;display:flex;flex-direction:column;gap:6px}.review p{color:#777}.review .submitRow{margin:4px 0 0}+.reportForm{display:flex;flex-direction:column;gap:2px;margin:0 0 30px;padding:18px 20px;background:#f7f7f5;font-size:13px}.reportForm .check{margin:6px 0}.reportForm small{color:#666;margin:8px 0 4px}.reportForm .submitRow{margin:8px 0 0}+.review{border-bottom:1px solid #efefed;padding:16px 0;font-size:13px;display:flex;flex-direction:column;gap:6px}.review p{color:#666}.review .submitRow{margin:4px 0 0}.bell{position:relative;display:inline-flex}.bell svg{width:19px;height:19px}.badge{position:absolute;top:-7px;right:-9px;min-width:16px;height:16px;padding:0 4px;border-radius:8px;background:#a4483f;color:#fff;font-size:10px;line-height:16px;text-align:center}-.notification{display:flex;justify-content:space-between;gap:16px;padding:14px 0;border-bottom:1px solid #efefed;font-size:14px}.notification small{color:#999;flex-shrink:0}.notification.unread{font-weight:500}+.notification{display:flex;justify-content:space-between;gap:16px;padding:14px 0;border-bottom:1px solid #efefed;font-size:14px}.notification small{color:#707070;flex-shrink:0}.notification.unread{font-weight:500}diff --git a/website/src/app/hub/components/Comments.tsx b/website/src/app/hub/components/Comments.tsxindex c780deeb8..e21b4048b 100644--- a/website/src/app/hub/components/Comments.tsx+++ b/website/src/app/hub/components/Comments.tsx@@ -3,26 +3,25 @@ import { useRef, useState } from 'react';import { commentTotal, threadComments } from '@/lib/community/comments';import type { ReportReason } from '@/lib/community/reports';import type { HarnessComment, SocialState } from '@/lib/community/types';+import { timeAgo } from '@/lib/community/time';import { SignIn } from './Header';import { ReportForm } from './ReportForm';import styles from '../community.module.css';type Props = {- social: SocialState; ready: boolean; busy: boolean; onRetry: () => void; onEarlier: () => Promise<boolean>;+ social: SocialState; ready: boolean; failed: boolean; busy: boolean; onRetry: () => void; onEarlier: () => Promise<boolean>;onRemove: (comment: HarnessComment) => void; onPost: (body: string, clientId: string, parentId?: string) => Promise<boolean>;onReport: (comment: HarnessComment, reason: ReportReason) => Promise<boolean>;};-const day = (createdAt: string) => new Date(createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });-type CommentProps = { comment: HarnessComment; busy: boolean; canReply: boolean; onReply: () => void; onRemove: () => void; onReport: (reason: ReportReason) => Promise<boolean> };function Comment({ comment, busy, canReply, onReply, onRemove, onReport }: CommentProps) {const [reporting, setReporting] = useState(false);return <article className={`${styles.comment} ${comment.parentId ? styles.reply : ''}`}><div className={styles.commentBy}>- <span>{comment.authorName}</span>{comment.creator && <em className={styles.creator}>Creator</em>}<small>{day(comment.createdAt)}</small>- {comment.mine && <button disabled={busy} aria-label={`Delete comment by ${comment.authorName}`} onClick={onRemove}>Delete</button>}+ <span>{comment.authorName}</span>{comment.creator && <em className={styles.creator}>Creator</em>}<small><time dateTime={comment.createdAt} title={new Date(comment.createdAt).toLocaleString()}>{timeAgo(comment.createdAt)}</time></small>+ {comment.mine && <button disabled={busy} aria-label={`Delete comment by ${comment.authorName}`} onClick={() => { if (window.confirm('Delete this comment? This cannot be undone.')) onRemove(); }}>Delete</button>}{!comment.mine && canReply && <button disabled={busy} aria-label={`Report comment by ${comment.authorName}`} onClick={() => setReporting(true)}>Report</button>}</div>{comment.parentId && <small className={styles.replyContext}>Replying to {comment.parentAuthorName}</small>}@@ -43,7 +42,7 @@ function EarlierComments({ shown, total, onEarlier }: { shown: number; total: nu}/** The conversation under a harness: the comments, each reply under its thread, and a form to add one or reply to one. */-export function Comments({ social, ready, busy, onRetry, onEarlier, onRemove, onReport, onPost }: Props) {+export function Comments({ social, ready, failed, busy, onRetry, onEarlier, onRemove, onReport, onPost }: Props) {const [draft, setDraft] = useState(''), [replyTo, setReplyTo] = useState<HarnessComment | null>(null);// Kept across a failed post, so a retry of the same text is recognised as the same comment.const requestId = useRef<string | null>(null);@@ -55,15 +54,17 @@ export function Comments({ social, ready, busy, onRetry, onEarlier, onRemove, onsetDraft(''); setReplyTo(null); requestId.current = null;}return <>- {!ready && <p className={styles.notice}>Comments are unavailable right now. <button onClick={onRetry}>Retry</button></p>}+ {/* Until the first read lands the panel is loading, not failed, and does not yet know who is reading. */}+ {!ready && !failed && <div className={styles.skeleton} aria-busy aria-label="Loading comments"><span /><span /></div>}+ {!ready && failed && <p className={styles.notice}>Comments are unavailable right now. <button onClick={onRetry}>Retry</button></p>}{ready && !social.comments.length && <p className={styles.notice}>What would you make from here?</p>}{ready && commentTotal(social) > social.comments.length && <EarlierComments shown={social.comments.length} total={commentTotal(social)} onEarlier={onEarlier} />}{threadComments(social.comments).map(comment => <Comment key={comment.id} comment={comment} busy={busy} canReply={social.signedIn} onReply={() => reply(comment)} onRemove={() => onRemove(comment)} onReport={reason => onReport(comment, reason)} />)}- {social.signedIn ? <form className={styles.commentForm} onSubmit={event => { event.preventDefault(); void submit(); }}>+ {ready && (social.signedIn ? <form className={styles.commentForm} onSubmit={event => { event.preventDefault(); void submit(); }}><label htmlFor="comment">{replyTo ? `Reply to ${replyTo.authorName}` : 'Join the conversation'}</label>{replyTo && <button type="button" className={styles.replyButton} onClick={() => reply(null)}>Cancel reply</button>}<textarea id="comment" required maxLength={2000} value={draft} onChange={event => { setDraft(event.target.value); requestId.current = null; }} placeholder="Ask a question or share an idea…" /><button className={styles.primary} disabled={busy || !draft.trim()}>{replyTo ? 'Post reply' : 'Post comment'}</button>- </form> : <SignIn />}+ </form> : <SignIn />)}</>;}diff --git a/website/src/app/hub/components/CreatorPage.tsx b/website/src/app/hub/components/CreatorPage.tsxindex fb852cea4..21e5138ff 100644--- a/website/src/app/hub/components/CreatorPage.tsx+++ b/website/src/app/hub/components/CreatorPage.tsx@@ -1,14 +1,16 @@'use client';-import type { FeedView } from '@/lib/community/feed';+import type { FeedPage, FeedView } from '@/lib/community/feed';import type { Creator } from '@/lib/community/types';import { CreatorHead } from './CreatorHead';import Feed from './Feed';import { Unavailable } from './Unavailable';import { useCreator } from './useCreator';-/** One creator: who they are and their harnesses, narrowed and ordered like any feed. */-export default function CreatorPage({ id, initial, initialView }: { id: string; initial: Creator | null; initialView: FeedView }) {+type Props = { id: string; initial: Creator | null; initialView: FeedView; initialPage?: FeedPage | null };++/** One creator: who they are and their harnesses, narrowed and ordered like any feed; the server's first page draws their cards at once. */+export default function CreatorPage({ id, initial, initialView, initialPage }: Props) {const page = useCreator(id, initial);if (page.unavailable) return <Unavailable what="creator" />;- return <Feed author={id} initialView={initialView} intro={<CreatorHead creator={page.creator} busy={page.busy} error={page.error} signIn={page.signIn} onFollow={() => void page.follow()} onRetry={() => void page.load()} />} />;+ return <Feed author={id} initialView={initialView} initialPage={initialPage} intro={<CreatorHead creator={page.creator} busy={page.busy} error={page.error} signIn={page.signIn} onFollow={() => void page.follow()} onRetry={() => void page.load()} />} />;}diff --git a/website/src/app/hub/components/Detail.tsx b/website/src/app/hub/components/Detail.tsxindex 2e065da6b..48a620a99 100644--- a/website/src/app/hub/components/Detail.tsx+++ b/website/src/app/hub/components/Detail.tsx@@ -10,6 +10,8 @@ import { Header } from './Header';import { ReportForm } from './ReportForm';import { SidePanel } from './SidePanel';import { useCanonicalAddress } from './useCanonicalAddress';+import { useHarnessDwell, useHubView } from './useHubView';+import { countHub } from '@/lib/community/hubMeasure';import { Unavailable } from './Unavailable';import { useHarnessDetail } from './useHarnessDetail';import { Viewer } from './Viewer';@@ -19,18 +21,21 @@ export default function Detail({ id, initial, initialComments = false }: { id: sconst [panel, setPanel] = useState<Panel>(initialComments ? 'comments' : 'log'), [reporting, setReporting] = useState(false);const page = useHarnessDetail(id, initial, () => setPanel('comments'));const { harness, social, ready, busy } = page;- useCanonicalAddress(harness);+ useCanonicalAddress(harness); useHubView('harness'); useHarnessDwell();if (page.unavailable || page.reported) return <Unavailable what="harness" reported={page.reported} />;if (!harness) return <><Header /><main className={`${styles.wrap} ${styles.loading}`}>{page.error || 'Loading harness…'}{page.error && <button onClick={() => void page.load()}>Retry</button>}</main></>;// A panel's button opens it; pressed again, it returns to the chat log.- const toggle = (next: Panel) => setPanel(current => current === next ? 'log' : next);+ const toggle = (next: Panel) => {+ if (panel !== next && next !== 'log') countHub(next === 'comments' ? 'hub_comments_open' : 'hub_files_open');+ setPanel(current => current === next ? 'log' : next);+ };return <><Header /><main className={`${styles.wrap} ${styles.detail}`}><Link className={styles.back} href="/hub"><ArrowLeft /> All harnesses</Link><DetailHead harness={harness} social={social} ready={ready} busy={busy} panel={panel} onFollow={() => void page.follow()} onLike={() => void page.like()} onPanel={toggle} onReport={() => setReporting(true)} />{reporting && <ReportForm what="harness" onReport={page.report} onCancel={() => setReporting(false)} />}<DetailNotice social={social} ready={ready} failed={page.failed} onRetry={() => void page.load()} /><div className={styles.split}><Viewer harness={harness} />- <SidePanel harness={harness} social={social} ready={ready} busy={busy} panel={panel} error={page.error}+ <SidePanel harness={harness} social={social} ready={ready} failed={page.failed || !!page.error} busy={busy} panel={panel} error={page.error}onClose={() => setPanel('log')} onRetry={() => void page.load()} onEarlier={page.loadEarlier} onReport={page.reportComment} onRemove={comment => void page.removeComment(comment)} onPost={page.postComment} /></div>{!!social.forks && <Forks id={harness.id} count={social.forks} />}diff --git a/website/src/app/hub/components/DetailHead.tsx b/website/src/app/hub/components/DetailHead.tsxindex 31b4bfad8..c74c9476b 100644--- a/website/src/app/hub/components/DetailHead.tsx+++ b/website/src/app/hub/components/DetailHead.tsx@@ -21,18 +21,19 @@ export function DetailHead({ harness, social, ready, busy, panel, onFollow, onLireturn <header className={styles.detailHead}><div className={styles.identity}><h1>{harness.title}</h1><div className={styles.byline}><Link className={styles.authorLink} href={`/hub/creators/${harness.authorId}`}>{harness.authorName}</Link>- {!social.mine && <button className={styles.follow} disabled={busy} aria-pressed={social.following} onClick={onFollow}>{social.following ? 'Following' : 'Follow'}</button>}+ {/* Shown once the reader is known: an author must not see Follow on their own harness, even for a moment. */}+ {ready && !social.mine && <button className={styles.follow} disabled={busy} aria-pressed={social.following} onClick={onFollow}>{social.following ? 'Following' : 'Follow'}</button>}<ForkedFrom harness={harness} />{!!social.forks && <a className={styles.textLink} href="#forks">{social.forks === 1 ? '1 fork' : `${social.forks} forks`}</a>}</div></div><div className={styles.actions}>- <button className={social.liked ? styles.liked : ''} disabled={busy} aria-label={social.liked ? 'Unlike harness' : 'Like harness'} aria-pressed={social.liked} onClick={onLike}><Heart /><span>{ready ? social.likes : 'Like'}</span></button>- <button aria-label="Comments" aria-pressed={panel === 'comments'} onClick={() => onPanel('comments')}><MessageCircle /><span>{ready ? commentTotal(social) : 'Comments'}</span></button>+ <button className={social.liked ? styles.liked : ''} disabled={busy || !ready} aria-label={social.liked ? 'Unlike harness' : 'Like harness'} aria-pressed={social.liked} onClick={onLike}><Heart /><span>{ready ? social.likes : '–'}</span></button>+ <button aria-label="Comments" aria-pressed={panel === 'comments'} onClick={() => onPanel('comments')}><MessageCircle /><span>{ready ? commentTotal(social) : '–'}</span></button><button aria-label="Source files" aria-pressed={panel === 'files'} onClick={() => onPanel('files')}><FileCode2 /><span className={styles.actionLabel}>Files</span></button><ShareMenu harness={harness} />{social.mine && <Link href={`/hub/publish?edit=${harness.id}`}><Pencil /><span>Edit</span></Link>}{/* Not your own, and not a starter: those are the Hub's. */}- {!social.mine && !harness.example && <button aria-label="Report harness" onClick={onReport}><Flag /><span className={styles.actionLabel}>Report</span></button>}+ {ready && !social.mine && !harness.example && <button aria-label="Report harness" onClick={onReport}><Flag /><span className={styles.actionLabel}>Report</span></button>}<ForkButton harness={harness}><GitFork /> Fork</ForkButton></div></header>;diff --git a/website/src/app/hub/components/ExploreIntro.tsx b/website/src/app/hub/components/ExploreIntro.tsxnew file mode 100644index 000000000..7232f0ed6--- /dev/null+++ b/website/src/app/hub/components/ExploreIntro.tsx@@ -0,0 +1,26 @@+'use client';+import { useEffect } from 'react';+import Link from 'next/link';+import { countHub } from '@/lib/community/hubMeasure';+import { rememberHubReturn } from '@/lib/community/session';+import { webAppPath } from '@/lib/webApp';+import { useSignedIn } from './useSignedIn';+import styles from './explore.module.css';++/**+ * What the Hub is, for someone arriving at it: drawn by the server for search engines and a first+ * look. Until a sign-in is known, a visitor is assumed, and is offered the app and a sign-in.+ */+export function ExploreIntro() {+ const signedIn = useSignedIn();+ // The sign-in offered here is a prompt like any other, counted once it is known to be a visitor's.+ useEffect(() => { if (signedIn === false) countHub('hub_sign_in_prompt_shown'); }, [signedIn]);+ return <section className={styles.intro}>+ <h1>What people make with agents</h1>+ <p>Open the output, read the conversation that made it, and fork the project into Harness to make your own version.</p>+ {signedIn !== true && <div className={styles.cta}>+ <Link className={styles.get} href="/desktop" onClick={() => countHub('hub_get_app')}>Get the Harness desktop app</Link>+ <a className={styles.signIn} href={webAppPath} onClick={() => { countHub('hub_sign_in_prompt_click'); rememberHubReturn(); }}>Sign in</a>+ </div>}+ </section>;+}diff --git a/website/src/app/hub/components/Feed.tsx b/website/src/app/hub/components/Feed.tsxindex 498f6b00d..a3553f51e 100644--- a/website/src/app/hub/components/Feed.tsx+++ b/website/src/app/hub/components/Feed.tsx@@ -1,14 +1,17 @@'use client';-import type { ReactNode } from 'react';+import { useEffect, useRef, type ReactNode } from 'react';import Link from 'next/link';import { defaultFeedView, inFeedOrder, type FeedPage, type FeedView } from '@/lib/community/feed';import { starterHarnesses } from '@/lib/community/starters';import type { HarnessSummary } from '@/lib/community/types';import { FeedCard, FeedSkeleton } from './FeedCard';import { FeedFilters } from './FeedFilters';+import { FeedToast } from './FeedToast';import { Header, SignIn } from './Header';import { useFeed } from './useFeed';import { useFeedView } from './useFeedView';+import { useHubView } from './useHubView';+import { countHub } from '@/lib/community/hubMeasure';import styles from '../community.module.css';/** Starters are the website's own, so they are matched here; publications are matched by the server. */@@ -17,6 +20,16 @@ function matches(item: HarnessSummary, { query, category }: FeedView) {return `${item.title} ${item.description} ${item.authorName} ${item.category} ${item.engine} ${item.harnessName || ''}`.toLowerCase().includes(query.toLowerCase());}+/** A search the reader settled on (the view's term is debounced), once each time it changes; not the one a page opened with. */+function useCountSearch(query: string) {+ const last = useRef(query);+ useEffect(() => {+ if (query === last.current) return;+ last.current = query;+ if (query) countHub('hub_feed_search');+ }, [query]);+}+function EmptyFeed({ narrowed, mine, author }: { narrowed: boolean; mine: boolean; author: boolean }) {if (narrowed) return <div className={styles.empty}><h1>Nothing here yet.</h1><p>Try a different search or category.</p></div>;if (author) return <div className={styles.empty}><h1>Nothing published here yet.</h1></div>;@@ -25,14 +38,15 @@ function EmptyFeed({ narrowed, mine, author }: { narrowed: boolean; mine: boolea}/**- * `initialPage` is the first page of `initialView` as the server read it for a visitor (Explore only).+ * `initialPage` is the first page of `initialView` as the server read it for a visitor (Explore, and a creator's page).* `author` narrows the feed to one creator's harnesses, under `intro` (their page's head).*/type Props = { following?: boolean; mine?: boolean; author?: string; intro?: ReactNode; initialView?: FeedView; initialPage?: FeedPage | null };export default function Feed({ following = false, mine = false, author, intro, initialView = defaultFeedView, initialPage }: Props) {const search = useFeedView(initialView), { view } = search;- const { posts, order, follows, stats, cursor, settled, error, likeError, signedOut, busy, liking, more, load, like } = useFeed({ following, mine, author, ...view }, initialPage);+ useHubView(author ? 'creator' : 'feed'); useCountSearch(view.query);+ const { posts, order, follows, stats, cursor, settled, error, likeError, likePrompt, dismissLike, signedOut, busy, liking, more, load, like } = useFeed({ following, mine, author, ...view }, initialPage);const narrowed = !!(view.query || view.category);// Starters follow the last page: drawn sooner, every page loaded while scrolling would land above// them. A narrowed view or a failed page shows them at once: there is nothing to scroll past.@@ -48,14 +62,14 @@ export default function Feed({ following = false, mine = false, author, intro, i<main className={`${styles.wrap} ${styles.feed}`}>{mine && <div className={styles.feedIntro}><h1>Your harnesses</h1><p>See what people like, join the conversation, and share your next version.</p></div>}{intro}- <FeedFilters category={view.category} sort={view.sort} onCategory={search.setCategory} onSort={search.setSort} />+ <FeedFilters category={view.category} sort={view.sort} onCategory={category => { if (category) countHub('hub_feed_category'); search.setCategory(category); }} onSort={sort => { countHub(`hub_feed_sort_${sort}`); search.setSort(sort); }} />{error && <p className={styles.notice} role="status">{error}<button onClick={() => void load()}>Retry</button></p>}- {likeError && <p className={styles.notice} role="status">{likeError}</p>}{signedOut && <SignIn action={following ? 'see creators you follow' : 'join the Hub'} />}<div className={styles.grid} aria-busy={!settled}>{settled ? visible.map(item => <FeedCard key={item.id} item={item} stats={stats[item.id]} liking={liking.has(item.id)} onLike={() => void like(item.id)} />) : <FeedSkeleton />}</div>{settled && !visible.length && !busy && !signedOut && <EmptyFeed narrowed={narrowed} mine={mine} author={!!author} />}<div ref={more}>{cursor && <button className={styles.more} disabled={busy} onClick={() => void load(cursor)}>{busy ? 'Loading…' : 'More harnesses'}</button>}</div>+ <FeedToast error={likeError} signIn={likePrompt} onDismiss={dismissLike} /></main></>;}diff --git a/website/src/app/hub/components/FeedCard.tsx b/website/src/app/hub/components/FeedCard.tsxindex f71de959a..558695058 100644--- a/website/src/app/hub/components/FeedCard.tsx+++ b/website/src/app/hub/components/FeedCard.tsx@@ -4,6 +4,7 @@ import { GitFork, Heart, MessageCircle } from 'lucide-react';import type { Stats } from '@/lib/community/feed';import type { HarnessSummary } from '@/lib/community/types';import { harnessPath } from '@/lib/community/slug';+import { countHub } from '@/lib/community/hubMeasure';import { HarnessTags } from './HarnessTags';import styles from '../community.module.css';@@ -13,7 +14,7 @@ type Props = { item: HarnessSummary; stats?: Stats; liking: boolean; onLike: ()export function FeedCard({ item, stats, liking, onLike }: Props) {const path = harnessPath(item);return <article className={styles.card}>- <Link href={path} aria-label={`Open ${item.title}`}>+ <Link href={path} aria-label={`Open ${item.title}`} onClick={() => countHub('hub_card_open')}>{item.cover ? <img className={styles.cover} src={item.cover} alt="" width={900} height={600} loading="lazy" /> : <div className={styles.blankCover}>{item.title}</div>}<h2>{item.title}</h2><p>{item.description}</p></Link>diff --git a/website/src/app/hub/components/FeedToast.tsx b/website/src/app/hub/components/FeedToast.tsxnew file mode 100644index 000000000..8fc84cc25--- /dev/null+++ b/website/src/app/hub/components/FeedToast.tsx@@ -0,0 +1,22 @@+'use client';+import { useEffect } from 'react';+import { X } from 'lucide-react';+import { SignIn } from './Header';+import styles from './toast.module.css';++type Props = { error: string; signIn: boolean; onDismiss: () => void };++/** What became of a like, at the bottom of the screen where the reader can see it, whichever card they are at; it leaves after a while. */+export function FeedToast({ error, signIn, onDismiss }: Props) {+ const open = signIn || !!error;+ useEffect(() => {+ if (!open) return;+ const timer = setTimeout(onDismiss, 8000);+ return () => clearTimeout(timer);+ }, [open, error, signIn, onDismiss]);+ if (!open) return null;+ return <div className={styles.toast} role="status">+ {signIn ? <SignIn action="like harnesses and follow creators" /> : <p>{error}</p>}+ <button type="button" aria-label="Dismiss" onClick={onDismiss}><X /></button>+ </div>;+}diff --git a/website/src/app/hub/components/ForkButton.tsx b/website/src/app/hub/components/ForkButton.tsxindex 957a442a1..fbf5fedb8 100644--- a/website/src/app/hub/components/ForkButton.tsx+++ b/website/src/app/hub/components/ForkButton.tsx@@ -1,18 +1,42 @@'use client';-import { useState, type ReactNode } from 'react';+import { useState, useSyncExternalStore, type ReactNode } from 'react';import Link from 'next/link';import { desktopForkLink, forkRequestId } from '@/lib/community/handoff';import { harnessPath } from '@/lib/community/slug';+import { countHub } from '@/lib/community/hubMeasure';import styles from '../community.module.css';-/** Hands the harness to the desktop app by its id; the page for anyone without the app is at its web address. */-export function ForkButton({ harness, children = 'Open in Harness' }: { harness: { id: string; title: string }; children?: ReactNode }) {- const [opened, setOpened] = useState(false), id = harness.id;+const desktop = '(hover: hover) and (pointer: fine)';+const onPointerChange = (notify: () => void) => {+ const query = window.matchMedia?.(desktop);+ query?.addEventListener('change', notify);+ return () => query?.removeEventListener('change', notify);+};+/** Whether this is a computer the desktop app could run on. The server draws the computer's button: the Hub is mouse-first. */+const useComputer = () => useSyncExternalStore(onPointerChange, () => window.matchMedia?.(desktop).matches ?? true, () => true);++type Props = { harness: { id: string; title: string }; children?: ReactNode; onForkPage?: boolean };++/**+ * Hands the harness to the desktop app by its id. A phone has no desktop app to open, so there the+ * button leads to the fork page, and on that page it copies the address to open on a computer.+ */+export function ForkButton({ harness, children = 'Open in Harness', onForkPage = false }: Props) {+ const [opened, setOpened] = useState(false), [copied, setCopied] = useState(false), computer = useComputer();+ const path = harnessPath(harness);+ if (!computer && !onForkPage) return <Link className={styles.primary} href={`${path}/fork`} onClick={() => countHub('hub_fork')}>{children}</Link>;+ if (!computer) return <span className={styles.handoff}>+ <button className={styles.primary} onClick={() => void navigator.clipboard.writeText(`${window.location.origin}${path}/fork`).then(() => setCopied(true), () => undefined)}>+ {copied ? 'Link copied' : 'Copy link for your computer'}+ </button>+ {copied && <span className={styles.handoffHelp} role="status">Open it on your computer to fork in Harness.</span>}+ </span>;return <span className={styles.handoff}><button className={styles.primary} onClick={() => {// Stay in the click gesture: browsers can ask permission to open the app.- window.location.href = desktopForkLink(id, forkRequestId(id)); setOpened(true);+ countHub('hub_fork');+ window.location.href = desktopForkLink(harness.id, forkRequestId(harness.id)); setOpened(true);}}>{children}</button>- {opened && <span className={styles.handoffHelp} role="status">Opening Harness… <Link href={`${harnessPath(harness)}/fork`}>Need the app?</Link></span>}+ {opened && <span className={styles.handoffHelp} role="status">Opening Harness… <Link href={`${path}/fork`} onClick={() => countHub('hub_fork_need_app')}>Need the app?</Link></span>}</span>;}diff --git a/website/src/app/hub/components/Forks.tsx b/website/src/app/hub/components/Forks.tsxindex ddfd3e03a..665a92b3c 100644--- a/website/src/app/hub/components/Forks.tsx+++ b/website/src/app/hub/components/Forks.tsx@@ -1,18 +1,31 @@'use client';+import { useEffect, useRef } from 'react';import { FeedCard, FeedSkeleton } from './FeedCard';+import { FeedToast } from './FeedToast';import { useFeed } from './useFeed';import styles from '../community.module.css';+/**+ * A `#forks` link (a card's fork count) arrives before this section exists, since it is drawn once the+ * harness's counts are read: the browser's own jump has passed, so the section takes the reader there.+ */+function useRevealForksLink() {+ const section = useRef<HTMLElement>(null);+ useEffect(() => { if (window.location.hash === '#forks') section.current?.scrollIntoView({ block: 'start' }); }, []);+ return section;+}+/** The public versions people made from this harness, newest first, paged like a feed. */export function Forks({ id, count }: { id: string; count: number }) {- const { posts, stats, cursor, settled, error, likeError, liking, busy, more, load, like } = useFeed({ forkedFrom: id });- return <section id="forks" className={styles.forks} aria-label="Forks">+ const { posts, stats, cursor, settled, error, likeError, likePrompt, dismissLike, liking, busy, more, load, like } = useFeed({ forkedFrom: id });+ const section = useRevealForksLink();+ return <section ref={section} id="forks" className={styles.forks} aria-label="Forks"><h2>Forks · {count}</h2>{error && <p className={styles.notice} role="status">The forks could not be loaded.<button onClick={() => void load()}>Retry</button></p>}- {likeError && <p className={styles.notice} role="status">{likeError}</p>}<div className={styles.grid} aria-busy={!settled}>{settled ? posts.map(item => <FeedCard key={item.id} item={item} stats={stats[item.id]} liking={liking.has(item.id)} onLike={() => void like(item.id)} />) : <FeedSkeleton count={3} />}</div><div ref={more}>{cursor && <button className={styles.more} disabled={busy} onClick={() => void load(cursor)}>{busy ? 'Loading…' : 'More forks'}</button>}</div>+ <FeedToast error={likeError} signIn={likePrompt} onDismiss={dismissLike} /></section>;}diff --git a/website/src/app/hub/components/Header.tsx b/website/src/app/hub/components/Header.tsxindex b29db3f3f..c8132a687 100644--- a/website/src/app/hub/components/Header.tsx+++ b/website/src/app/hub/components/Header.tsx@@ -1,6 +1,8 @@'use client';+import { useEffect } from 'react';import Link from 'next/link';import { ArrowUpRight, Bell } from 'lucide-react';+import { countHub } from '@/lib/community/hubMeasure';import { rememberHubReturn } from '@/lib/community/session';import { webAppPath } from '@/lib/webApp';import { SearchField, type SearchFieldProps } from './SearchField';@@ -42,6 +44,8 @@ export function Header({ tab, search }: { tab?: HubTab; search?: SearchFieldProp</div></header>;}+/** Asks a visitor to sign in where an action needs an account; each time it is drawn and each click are counted. */export function SignIn({ action = 'join the conversation' }: { action?: string }) {- return <p className={styles.signin}><a href={webAppPath} onClick={rememberHubReturn}>Sign in to Harness</a> to {action}. You’ll return here afterward.</p>;+ useEffect(() => { countHub('hub_sign_in_prompt_shown'); }, []);+ return <p className={styles.signin}><a href={webAppPath} onClick={() => { countHub('hub_sign_in_prompt_click'); rememberHubReturn(); }}>Sign in to Harness</a> to {action}. You’ll return here afterward.</p>;}diff --git a/website/src/app/hub/components/HubFooter.tsx b/website/src/app/hub/components/HubFooter.tsxnew file mode 100644index 000000000..9a3fb4782--- /dev/null+++ b/website/src/app/hub/components/HubFooter.tsx@@ -0,0 +1,15 @@+import community from '../community.module.css';+import styles from './footer.module.css';++const links = [+ { href: '/desktop', label: 'Harness desktop app' }, { href: '/download', label: 'Download' },+ { href: '/agents', label: 'For agents' }, { href: '/os', label: 'Harness operating system' },+];++/** Under every Hub page: where Harness itself is, for a reader who arrived at a harness first. Plain links: they leave the Hub. */+export function HubFooter() {+ return <footer className={styles.footer}><div className={`${community.wrap} ${styles.inner}`}>+ <span>Harness by Autonomous</span>+ <nav aria-label="Harness">{links.map(link => <a key={link.href} href={link.href}>{link.label}</a>)}</nav>+ </div></footer>;+}diff --git a/website/src/app/hub/components/HubView.tsx b/website/src/app/hub/components/HubView.tsxnew file mode 100644index 000000000..19f73fc72--- /dev/null+++ b/website/src/app/hub/components/HubView.tsx@@ -0,0 +1,9 @@+'use client';+import type { HubViewPage } from '@/lib/community/hubMetrics';+import { useHubView } from './useHubView';++/** Counts a page the server draws (it cannot use the hook itself): draws nothing. */+export function HubView({ page }: { page: HubViewPage }) {+ useHubView(page);+ return null;+}diff --git a/website/src/app/hub/components/ShareMenu.tsx b/website/src/app/hub/components/ShareMenu.tsxindex 7e8c5c424..073fbb145 100644--- a/website/src/app/hub/components/ShareMenu.tsx+++ b/website/src/app/hub/components/ShareMenu.tsx@@ -5,6 +5,8 @@ import { harnessPath } from '@/lib/community/slug';import { shareNetworks, shareUrl } from '@/lib/community/share';import { SocialIcon } from './SocialIcons';import { useDismiss } from './useDismiss';+import { useMenuKeys } from './useMenuKeys';+import { countHub } from '@/lib/community/hubMeasure';import community from '../community.module.css';import styles from './share.module.css';@@ -29,23 +31,27 @@ function useCopy(onDone: () => void) {/** Share opens a menu: copy the harness's address, post it to X, Facebook or LinkedIn, or use the device's own sheet. */export function ShareMenu({ harness }: { harness: { id: string; title: string } }) {- const [open, setOpen] = useState(false), root = useRef<HTMLSpanElement>(null), sheet = useShareSheet();- const close = useCallback(() => setOpen(false), []);+ const [open, setOpen] = useState(false), root = useRef<HTMLSpanElement>(null), menu = useRef<HTMLDivElement>(null), button = useRef<HTMLButtonElement>(null);+ const sheet = useShareSheet(), close = useCallback(() => setOpen(false), []);const { copy, copyText } = useCopy(close);useDismiss(root, open, close);+ const onMenuKey = useMenuKeys(menu, button, open, close);const url = () => `${window.location.origin}${harnessPath(harness)}`;// A sheet closed without choosing anything is not a failure to report.- const openSheet = () => { close(); void navigator.share({ title: harness.title, url: url() }).catch(() => undefined); };+ const openSheet = () => { countHub('hub_share_sheet'); close(); void navigator.share({ title: harness.title, url: url() }).catch(() => undefined); };return <span ref={root} className={styles.share}>- <button type="button" className={community.actionButton} aria-haspopup="menu" aria-expanded={open} aria-pressed={open} onClick={() => setOpen(value => !value)}>+ <button ref={button} type="button" className={community.actionButton} aria-haspopup="menu" aria-expanded={open} onClick={() => { if (!open) countHub('hub_share_open'); setOpen(!open); }}+ onKeyDown={event => { if (event.key === 'ArrowDown' && !open) { event.preventDefault(); countHub('hub_share_open'); setOpen(true); } }}><Link2 /><span className={community.actionLabel}>Share</span></button>- {open && <div className={styles.menu} role="menu" aria-label="Share this harness">- <button type="button" role="menuitem" className={copy === 'copied' ? styles.done : ''} onClick={() => void copyText(url())}>+ {/* Focus leaving the menu (a click elsewhere, Tab past its end) closes it, as useDismiss does for the pointer. */}+ {open && <div ref={menu} className={styles.menu} role="menu" aria-label="Share this harness" onKeyDown={onMenuKey}+ onBlur={event => { if (!root.current?.contains(event.relatedTarget as Node | null)) close(); }}>+ <button type="button" role="menuitem" className={copy === 'copied' ? styles.done : ''} onClick={() => { countHub('hub_share_copy'); void copyText(url()); }}>{copy === 'copied' ? <Check /> : <Link2 />}<span aria-live="polite">{copyLabels[copy]}</span></button><hr />- {shareNetworks.map(network => <a key={network.id} role="menuitem" href={shareUrl(network.id, url(), harness.title)} target="_blank" rel="noopener noreferrer" onClick={close}>+ {shareNetworks.map(network => <a key={network.id} role="menuitem" href={shareUrl(network.id, url(), harness.title)} target="_blank" rel="noopener noreferrer" onClick={() => { countHub(`hub_share_${network.id}`); close(); }}><SocialIcon network={network.id} /><span>{network.label}</span></a>)}{sheet && <><hr /><button type="button" role="menuitem" onClick={openSheet}><Share2 /><span>More options…</span></button></>}diff --git a/website/src/app/hub/components/SidePanel.tsx b/website/src/app/hub/components/SidePanel.tsxindex 503462a4f..852774bce 100644--- a/website/src/app/hub/components/SidePanel.tsx+++ b/website/src/app/hub/components/SidePanel.tsx@@ -13,7 +13,7 @@ import { useHarnessFiles } from './useHarnessFiles';import styles from '../community.module.css';type Props = {- harness: OpenHarness; social: SocialState; ready: boolean; busy: boolean; panel: Panel; error: string;+ harness: OpenHarness; social: SocialState; ready: boolean; failed: boolean; busy: boolean; panel: Panel; error: string;onClose: () => void; onRetry: () => void; onEarlier: () => Promise<boolean>; onRemove: (comment: HarnessComment) => void;onReport: (comment: HarnessComment, reason: ReportReason) => Promise<boolean>;onPost: (body: string, clientId: string, parentId?: string) => Promise<boolean>;@@ -21,9 +21,12 @@ type Props = {const titles: Record<Panel, string> = { log: 'Chat log', comments: 'Comments', files: 'Source files' };-/** On a phone the panel sits under the output: one the reader opens is brought into view, not left below it. */+/**+ * On a phone the panel sits under the output: one the reader opens is brought into view, not left below it,+ * and so is one the page opens with (a comments link from a card or a notification).+ */function useRevealOnOpen(panel: Panel) {- const aside = useRef<HTMLElement>(null), opened = useRef(panel);+ const aside = useRef<HTMLElement>(null), opened = useRef<Panel>('log');useEffect(() => {if (panel === opened.current) return;opened.current = panel;@@ -33,13 +36,13 @@ function useRevealOnOpen(panel: Panel) {}/** Beside the output: the agent's chat log, or the comments, or the project's files. */-export function SidePanel({ harness, social, ready, busy, panel, error, onClose, onRetry, onEarlier, onRemove, onReport, onPost }: Props) {+export function SidePanel({ harness, social, ready, failed, busy, panel, error, onClose, onRetry, onEarlier, onRemove, onReport, onPost }: Props) {const files = useHarnessFiles(harness.id, panel === 'files'), aside = useRevealOnOpen(panel);const title = panel === 'comments' && ready ? `Comments · ${commentTotal(social)}` : titles[panel];return <aside ref={aside} className={styles.chat} aria-label={panel === 'log' ? 'Agent chat log' : titles[panel]}><div className={styles.chatHead}><h2>{title}</h2>{panel === 'log' ? <HarnessTags harness={harness} /> : <button className={styles.icon} onClick={onClose} aria-label="Back to chat log"><X /></button>}</div>{panel === 'log' && <Transcript harness={harness} />}- {panel === 'comments' && <Comments social={social} ready={ready} busy={busy} onRetry={onRetry} onEarlier={onEarlier} onRemove={onRemove} onReport={onReport} onPost={onPost} />}+ {panel === 'comments' && <Comments social={social} ready={ready} failed={failed} busy={busy} onRetry={onRetry} onEarlier={onEarlier} onRemove={onRemove} onReport={onReport} onPost={onPost} />}{panel === 'files' && <HarnessFiles id={harness.id} files={files.files} error={files.error} onRetry={() => void files.load()} />}{error && <p className={styles.error} role="alert">{error}</p>}</aside>;diff --git a/website/src/app/hub/components/Viewer.tsx b/website/src/app/hub/components/Viewer.tsxindex 6742d8dff..ee301b428 100644--- a/website/src/app/hub/components/Viewer.tsx+++ b/website/src/app/hub/components/Viewer.tsx@@ -4,6 +4,7 @@ import { Maximize2, Minimize2 } from 'lucide-react';import { previewDocument } from '@/lib/community/preview';import type { OpenHarness } from '@/lib/community/types';import styles from '../community.module.css';+import { countHub } from '@/lib/community/hubMeasure';const onFullscreenChange = (notify: () => void) => {document.addEventListener('fullscreenchange', notify);@@ -32,7 +33,7 @@ export function Viewer({ harness }: { harness: OpenHarness }) {<iframe title={`${harness.title} output`} srcDoc={previewDocument(html)} sandbox={harness.example ? 'allow-scripts allow-downloads allow-modals' : 'allow-scripts'} referrerPolicy="no-referrer" />{/* Under the output, never over it: a corner control would cover the page's own controls. */}{fullscreen.supported && <div className={styles.viewerBar}>- <button type="button" onClick={fullscreen.toggle} aria-label={fullscreen.active ? 'Exit full screen' : 'View output full screen'}>+ <button type="button" onClick={() => { if (!fullscreen.active) countHub('hub_fullscreen'); fullscreen.toggle(); }} aria-label={fullscreen.active ? 'Exit full screen' : 'View output full screen'}>{fullscreen.active ? <Minimize2 /> : <Maximize2 />}<span>{fullscreen.active ? 'Exit full screen' : 'Full screen'}</span></button></div>}diff --git a/website/src/app/hub/components/community.spec.tsx b/website/src/app/hub/components/community.spec.tsxindex 12b720c22..361a09caf 100644--- a/website/src/app/hub/components/community.spec.tsx+++ b/website/src/app/hub/components/community.spec.tsx@@ -144,6 +144,50 @@ describe('community navigation', () => {window.history.replaceState(null, '', '/');}});+ it('reads as loading, not failed, until the reader is known, and offers no action that would need them', async () => {+ request.mockReturnValueOnce(new Promise(() => {}));+ render(<Detail id={sample.id} initial={sample} initialComments />);+ expect(screen.getByLabelText('Loading comments')).toBeInTheDocument();+ expect(screen.queryByText(/Comments are unavailable/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Sign in to Harness/)).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Like harness' })).toBeDisabled();+ expect(screen.queryByRole('button', { name: 'Follow' })).not.toBeInTheDocument();+ });+ it('sends a phone’s Fork to the fork page, which has no app to open', async () => {+ request.mockResolvedValue({ harness: null, social: emptySocial });+ Object.defineProperty(window, 'matchMedia', { configurable: true, value: () => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }) });+ render(<Detail id={sample.id} initial={sample} />);+ expect(screen.getByRole('link', { name: 'Fork' })).toHaveAttribute('href', '/hub/starter-orbit/fork');+ Object.defineProperty(window, 'matchMedia', { configurable: true, value: undefined });+ });+ it('moves through the Share menu by keyboard and returns to its button on Escape', async () => {+ request.mockResolvedValue({ harness: null, social: emptySocial });+ render(<Detail id={sample.id} initial={sample} />);+ const share = screen.getByRole('button', { name: 'Share' });+ fireEvent.keyDown(share, { key: 'ArrowDown' });+ await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Copy link' })).toHaveFocus());+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'ArrowDown' });+ expect(screen.getByRole('menuitem', { name: 'Share on X' })).toHaveFocus();+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'End' });+ expect(screen.getByRole('menuitem', { name: 'Share on LinkedIn' })).toHaveFocus();+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' });+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();+ expect(share).toHaveFocus();+ });+ it('likes from a card before the first page answers when this browser holds a sign-in, and asks a visitor at the bottom of the screen', async () => {+ const page = { harnesses: [{ ...sample, id: 'first', title: 'Server card' }], nextCursor: null, following: [], stats: {} };+ request.mockReturnValueOnce(new Promise(() => {}));+ const { unmount } = render(<Feed initialPage={page} />);+ fireEvent.click(screen.getByRole('button', { name: 'Like Server card' }));+ expect(await screen.findByRole('status')).toHaveTextContent('Sign in to Harness to like harnesses and follow creators');+ unmount();+ localStorage.setItem('harness.web.v1.auth_access_token', 'token');+ request.mockReturnValueOnce(new Promise(() => {})).mockResolvedValueOnce({ liked: true, likes: 1 });+ render(<Feed initialPage={page} />);+ fireEvent.click(screen.getByRole('button', { name: 'Like Server card' }));+ await waitFor(() => expect(request).toHaveBeenCalledWith('harnesses/first/like', expect.objectContaining({ method: 'PUT' })));+ localStorage.clear();+ });it('says so when a drawn page cannot load its likes and actions, and retries', async () => {const id = '0f8fad5b-d9cb-469f-a165-70867728950e';request.mockRejectedValueOnce(new CommunityError('Service unavailable', 503));diff --git a/website/src/app/hub/components/explore.module.css b/website/src/app/hub/components/explore.module.cssnew file mode 100644index 000000000..c9fa7a7ae--- /dev/null+++ b/website/src/app/hub/components/explore.module.css@@ -0,0 +1,10 @@+/* Explore's opening: a heading and one line, and for a visitor the two ways in. */+.intro{margin:6px 0 30px;max-width:640px}+.intro h1{font-size:30px;font-weight:400;letter-spacing:-.8px;line-height:1.15;color:#242424}+.intro p{margin-top:10px;font-size:14px;line-height:1.6;color:#666}+.cta{display:flex;flex-wrap:wrap;align-items:center;gap:10px 18px;margin-top:20px}+.intro .get{display:inline-flex;align-items:center;height:38px;padding:0 18px;border-radius:8px;background:#242424;color:#fff;font-size:13px;transition:background-color .15s}+.intro .get:hover{background:#000}+.intro .signIn{font-size:13px;color:#242424;text-decoration:underline;text-underline-offset:3px}+.intro .get:focus-visible,.intro .signIn:focus-visible{outline:2px solid #242424;outline-offset:2px}+@media(max-width:760px){.intro{margin-bottom:22px}.intro h1{font-size:25px}}diff --git a/website/src/app/hub/components/footer.module.css b/website/src/app/hub/components/footer.module.cssnew file mode 100644index 000000000..b1a7d4698--- /dev/null+++ b/website/src/app/hub/components/footer.module.css@@ -0,0 +1,5 @@+/* A quiet last line, the header's width (`.wrap`). */+.footer{border-top:1px solid #efefed;margin-top:40px}+.inner{padding:22px 0 calc(28px + env(safe-area-inset-bottom));display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px 24px;font-size:12px;color:#666}+.inner nav{display:flex;flex-wrap:wrap;gap:8px 22px}+.inner a:hover{color:#242424}diff --git a/website/src/app/hub/components/share.module.css b/website/src/app/hub/components/share.module.cssindex 16b29026a..5c49c0726 100644--- a/website/src/app/hub/components/share.module.css+++ b/website/src/app/hub/components/share.module.css@@ -2,7 +2,8 @@.share{position:relative;display:inline-flex}.menu{position:absolute;top:calc(100% + 8px);right:0;z-index:10;display:flex;flex-direction:column;min-width:228px;padding:6px;border-radius:14px;background:rgba(255,255,255,.93);-webkit-backdrop-filter:saturate(180%) blur(20px);backdrop-filter:saturate(180%) blur(20px);border:1px solid rgba(36,36,36,.08);box-shadow:0 12px 32px rgba(36,36,36,.12),0 2px 6px rgba(36,36,36,.05);animation:menuIn .16s ease-out;transform-origin:top right}.share .menu>button,.share .menu>a{display:flex;align-items:center;gap:11px;width:100%;height:38px;padding:0 11px;border-radius:9px;font-size:13px;color:#333;text-align:left;white-space:nowrap;transition:background-color .12s}-.share .menu>button:hover,.share .menu>a:hover,.share .menu>button:focus-visible,.share .menu>a:focus-visible{background:rgba(36,36,36,.06);outline:0}+.share .menu>button:hover,.share .menu>a:hover{background:rgba(36,36,36,.06)}+.share .menu>button:focus-visible,.share .menu>a:focus-visible{background:rgba(36,36,36,.06);outline:2px solid #242424;outline-offset:-2px}.menu svg{width:16px;height:16px;flex-shrink:0}.menu hr{height:1px;margin:5px 6px;border:0;background:rgba(36,36,36,.08)}.share .menu .done{color:#2f7a4f}diff --git a/website/src/app/hub/components/toast.module.css b/website/src/app/hub/components/toast.module.cssnew file mode 100644index 000000000..40c95935b--- /dev/null+++ b/website/src/app/hub/components/toast.module.css@@ -0,0 +1,8 @@+/* A glass note pinned to the bottom of the screen, above the page, clear of a phone's home bar. */+.toast{position:fixed;left:50%;bottom:calc(20px + env(safe-area-inset-bottom));z-index:30;translate:-50% 0;display:flex;align-items:center;gap:10px;max-width:min(520px,calc(100vw - 32px));padding:10px 10px 10px 18px;border-radius:14px;background:rgba(255,255,255,.9);-webkit-backdrop-filter:saturate(180%) blur(20px);backdrop-filter:saturate(180%) blur(20px);border:1px solid rgba(36,36,36,.08);box-shadow:0 12px 32px rgba(36,36,36,.14);font-size:13px;color:#333;animation:toastIn .2s ease-out}+.toast p{margin:0;line-height:1.5}+.toast button{flex-shrink:0;display:inline-flex;padding:6px;border-radius:8px;color:#666}+.toast button:hover{background:rgba(36,36,36,.06);color:#242424}+.toast svg{width:16px;height:16px}+@keyframes toastIn{from{opacity:0;transform:translateY(8px)}}+@media(prefers-reduced-motion:reduce){.toast{animation:none}}diff --git a/website/src/app/hub/components/useCreator.ts b/website/src/app/hub/components/useCreator.tsindex f2e02e360..45dda2a8c 100644--- a/website/src/app/hub/components/useCreator.ts+++ b/website/src/app/hub/components/useCreator.ts@@ -4,6 +4,7 @@ import { CommunityError, communityRequest } from '@/lib/community/client';import { onSessionChange } from '@/lib/community/session';import { putFollow } from '@/lib/community/social';import type { Creator } from '@/lib/community/types';+import { countHub } from '@/lib/community/hubMeasure';/*** A creator's page: who they are, read again with the reader's sign-in (the server read it as a@@ -27,6 +28,7 @@ export function useCreator(id: string, initial: Creator | null) {async function follow() {if (!creator || busy) return;if (!creator.signedIn) { setSignIn(true); return; }+ countHub('hub_follow');const next = !creator.following;setBusy(true); setError('');try {diff --git a/website/src/app/hub/components/useFeed.ts b/website/src/app/hub/components/useFeed.tsindex cc5a87655..9691dabd5 100644--- a/website/src/app/hub/components/useFeed.ts+++ b/website/src/app/hub/components/useFeed.ts@@ -1,10 +1,11 @@'use client';import { useCallback, useEffect, useRef, useState } from 'react';-import { communityRequest, CommunityError } from '@/lib/community/client';+import { communityRequest, CommunityError, sessionHeaders } from '@/lib/community/client';import { feedPath, type FeedPage, type FeedQuery, type Stats } from '@/lib/community/feed';import { onSessionChange } from '@/lib/community/session';import { putLike } from '@/lib/community/social';import type { HarnessSummary } from '@/lib/community/types';+import { countHub } from '@/lib/community/hubMeasure';/**@@ -21,10 +22,13 @@ export function useFeed({ following, mine, forkedFrom, author, query, category,const [cursor, setCursor] = useState<string | null>(initial?.nextCursor ?? null), [settled, setSettled] = useState(!!initial);const [order, setOrder] = useState<string[] | null>(initial?.order ?? null);const [error, setError] = useState(''), [likeError, setLikeError] = useState(''), [signedOut, setSignedOut] = useState(false), [busy, setBusy] = useState(false);+ // A like that needs an account: said where the reader is (FeedToast), not as the feed's own sign-in.+ const [likePrompt, setLikePrompt] = useState(false);const [liking, setLiking] = useState<ReadonlySet<string>>(new Set());const generation = useRef(0), loading = useRef(false), pendingLikes = useRef(new Set<string>()), more = useRef<HTMLDivElement>(null);const load = useCallback(async (after?: string) => {if (after && loading.current) return;+ if (after) countHub('hub_feed_more');const requestId = ++generation.current;loading.current = true; setBusy(true); setError(''); setSignedOut(false);try {@@ -56,17 +60,20 @@ export function useFeed({ following, mine, forkedFrom, author, query, category,setLiking(new Set(pendingLikes.current));};async function like(id: string) {- if (!signedIn) { setSignedOut(true); return; }+ // Before the first page answers the feed cannot say who is reading: a browser holding a sign-in tries, and the Hub decides.+ if (!signedIn && !sessionHeaders().Authorization) { setLikePrompt(true); return; }if (pendingLikes.current.has(id)) return;- pending(id, true); setLikeError('');+ countHub('hub_like');+ pending(id, true); setLikeError(''); setLikePrompt(false);try {const result = await putLike(id, !stats[id]?.liked);setStats(previous => ({ ...previous, [id]: { ...previous[id], comments: previous[id]?.comments || 0, ...result } }));} catch (e) {- if (e instanceof CommunityError && e.status === 401) setSignedOut(true);+ if (e instanceof CommunityError && e.status === 401) setLikePrompt(true);// Not the feed's error: that one offers to reload the feed and pauses its paging.else setLikeError(e instanceof Error ? e.message : 'Could not save your like. Try again.');} finally { pending(id, false); }}- return { posts, order, follows, stats, cursor, settled, error, likeError, signedOut, busy, liking, more, load, like };+ const dismissLike = useCallback(() => { setLikeError(''); setLikePrompt(false); }, []);+ return { posts, order, follows, stats, cursor, settled, error, likeError, likePrompt, dismissLike, signedOut, busy, liking, more, load, like };}diff --git a/website/src/app/hub/components/useHarnessDetail.ts b/website/src/app/hub/components/useHarnessDetail.tsindex 0803cbb2b..04ae47eb9 100644--- a/website/src/app/hub/components/useHarnessDetail.ts+++ b/website/src/app/hub/components/useHarnessDetail.ts@@ -6,6 +6,7 @@ import { postReport, type ReportReason } from '@/lib/community/reports';import { putFollow, putLike } from '@/lib/community/social';import type { HarnessComment, OpenHarness, SocialState } from '@/lib/community/types';import { useRefreshOnReturn } from './useRefreshOnReturn';+import { countHub } from '@/lib/community/hubMeasure';/*** One harness page's data and the reader's actions on it. Writes run one at a time, and a read that@@ -80,11 +81,13 @@ export function useHarnessDetail(address: string, initial: OpenHarness | null, oconst follow = () => mutate(async () => {if (!harness) return;+ countHub('hub_follow');const next = !social.following;await putFollow(harness.authorId, next);setSocial(value => ({ ...value, following: next }));});const like = () => mutate(async () => {+ countHub('hub_like');const result = await putLike(id.current, !social.liked);setSocial(value => ({ ...value, ...result }));});@@ -95,11 +98,12 @@ export function useHarnessDetail(address: string, initial: OpenHarness | null, oawait communityRequest(`harnesses/${id.current}/comments/${comment.id}`, { method: 'DELETE' });dropComment(comment);});- const report = (reason: ReportReason) => mutate(async () => { await postReport('harness', id.current, reason); setReported(true); });- const reportComment = (comment: HarnessComment, reason: ReportReason) => mutate(async () => { await postReport('comment', comment.id, reason); dropComment(comment); });+ const report = (reason: ReportReason) => mutate(async () => { await postReport('harness', id.current, reason); countHub('hub_report'); setReported(true); });+ const reportComment = (comment: HarnessComment, reason: ReportReason) => mutate(async () => { await postReport('comment', comment.id, reason); countHub('hub_report'); dropComment(comment); });/** `clientId` makes a retried post return the same comment rather than a second one. */const postComment = (body: string, clientId: string, parentId?: string) => mutate(async () => {const data = await communityRequest<{ comment: HarnessComment }>(`harnesses/${id.current}/comments`, { method: 'POST', body: { body, clientId, ...(parentId ? { parentId } : {}) } });+ countHub('hub_comment_post');// A retried post answers with the comment it already made: replaced, not counted twice.setSocial(value => {const known = value.comments.some(item => item.id === data.comment.id);diff --git a/website/src/app/hub/components/useHubView.ts b/website/src/app/hub/components/useHubView.tsnew file mode 100644index 000000000..a88a42aa5--- /dev/null+++ b/website/src/app/hub/components/useHubView.ts@@ -0,0 +1,34 @@+'use client';+import { useEffect, useRef } from 'react';+import { countHub, countHubEntry, flushHub } from '@/lib/community/hubMeasure';+import { dwellBucket, type HubViewPage } from '@/lib/community/hubMetrics';+import { useSignedIn } from './useSignedIn';++/** A Hub page drawn, once per navigation, by a visitor or a member, as soon as it is known which; the first of a tab's visit also says where it came from. */+export function useHubView(page: HubViewPage) {+ const signedIn = useSignedIn(), counted = useRef(false);+ useEffect(() => {+ if (signedIn === null || counted.current) return;+ counted.current = true;+ countHub(`hub_view_${page}_${signedIn ? 'member' : 'visitor'}`);+ countHubEntry();+ }, [page, signedIn]);+}++/** How long a harness page stayed in view (hidden time not counted), counted once as it is left: a navigation, or the tab closing. */+export function useHarnessDwell() {+ useEffect(() => {+ let shown = 0, since: number | null = document.visibilityState === 'visible' ? performance.now() : null, done = false;+ const pause = () => { if (since !== null) { shown += performance.now() - since; since = null; } };+ const visibility = () => { if (document.visibilityState === 'visible') since ??= performance.now(); else pause(); };+ const finish = () => {+ if (done) return;+ done = true; pause(); countHub(dwellBucket(shown));+ };+ // The tab closing: counted, then sent with the rest before the page goes.+ const leave = () => { finish(); flushHub(); };+ document.addEventListener('visibilitychange', visibility);+ window.addEventListener('pagehide', leave);+ return () => { document.removeEventListener('visibilitychange', visibility); window.removeEventListener('pagehide', leave); finish(); };+ }, []);+}diff --git a/website/src/app/hub/components/useMenuKeys.ts b/website/src/app/hub/components/useMenuKeys.tsnew file mode 100644index 000000000..c6c9ba938--- /dev/null+++ b/website/src/app/hub/components/useMenuKeys.ts@@ -0,0 +1,22 @@+'use client';+import { useEffect, type KeyboardEvent, type RefObject } from 'react';++const items = (menu: HTMLElement | null) => [...(menu?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [])];++/**+ * A menu button's keyboard: opening moves focus to the first item, the arrows (and Home and End) move+ * between items, and Escape or Tab closes it — Escape back to its button.+ */+export function useMenuKeys(menu: RefObject<HTMLElement | null>, button: RefObject<HTMLElement | null>, open: boolean, onClose: () => void) {+ useEffect(() => { if (open) items(menu.current)[0]?.focus(); }, [menu, open]);+ return (event: KeyboardEvent) => {+ const all = items(menu.current), at = all.indexOf(document.activeElement as HTMLElement);+ const move = (index: number) => { event.preventDefault(); all[(index + all.length) % all.length]?.focus(); };+ if (event.key === 'ArrowDown') move(at + 1);+ else if (event.key === 'ArrowUp') move(at - 1);+ else if (event.key === 'Home') move(0);+ else if (event.key === 'End') move(all.length - 1);+ else if (event.key === 'Escape') { event.preventDefault(); onClose(); button.current?.focus(); }+ else if (event.key === 'Tab') onClose();+ };+}diff --git a/website/src/app/hub/creators/[id]/page.tsx b/website/src/app/hub/creators/[id]/page.tsxindex d1f3b35e2..6d98dc67e 100644--- a/website/src/app/hub/creators/[id]/page.tsx+++ b/website/src/app/hub/creators/[id]/page.tsx@@ -2,7 +2,7 @@ import type { Metadata } from 'next';import { cache } from 'react';import { notFound } from 'next/navigation';import { feedViewFromParams, type FeedViewParams } from '@/lib/community/feed';-import { getCreator, serverReadMs } from '@/lib/community/server';+import { getCreator, getFeedPage, serverReadMs } from '@/lib/community/server';import CreatorPage from '../../components/CreatorPage';type Props = { params: Promise<{ id: string }>; searchParams: Promise<FeedViewParams> };@@ -12,12 +12,17 @@ const validId = (id: string) => /^[a-z0-9-]{1,80}$/.test(id);const readCreator = cache(async (id: string) => validId(id) ? getCreator(id, serverReadMs) : null);export async function generateMetadata({ params }: Props): Promise<Metadata> {- const creator = await readCreator((await params).id);- return { title: creator?.name ?? 'Creator' };+ const id = (await params).id, creator = await readCreator(id);+ // Not read here (no publications, or a slow Hub): nothing for a search engine to keep.+ if (!creator) return { title: 'Creator', robots: { index: false } };+ const title = creator.name, description = `What ${creator.name} made with agents, on Harness Hub: like it, join the conversation, and fork your own version.`;+ return { title, description, alternates: { canonical: `/hub/creators/${id}` }, openGraph: { type: 'profile', title, description, url: `/hub/creators/${id}`, siteName: 'Harness Hub' }, twitter: { card: 'summary', title, description } };}export default async function CreatorRoute({ params, searchParams }: Props) {const { id } = await params;if (!validId(id)) notFound();- return <CreatorPage key={id} id={id} initial={await readCreator(id)} initialView={await feedViewFromParams(searchParams)} />;+ const view = await feedViewFromParams(searchParams);+ const [initial, initialPage] = await Promise.all([readCreator(id), getFeedPage({ ...view, author: id }, serverReadMs)]);+ return <CreatorPage key={id} id={id} initial={initial} initialView={view} initialPage={initialPage} />;}diff --git a/website/src/app/hub/following/layout.tsx b/website/src/app/hub/following/layout.tsxnew file mode 100644index 000000000..d3e6e1780--- /dev/null+++ b/website/src/app/hub/following/layout.tsx@@ -0,0 +1,4 @@+import { PassThrough, privateMetadata } from '../privatePage';++export const metadata = privateMetadata('Following');+export default PassThrough;diff --git a/website/src/app/hub/layout.tsx b/website/src/app/hub/layout.tsxindex 16cc71f1d..a3814b0b6 100644--- a/website/src/app/hub/layout.tsx+++ b/website/src/app/hub/layout.tsx@@ -1,7 +1,13 @@import type { Metadata, Viewport } from 'next';+import { HubFooter } from './components/HubFooter';import styles from './community.module.css';/** Absolute addresses for link previews (a harness's cover); the Hub is served from this origin. */-export const metadata: Metadata = { metadataBase: new URL('https://harness.autonomous.ai'), title: { default: 'Harness Hub — Discover, fork, create', template: '%s — Harness Hub' }, description: 'Discover what people make with agents. Like the work, join the conversation, fork your own version, and publish what you make.' };+const title = 'Harness Hub — Discover, fork, create', description = 'Discover what people make with agents. Like the work, join the conversation, fork your own version, and publish what you make.';+export const metadata: Metadata = {+ metadataBase: new URL('https://harness.autonomous.ai'), title: { default: title, template: '%s — Harness Hub' }, description,+ // A link to the Hub itself previews as the Hub; a harness or creator page sets its own.+ openGraph: { type: 'website', siteName: 'Harness Hub', title, description, url: '/hub' }, twitter: { card: 'summary', title, description },+};export const viewport: Viewport = { themeColor: '#ffffff' };-export default function ExploreLayout({ children }: { children: React.ReactNode }) { return <div className={styles.page}>{children}</div>; }+export default function ExploreLayout({ children }: { children: React.ReactNode }) { return <div className={styles.page}>{children}<HubFooter /></div>; }diff --git a/website/src/app/hub/notifications/layout.tsx b/website/src/app/hub/notifications/layout.tsxnew file mode 100644index 000000000..164d64278--- /dev/null+++ b/website/src/app/hub/notifications/layout.tsx@@ -0,0 +1,4 @@+import { PassThrough, privateMetadata } from '../privatePage';++export const metadata = privateMetadata('Notifications');+export default PassThrough;diff --git a/website/src/app/hub/notifications/notifications.module.css b/website/src/app/hub/notifications/notifications.module.cssindex 247c20ba9..492c5b31e 100644--- a/website/src/app/hub/notifications/notifications.module.css+++ b/website/src/app/hub/notifications/notifications.module.css@@ -2,7 +2,7 @@.inbox{padding:40px 0 100px}.head{margin-bottom:26px}.head h1{font-size:30px;font-weight:400;letter-spacing:-.8px;line-height:1.15}-.head p{margin-top:6px;font-size:13px;color:#888}+.head p{margin-top:6px;font-size:13px;color:#6b6b6b}.list{list-style:none;margin:0;padding:6px;border:1px solid #efefed;border-radius:16px;background:#fff;box-shadow:0 1px 2px rgba(36,36,36,.03)}.row{position:relative;display:grid;grid-template-columns:40px minmax(0,1fr) auto;align-items:center;gap:14px;padding:12px 14px;border-radius:11px;font-size:14px;line-height:1.45;color:#555;transition:background-color .15s}@@ -17,7 +17,7 @@.kind{position:absolute;right:-3px;bottom:-3px;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;background:#242424;color:#fff;box-shadow:0 0 0 2px #fff}.kind svg{width:11px;height:11px}.text{min-width:0;overflow-wrap:anywhere}-.time{font-size:12px;color:#999;white-space:nowrap;padding-right:8px}+.time{font-size:12px;color:#707070;white-space:nowrap;padding-right:8px}.skeleton{display:grid;grid-template-columns:40px 1fr;gap:14px;align-items:center;padding:12px 14px}.skeleton span{height:12px;border-radius:6px;background:linear-gradient(100deg,#efeeeb 40%,#f7f6f3 50%,#efeeeb 60%) 0 0/200% 100%;animation:shimmer 1.4s linear infinite}@@ -27,8 +27,8 @@.placeholder{display:flex;flex-direction:column;align-items:center;text-align:center;gap:10px;padding:56px 24px;border:1px solid #efefed;border-radius:16px;background:linear-gradient(180deg,#fafaf8,#fff)}.placeholder h2{font-size:17px;font-weight:600;color:#242424}-.placeholder p{max-width:340px;margin:0;font-size:13px;line-height:1.6;color:#777}-.placeholderIcon{display:inline-flex;align-items:center;justify-content:center;width:52px;height:52px;margin-bottom:4px;border-radius:50%;background:rgba(255,255,255,.7);border:1px solid #ecebe8;box-shadow:0 6px 18px rgba(36,36,36,.06);color:#777}+.placeholder p{max-width:340px;margin:0;font-size:13px;line-height:1.6;color:#666}+.placeholderIcon{display:inline-flex;align-items:center;justify-content:center;width:52px;height:52px;margin-bottom:4px;border-radius:50%;background:rgba(255,255,255,.7);border:1px solid #ecebe8;box-shadow:0 6px 18px rgba(36,36,36,.06);color:#666}.placeholderIcon svg{width:22px;height:22px}.placeholder .retry{margin-top:6px;height:36px;padding:0 18px;border-radius:8px;background:#242424;color:#fff;font-size:13px}.placeholder .retry:hover{background:#000}diff --git a/website/src/app/hub/notifications/page.tsx b/website/src/app/hub/notifications/page.tsxindex 11a1be44b..a4a937840 100644--- a/website/src/app/hub/notifications/page.tsx+++ b/website/src/app/hub/notifications/page.tsx@@ -5,6 +5,7 @@ import { Bell } from 'lucide-react';import { Header, SignIn } from '../components/Header';import { NotificationRow, NotificationSkeleton } from './NotificationRow';import { useNotifications, type NotificationsState } from './useNotifications';+import { useHubView } from '../components/useHubView';import community from '../community.module.css';import styles from './notifications.module.css';@@ -28,6 +29,7 @@ function Body({ state, retry }: ReturnType<typeof useNotifications>) {/** The reader's notifications, latest first. */export default function NotificationsPage() {const notifications = useNotifications();+ useHubView('notifications');return <><Header /><main className={`${community.wrap} ${styles.inbox}`}><header className={styles.head}><h1>Notifications</h1><p>{subtitle(notifications.state)}</p></header><Body {...notifications} />diff --git a/website/src/app/hub/page.tsx b/website/src/app/hub/page.tsxindex 8194c671e..a66407081 100644--- a/website/src/app/hub/page.tsx+++ b/website/src/app/hub/page.tsx@@ -1,9 +1,10 @@import { feedViewFromParams, type FeedViewParams } from '@/lib/community/feed';import { getFeedPage, serverReadMs } from '@/lib/community/server';+import { ExploreIntro } from './components/ExploreIntro';import Feed from './components/Feed';type Props = { searchParams: Promise<FeedViewParams> };/** Explore is drawn with its first page, for search engines and a first paint with cards; a slow Hub does not hold it. */export default async function ExplorePage({ searchParams }: Props) {const view = await feedViewFromParams(searchParams);- return <Feed initialView={view} initialPage={await getFeedPage(view, serverReadMs)} />;+ return <Feed intro={<ExploreIntro />} initialView={view} initialPage={await getFeedPage(view, serverReadMs)} />;}diff --git a/website/src/app/hub/privatePage.ts b/website/src/app/hub/privatePage.tsnew file mode 100644index 000000000..add1982e1--- /dev/null+++ b/website/src/app/hub/privatePage.ts@@ -0,0 +1,8 @@+import type { Metadata } from 'next';+import type { ReactNode } from 'react';++/** A page that is one reader's own (their notifications, what they follow, a draft): its own title, and nothing for a search engine to keep. */+export const privateMetadata = (title: string): Metadata => ({ title, robots: { index: false, follow: true } });++/** A route's layout that only names its page. */+export const PassThrough = ({ children }: { children: ReactNode }) => children;diff --git a/website/src/app/hub/publish/layout.tsx b/website/src/app/hub/publish/layout.tsxnew file mode 100644index 000000000..903c47369--- /dev/null+++ b/website/src/app/hub/publish/layout.tsx@@ -0,0 +1,4 @@+import { PassThrough, privateMetadata } from '../privatePage';++export const metadata = privateMetadata('Publish a harness');+export default PassThrough;diff --git a/website/src/app/hub/publish/page.tsx b/website/src/app/hub/publish/page.tsxindex 83519f131..b8433cec0 100644--- a/website/src/app/hub/publish/page.tsx+++ b/website/src/app/hub/publish/page.tsx@@ -18,6 +18,8 @@ import { PublishTarget } from './components/PublishTarget';import { UnpublishAction } from './components/UnpublishAction';import { originalOutput, readCover, readProjectFolder } from './projectFiles';import { harnessPath } from '@/lib/community/slug';+import { countHub } from '@/lib/community/hubMeasure';+import { useHubView } from '../components/useHubView';import { submitPublication, unpublishPublication } from './publication';import { usePublishDraft, type PublishDraft } from './usePublishDraft';import { useEnglishDraft } from './useEnglishDraft';@@ -27,6 +29,7 @@ const reviewInputs = ['confirmation', 'secrets'];export default function PublishPage() {const router = useRouter(), signedIn = useSignedIn();+ useHubView('publish');const { draft, update, applyBundle, saveError, loadError, publishOnce } = usePublishDraft();const english = useEnglishDraft(draft, update, signedIn);const [confirmed, setConfirmed] = useState(false), [checkedSecrets, setCheckedSecrets] = useState(''), [busy, setBusy] = useState(false), [error, setError] = useState('');@@ -66,9 +69,12 @@ export default function PublishPage() {function publish(event: FormEvent) {event.preventDefault();if (!ready || busy) return;- setBusy(true); setError('');- void publishOnce(async clientId => { router.push(harnessPath({ id: await submitPublication(draft, clientId), title: draft.title })); })- .catch(e => setError(e instanceof Error ? e.message : 'Publication failed. Your draft is still here.')).finally(() => setBusy(false));+ setBusy(true); setError(''); countHub('hub_publish_started');+ void publishOnce(async clientId => {+ const id = await submitPublication(draft, clientId);+ countHub('hub_publish_ok');+ router.push(harnessPath({ id, title: draft.title }));+ }).catch(e => { countHub('hub_publish_failed'); setError(e instanceof Error ? e.message : 'Publication failed. Your draft is still here.'); }).finally(() => setBusy(false));}function unpublish() {if (!draft.updateId || busy) return;diff --git a/website/src/app/hub/reports/layout.tsx b/website/src/app/hub/reports/layout.tsxnew file mode 100644index 000000000..82e772add--- /dev/null+++ b/website/src/app/hub/reports/layout.tsx@@ -0,0 +1,4 @@+import { PassThrough, privateMetadata } from '../privatePage';++export const metadata = privateMetadata('Reports');+export default PassThrough;diff --git a/website/src/app/hub/sitemap.ts b/website/src/app/hub/sitemap.tsnew file mode 100644index 000000000..70f5f42da--- /dev/null+++ b/website/src/app/hub/sitemap.ts@@ -0,0 +1,31 @@+import type { MetadataRoute } from 'next';+import type { FeedPage } from '@/lib/community/feed';+import { getFeedPage } from '@/lib/community/server';+import { harnessPath } from '@/lib/community/slug';+import { starterHarnesses } from '@/lib/community/starters';++const origin = 'https://harness.autonomous.ai';+/** Read again at most hourly; a slow or failing Hub leaves out what it could not read, never the starters. */+export const revalidate = 3600;+/** Newest first, a page at a time, up to this many: past it the oldest publications wait for the next read. */+const maxPages = 40, readMs = 4000;++/** The Hub for search engines (`/hub/sitemap.xml`, named in robots.txt): Explore, every starter and publication, and their creators. */+export default async function sitemap(): Promise<MetadataRoute.Sitemap> {+ const publications: FeedPage['harnesses'] = [];+ let cursor: string | null = null;+ for (let page = 0; page < maxPages; page++) {+ const read: FeedPage | null = await getFeedPage({ sort: 'newest' }, readMs, cursor ?? undefined);+ if (!read) break;+ publications.push(...read.harnesses.filter(item => !item.example));+ cursor = read.nextCursor;+ if (!cursor) break;+ }+ const creators = [...new Set(publications.map(item => item.authorId))];+ return [+ { url: `${origin}/hub`, changeFrequency: 'hourly', priority: 1 },+ ...starterHarnesses.map(item => ({ url: `${origin}${harnessPath(item)}`, changeFrequency: 'monthly' as const, priority: 0.6 })),+ ...publications.map(item => ({ url: `${origin}${harnessPath(item)}`, lastModified: item.updatedAt ?? item.createdAt, changeFrequency: 'weekly' as const, priority: 0.8 })),+ ...creators.map(id => ({ url: `${origin}/hub/creators/${id}`, changeFrequency: 'weekly' as const, priority: 0.5 })),+ ];+}diff --git a/website/src/app/hub/yours/layout.tsx b/website/src/app/hub/yours/layout.tsxnew file mode 100644index 000000000..c8eb17848--- /dev/null+++ b/website/src/app/hub/yours/layout.tsx@@ -0,0 +1,4 @@+import { PassThrough, privateMetadata } from '../privatePage';++export const metadata = privateMetadata('Your harnesses');+export default PassThrough;diff --git a/website/src/lib/community/hubMeasure.spec.ts b/website/src/lib/community/hubMeasure.spec.tsnew file mode 100644index 000000000..d0ca2510c--- /dev/null+++ b/website/src/lib/community/hubMeasure.spec.ts@@ -0,0 +1,47 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { countHub, countHubEntry, flushHub } from './hubMeasure';++const sent = () => (vi.mocked(fetch).mock.calls as [string, RequestInit][]).map(([url, init]) => ({ url, init, report: JSON.parse(String(init.body)) }));+const setNavigator = (key: string, value: unknown) => Object.defineProperty(navigator, key, { value, configurable: true });++beforeEach(() => { vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 204 }))); localStorage.clear(); sessionStorage.clear(); });+afterEach(() => { flushHub(); vi.unstubAllGlobals(); setNavigator('globalPrivacyControl', undefined); setNavigator('doNotTrack', null); });++describe('Hub measurement', () => {+ it('adds up a day’s counts and sends them once, without cookies', () => {+ countHub('hub_like'); countHub('hub_like'); countHub('hub_share_x');+ flushHub();+ const [request] = sent();+ expect(request.url).toBe('/api/hub-usage');+ expect(request.init.credentials).toBe('omit');+ expect(request.init.keepalive).toBe(true);+ expect(request.report).toMatchObject({ schemaVersion: 1, day: new Date().toISOString().slice(0, 10), counters: { hub_like: 2, hub_share_x: 1 } });+ expect(Object.keys(request.report).sort()).toEqual(['counters', 'day', 'id', 'schemaVersion']);+ flushHub();+ expect(fetch).toHaveBeenCalledTimes(1);+ });+ it('passes a sign-in only so the server can leave out a reader who turned sharing off', () => {+ localStorage.setItem('harness.web.v1.auth_access_token', 'token');+ countHub('hub_follow'); flushHub();+ expect((sent()[0].init.headers as Record<string, string>).Authorization).toBe('Bearer token');+ });+ it('counts nothing under Global Privacy Control, Do Not Track, or for a staging account', () => {+ setNavigator('globalPrivacyControl', true); countHub('hub_like'); flushHub();+ setNavigator('globalPrivacyControl', undefined); setNavigator('doNotTrack', '1'); countHub('hub_like'); flushHub();+ setNavigator('doNotTrack', null); localStorage.setItem('harness.web.v1.auth_autonomous_env', 'stag'); countHub('hub_like'); flushHub();+ expect(fetch).not.toHaveBeenCalled();+ });+ it('says where a tab’s visit came from once, never the referrer itself', () => {+ countHubEntry(); countHubEntry(); flushHub();+ const { report } = sent()[0];+ expect(report.counters).toEqual({ hub_entry_direct: 1 });+ expect(JSON.stringify(report)).not.toContain('http');+ });+ it('sends on its own after a while', () => {+ vi.useFakeTimers();+ countHub('hub_card_open');+ vi.advanceTimersByTime(60_000);+ expect(sent()[0].report.counters).toEqual({ hub_card_open: 1 });+ vi.useRealTimers();+ });+});diff --git a/website/src/lib/community/hubMeasure.ts b/website/src/lib/community/hubMeasure.tsnew file mode 100644index 000000000..b1cb2d535--- /dev/null+++ b/website/src/lib/community/hubMeasure.ts@@ -0,0 +1,67 @@+import { sessionHeaders } from './client';+import { entrySource, hubReportMaxValue, type HubMetric } from './hubMetrics';++/**+ * Counts what readers do on the Hub as daily totals, kept in this tab's memory and sent to the+ * website's server (`/api/hub-usage`) every so often and when the tab is hidden. The request carries+ * no cookies; a sign-in only lets the server leave out a reader who turned sharing off, and is never+ * passed on. Nothing is counted under Global Privacy Control or Do Not Track, for a staging account, or in development.+ * Counts lost to a failed send stay lost: measurement never retries into the reader's way.+ */+/**+ * A minute per tab, and once as it hides: the backend admits 240 Hub reports a minute per process, so+ * this holds about 200 tabs open at once before counts are dropped.+ * TODO(BE): past that, add the reports up on the website's server and send one a minute.+ */+const flushMs = 60_000, visitKey = 'harness.hub.visit';+const counts = new Map<HubMetric, number>();+let day = '', timer: ReturnType<typeof setTimeout> | null = null, listening = false;++const utcDay = () => new Date().toISOString().slice(0, 10);++function measuring(): boolean {+ // `next dev` reads the production Hub: a developer's clicks are not readers'.+ if (typeof window === 'undefined' || process.env.NODE_ENV === 'development') return false;+ const nav = navigator as Navigator & { globalPrivacyControl?: boolean };+ if (nav.globalPrivacyControl === true || nav.doNotTrack === '1') return false;+ return sessionHeaders()['x-autonomous-env'] !== 'stag';+}++/** Sends what is counted so far, once; called on a timer, when the day turns, and as the tab hides. */+export function flushHub(): void {+ if (timer) { clearTimeout(timer); timer = null; }+ if (!counts.size) return;+ const report = { schemaVersion: 1, id: crypto.randomUUID(), day, counters: Object.fromEntries(counts) };+ counts.clear();+ const auth = sessionHeaders().Authorization;+ void fetch('/api/hub-usage', {+ method: 'POST', keepalive: true, credentials: 'omit', cache: 'no-store',+ headers: { 'Content-Type': 'application/json', ...(auth ? { Authorization: auth } : {}) }, body: JSON.stringify(report),+ }).catch(() => undefined);+}++function listen() {+ if (listening) return;+ listening = true;+ window.addEventListener('pagehide', flushHub);+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flushHub(); });+}++/** One more of `metric` today. */+export function countHub(metric: HubMetric): void {+ if (!measuring()) return;+ listen();+ if (day && day !== utcDay()) flushHub();+ day = utcDay();+ counts.set(metric, Math.min((counts.get(metric) ?? 0) + 1, hubReportMaxValue));+ timer ??= setTimeout(flushHub, flushMs);+}++/** The first Hub page of this tab's visit says where the visit came from; a reload or the next page does not. */+export function countHubEntry(): void {+ try {+ if (sessionStorage.getItem(visitKey)) return;+ sessionStorage.setItem(visitKey, '1');+ } catch { return; }+ countHub(`hub_entry_${entrySource(document.referrer, window.location.hostname)}`);+}diff --git a/website/src/lib/community/hubMetrics.spec.ts b/website/src/lib/community/hubMetrics.spec.tsnew file mode 100644index 000000000..e3c3655bb--- /dev/null+++ b/website/src/lib/community/hubMetrics.spec.ts@@ -0,0 +1,33 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';+import * as backend from '../../../../backend/src/lib/hubMetricsContract';+import { dwellBucket, entrySource, hubActions, hubDwell, hubEntrySources, hubReportMaxValue, hubViewPages } from './hubMetrics';++describe('the Hub usage counters', () => {+ it('are the ones the backend accepts', () => {+ expect([...hubViewPages]).toEqual([...backend.HUB_VIEW_PAGES]);+ expect([...hubEntrySources]).toEqual([...backend.HUB_ENTRY_SOURCES]);+ expect([...hubDwell]).toEqual([...backend.HUB_DWELL]);+ expect([...hubActions]).toEqual([...backend.HUB_ACTIONS]);+ expect(hubReportMaxValue).toBe(backend.HUB_REPORT_MAX_VALUE);+ });+ it('class a visit by its referrer’s host alone', () => {+ const own = 'harness.autonomous.ai';+ expect(entrySource('', own)).toBe('direct');+ expect(entrySource('https://harness.autonomous.ai/desktop', own)).toBe('internal');+ expect(entrySource('https://www.google.com/', own)).toBe('search');+ expect(entrySource('https://duckduckgo.com/?q=harness', own)).toBe('search');+ expect(entrySource('https://t.co/abc', own)).toBe('social');+ expect(entrySource('https://m.facebook.com/', own)).toBe('social');+ expect(entrySource('https://news.ycombinator.com/item?id=1', own)).toBe('social');+ expect(entrySource('https://example.dev/post', own)).toBe('other');+ expect(entrySource('not a url', own)).toBe('other');+ // A host that only ends like one is not it.+ expect(entrySource('https://notx.com/', own)).toBe('other');+ });+ it('bucket a harness page’s time in view as the backend does', () => {+ expect(dwellBucket(9_999)).toBe('hub_harness_dwell_under_10s');+ expect(dwellBucket(10_000)).toBe('hub_harness_dwell_10s_to_1m');+ expect(dwellBucket(60_000)).toBe('hub_harness_dwell_over_1m');+ });+});diff --git a/website/src/lib/community/hubMetrics.ts b/website/src/lib/community/hubMetrics.tsnew file mode 100644index 000000000..984e13077--- /dev/null+++ b/website/src/lib/community/hubMetrics.ts@@ -0,0 +1,37 @@+/**+ * The Hub's usage counters, as the backend accepts them (`backend/src/lib/hubMetricsContract.ts`;+ * `hubMetrics.spec.ts` fails when the two drift). Fixed daily totals only: no identifiers, URLs or content.+ */+export const hubViewPages = ['feed', 'harness', 'creator', 'publish', 'notifications', 'fork'] as const;+export const hubEntrySources = ['direct', 'search', 'social', 'internal', 'other'] as const;+export const hubDwell = ['under_10s', '10s_to_1m', 'over_1m'] as const;+export const hubActions = [+ 'feed_search', 'feed_category', 'feed_sort_newest', 'feed_sort_popular', 'feed_sort_trending', 'feed_more', 'card_open',+ 'like', 'comment_post', 'comments_open', 'files_open', 'fullscreen',+ 'share_open', 'share_copy', 'share_x', 'share_facebook', 'share_linkedin', 'share_sheet',+ 'fork', 'fork_need_app', 'follow', 'report',+ 'sign_in_prompt_shown', 'sign_in_prompt_click', 'get_app', 'publish_started', 'publish_ok', 'publish_failed',+] as const;++export type HubViewPage = typeof hubViewPages[number];+export type HubEntrySource = typeof hubEntrySources[number];+export type HubAction = typeof hubActions[number];+export type HubMetric = `hub_view_${HubViewPage}_${'visitor' | 'member'}` | `hub_entry_${HubEntrySource}` | `hub_${HubAction}` | `hub_harness_dwell_${typeof hubDwell[number]}`;++export const hubReportMaxValue = 1000;++/** How long a harness page stayed in view, as the backend buckets it. */+export const dwellBucket = (ms: number): HubMetric => `hub_harness_dwell_${ms < 10_000 ? 'under_10s' : ms < 60_000 ? '10s_to_1m' : 'over_1m'}`;++const search = /(^|\.)(google|bing|duckduckgo|yahoo|baidu|yandex|ecosia|brave|kagi|naver|startpage)\./;+const social = /(^|\.)(x\.com|twitter\.com|t\.co|facebook\.com|fb\.com|m\.facebook\.com|linkedin\.com|lnkd\.in|reddit\.com|news\.ycombinator\.com|threads\.net|bsky\.app|mastodon\.social|youtube\.com|discord\.com|t\.me|instagram\.com)$/;++/** Where a visit came from, from the referrer's host alone; only the class leaves the browser. */+export function entrySource(referrer: string, ownHost: string): HubEntrySource {+ if (!referrer) return 'direct';+ let host: string;+ try { host = new URL(referrer).hostname.toLowerCase(); } catch { return 'other'; }+ if (host === ownHost) return 'internal';+ if (search.test(`${host}.`)) return 'search';+ return social.test(host) ? 'social' : 'other';+}diff --git a/website/src/lib/community/server.ts b/website/src/lib/community/server.tsindex 87c358faf..988f73c7f 100644--- a/website/src/lib/community/server.ts+++ b/website/src/lib/community/server.ts@@ -1,7 +1,7 @@import { readFile } from 'node:fs/promises';import path from 'node:path';import { starterHarnesses, starterConversation, starterSlug } from './starters';-import { feedPath, type FeedPage, type FeedView } from './feed';+import { feedPath, type FeedPage, type FeedQuery } from './feed';import { namesPublication } from './slug';import type { Creator, OpenHarness } from './types';@@ -61,7 +61,7 @@ async function readHub<T>(path: string, timeoutMs: number): Promise<T | null> {}/** A feed's first page as a visitor reads it: the reader's sign-in is only in their browser, which reads the page again with it. */-export const getFeedPage = (view: FeedView, timeoutMs: number) => readHub<FeedPage>(feedPath(view), timeoutMs);+export const getFeedPage = (view: FeedQuery, timeoutMs: number, after?: string) => readHub<FeedPage>(feedPath(view, after), timeoutMs);/** A creator's page head as a visitor reads it. */export const getCreator = async (id: string, timeoutMs: number) => (await readHub<{ creator: Creator }>(`creators/${id}`, timeoutMs))?.creator ?? null;diff --git a/website/src/lib/community/types.ts b/website/src/lib/community/types.tsindex fbdb80222..9e32e2cac 100644--- a/website/src/lib/community/types.ts+++ b/website/src/lib/community/types.ts@@ -29,6 +29,8 @@ export type HarnessSummary = {example?: boolean;recording?: string;forkedFrom?: string;+ /** When its author last edited it; a feed from an older backend leaves it out. */+ updatedAt?: string | null;};/*** `updatedAt`: when its author last edited it. `origin`: the publication it was forked from, by name,