Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
[MUL-5125] Add daily Desktop/Web usage and runtime reporting (#5763)
Multica Eve216aee5629ca
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 195db7aef6..18fa3a39bb 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -16,7 +16,11 @@ import {} from "fs";import { join } from "path";import { homedir, hostname } from "os";-import type { DaemonStatus, DaemonPrefs } from "../shared/daemon-types";+import type {+ DaemonStatus,+ DaemonPrefs,+ LocalRuntimeProbe,+} from "../shared/daemon-types";import { daemonStatusAlive } from "../shared/daemon-types";import { ensureManagedCli, managedCliPath } from "./cli-bootstrap";import { decideVersionAction } from "./version-decision";@@ -810,6 +814,92 @@ function profileArgs(active: ActiveProfile): string[] {return active.name ? ["--profile", active.name] : [];}+function successfulRuntimeProbe(+ providers: string[],+ daemonRunning: boolean,+): Extract<LocalRuntimeProbe, { probeResult: "success" }> {+ const providerSummary: Record<string, number> = {};+ for (const rawProvider of providers) {+ const provider = rawProvider.trim().toLowerCase();+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(provider)) continue;+ providerSummary[provider] = (providerSummary[provider] ?? 0) + 1;+ }+ const runtimeCount = Object.values(providerSummary).reduce(+ (sum, count) => sum + count,+ 0,+ );+ return {+ probeResult: "success",+ runtimeCount,+ providerSummary,+ onlineCount: daemonRunning ? runtimeCount : 0,+ offlineCount: daemonRunning ? 0 : runtimeCount,+ };+}++async function probeLocalRuntimes(): Promise<LocalRuntimeProbe> {+ const health = await fetchHealth();+ if (health.state === "running") {+ return successfulRuntimeProbe(health.agents ?? [], true);+ }++ const bin = await resolveCliBinary();+ if (!bin) return { probeResult: "error" };+ const active = await ensureActiveProfile();+ return new Promise((resolve) => {+ execFile(+ bin,+ ["daemon", "probe-runtimes", ...profileArgs(active)],+ { timeout: 15_000, env: desktopSpawnEnv(), maxBuffer: 64 * 1024 },+ (error, stdout) => {+ if (error) {+ resolve({ probeResult: "error" });+ return;+ }+ try {+ const parsed = JSON.parse(stdout) as {+ probe_result?: unknown;+ runtime_count?: unknown;+ provider_summary?: unknown;+ };+ if (+ parsed.probe_result !== "success" ||+ typeof parsed.runtime_count !== "number" ||+ !parsed.provider_summary ||+ typeof parsed.provider_summary !== "object" ||+ Array.isArray(parsed.provider_summary)+ ) {+ resolve({ probeResult: "error" });+ return;+ }+ const providers: string[] = [];+ for (const [provider, count] of Object.entries(+ parsed.provider_summary as Record<string, unknown>,+ )) {+ if (+ !Number.isInteger(count) ||+ (count as number) < 0 ||+ (count as number) > 1000+ ) {+ resolve({ probeResult: "error" });+ return;+ }+ providers.push(...Array<string>(count as number).fill(provider));+ }+ const probe = successfulRuntimeProbe(providers, false);+ resolve(+ probe.runtimeCount === parsed.runtime_count+ ? probe+ : { probeResult: "error" },+ );+ } catch {+ resolve({ probeResult: "error" });+ }+ },+ );+ });+}+// Env passed to every CLI child so the daemon process knows it was spawned// by the Desktop app. The server uses this to mark runtimes as managed and// hide CLI self-update UI. Computed lazily so it picks up the PATH fix@@ -1078,6 +1168,7 @@ export function setupDaemonManager(ipcMain.handle("daemon:stop", () => withGuard(() => stopDaemon()));ipcMain.handle("daemon:restart", () => withGuard(() => restartDaemon()));ipcMain.handle("daemon:get-status", () => fetchHealth());+ ipcMain.handle("daemon:probe-runtimes", () => probeLocalRuntimes());// The host's OS name, available regardless of daemon state. The Runtimes// page uses it as a fallback identity for "this machine" when no// app-managed daemon is reporting a device name (e.g. the daemon runsdiff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex 2ee0949c3b..6d72562ec9 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -11,6 +11,11 @@ import type {ManualUpdateCheckResult,UpdaterPreferences,} from "../shared/updater-types";+import type {+ DaemonStatus,+ DaemonPrefs,+ LocalRuntimeProbe,+} from "../shared/daemon-types";interface DesktopAPI {/** App version + normalized OS, captured synchronously at preload time. */@@ -101,30 +106,6 @@ interface DesktopAPI {) => Promise<{ ok: true } | { ok: false; reason: "invalid_request" }>;}-interface DaemonStatus {- state:- | "running"- | "stopped"- | "starting"- | "stopping"- | "installing_cli"- | "cli_not_found"- | "auth_expired";- pid?: number;- uptime?: string;- daemonId?: string;- deviceName?: string;- agents?: string[];- workspaceCount?: number;- profile?: string;- serverUrl?: string;-}--interface DaemonPrefs {- autoStart: boolean;- autoStop: boolean;-}-type DaemonReauthResult =| { ok: true }| { ok: false; reason: "session_invalid" }@@ -135,6 +116,7 @@ interface DaemonAPI {stop: () => Promise<{ success: boolean; error?: string }>;restart: () => Promise<{ success: boolean; error?: string }>;getStatus: () => Promise<DaemonStatus>;+ probeRuntimes: () => Promise<LocalRuntimeProbe>;getHostName: () => Promise<string>;onStatusChange: (callback: (status: DaemonStatus) => void) => () => void;setTargetApiUrl: (url: string) => Promise<void>;diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 9d143b4617..4c187d6c3d 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -20,6 +20,10 @@ import {type IssueWindowRequest,} from "../shared/issue-window";import { AUTH_SESSION_STATE_CHANNEL } from "../shared/auth-session";+import type {+ DaemonStatus,+ LocalRuntimeProbe,+} from "../shared/daemon-types";import {MAIN_RENDERER_CHANNEL_STATE_CHANNEL,type MainRendererMessageChannel,@@ -217,25 +221,6 @@ const desktopAPI = {ipcRenderer.invoke("window:open-issue", request),};-interface DaemonStatus {- state:- | "running"- | "stopped"- | "starting"- | "stopping"- | "installing_cli"- | "cli_not_found"- | "auth_expired";- pid?: number;- uptime?: string;- daemonId?: string;- deviceName?: string;- agents?: string[];- workspaceCount?: number;- profile?: string;- serverUrl?: string;-}-type DaemonReauthResult =| { ok: true }| { ok: false; reason: "session_invalid" }@@ -250,6 +235,8 @@ const daemonAPI = {ipcRenderer.invoke("daemon:restart"),getStatus: (): Promise<DaemonStatus> =>ipcRenderer.invoke("daemon:get-status"),+ probeRuntimes: (): Promise<LocalRuntimeProbe> =>+ ipcRenderer.invoke("daemon:probe-runtimes"),getHostName: (): Promise<string> =>ipcRenderer.invoke("daemon:get-host-name"),onStatusChange: (callback: (status: DaemonStatus) => void) => {diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex bc1a587d20..e4aef2b415 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -21,6 +21,7 @@ import { useDaemonIPCBridge } from "./platform/daemon-ipc-bridge";import { createDesktopLocaleAdapter } from "./platform/i18n-adapter";import { captureEvent } from "@multica/core/analytics";import { RESOURCES } from "@multica/views/locales";+import { DesktopClientUsageReporter } from "./platform/client-usage-reporter";// BCP-47 region tags for the <html lang> attribute, mirroring// apps/web/app/layout.tsx HTML_LANG. index.html ships a static lang="en";@@ -452,6 +453,11 @@ export default function App() {localeAdapter={localeAdapter}><DesktopAuthSessionBridge />+ {windowContext.kind === "main" && (+ <DesktopClientUsageReporter+ apiUrl={runtimeConfigResult.config.apiUrl}+ />+ )}{windowContext.kind === "issue" ? (<IssueWindowContent />) : (diff --git a/apps/desktop/src/renderer/src/platform/client-usage-reporter.test.ts b/apps/desktop/src/renderer/src/platform/client-usage-reporter.test.tsnew file mode 100644index 0000000000..976c4abc59--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/client-usage-reporter.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { runtimeProbeSignature } from "./client-usage-reporter";++describe("runtimeProbeSignature", () => {+ it("is stable across provider insertion order", () => {+ const base = {+ probeResult: "success" as const,+ runtimeCount: 2,+ onlineCount: 1,+ offlineCount: 1,+ };+ expect(+ runtimeProbeSignature({ ...base, providerSummary: { codex: 1, claude: 1 } }),+ ).toBe(+ runtimeProbeSignature({ ...base, providerSummary: { claude: 1, codex: 1 } }),+ );+ });++ it("distinguishes runtime state changes", () => {+ const base = {+ probeResult: "success" as const,+ runtimeCount: 1,+ providerSummary: { codex: 1 },+ offlineCount: 0,+ };+ expect(runtimeProbeSignature({ ...base, onlineCount: 1 })).not.toBe(+ runtimeProbeSignature({ ...base, onlineCount: 0, offlineCount: 1 }),+ );+ });+});diff --git a/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsx b/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsxnew file mode 100644index 0000000000..4dc4ce857d--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/client-usage-reporter.tsx@@ -0,0 +1,103 @@+import { useCallback, useEffect, useRef } from "react";+import { api } from "@multica/core/api";+import { useAuthStore } from "@multica/core/auth";+import { getOrCreateInstallId, utcDay } from "@multica/core/client-usage";+import { defaultStorage } from "@multica/core/platform";+import type { LocalRuntimeProbe } from "../../../shared/daemon-types";++const LAST_RUNTIME_PREFIX = "multica_runtime_probe_last_reported";++export function runtimeProbeSignature(probe: LocalRuntimeProbe): string {+ if (probe.probeResult === "error") return "error";+ return JSON.stringify({+ runtimeCount: probe.runtimeCount,+ providers: Object.entries(probe.providerSummary).sort(([a], [b]) =>+ a.localeCompare(b),+ ),+ onlineCount: probe.onlineCount,+ offlineCount: probe.offlineCount,+ });+}++export function DesktopClientUsageReporter({ apiUrl }: { apiUrl: string }) {+ const userID = useAuthStore((state) => state.user?.id ?? null);+ const userIDRef = useRef(userID);+ userIDRef.current = userID;+ const inFlight = useRef(false);+ const rerun = useRef(false);+ const lastStatusSignal = useRef<string | null>(null);++ const probeAndReport = useCallback(async () => {+ const activeUserID = userIDRef.current;+ if (!activeUserID) return;+ if (inFlight.current) {+ rerun.current = true;+ return;+ }+ inFlight.current = true;+ try {+ await window.daemonAPI.setTargetApiUrl(apiUrl);+ const installID = getOrCreateInstallId(defaultStorage);+ const probe = await window.daemonAPI.probeRuntimes();+ if (userIDRef.current !== activeUserID) {+ rerun.current = true;+ return;+ }+ const day = utcDay();+ const signature = runtimeProbeSignature(probe);+ const key = `${LAST_RUNTIME_PREFIX}:${activeUserID}:${installID}`;+ if (defaultStorage.getItem(key) === `${day}:${signature}`) return;++ await api.upsertClientUsage({+ install_id: installID,+ runtime:+ probe.probeResult === "error"+ ? { probe_result: "error" }+ : {+ probe_result: "success",+ runtime_count: probe.runtimeCount,+ provider_summary: probe.providerSummary,+ online_count: probe.onlineCount,+ offline_count: probe.offlineCount,+ },+ });+ defaultStorage.setItem(key, `${day}:${signature}`);+ } catch {+ // Runtime analytics are best-effort and never block daemon control.+ } finally {+ inFlight.current = false;+ if (rerun.current) {+ rerun.current = false;+ void probeAndReport();+ }+ }+ }, [apiUrl]);++ useEffect(() => {+ void probeAndReport();+ }, [probeAndReport, userID]);++ useEffect(() => {+ const unsubscribe = window.daemonAPI.onStatusChange((status) => {+ if (+ status.state === "running" ||+ status.state === "stopped" ||+ status.state === "auth_expired" ||+ status.state === "cli_not_found"+ ) {+ const signal = `${status.state}:${[...(status.agents ?? [])].sort().join(",")}`;+ if (lastStatusSignal.current === signal) return;+ lastStatusSignal.current = signal;+ void probeAndReport();+ }+ });+ const onFocus = () => void probeAndReport();+ window.addEventListener("focus", onFocus);+ return () => {+ unsubscribe();+ window.removeEventListener("focus", onFocus);+ };+ }, [probeAndReport]);++ return null;+}diff --git a/apps/desktop/src/shared/daemon-types.ts b/apps/desktop/src/shared/daemon-types.tsindex d0932f61dc..d8a86cf475 100644--- a/apps/desktop/src/shared/daemon-types.ts+++ b/apps/desktop/src/shared/daemon-types.ts@@ -39,6 +39,16 @@ export interface DaemonPrefs {autoStop: boolean;}+export type LocalRuntimeProbe =+ | {+ probeResult: "success";+ runtimeCount: number;+ providerSummary: Record<string, number>;+ onlineCount: number;+ offlineCount: number;+ }+ | { probeResult: "error" };+export const DAEMON_STATE_COLORS: Record<DaemonState, string> = {running: "bg-emerald-500",stopped: "bg-muted-foreground/40",diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsxindex 725ecf9e95..1adbf72cde 100644--- a/apps/web/components/web-providers.tsx+++ b/apps/web/components/web-providers.tsx@@ -11,6 +11,7 @@ import {setLoggedInCookie,clearLoggedInCookie,} from "@/features/auth/auth-cookie";+import { detectWebOS } from "@/platform/client-os";// Legacy token in localStorage → keep this session in token mode so users who// logged in before the cookie-auth migration stay authed. They migrate to@@ -56,7 +57,7 @@ export function WebProviders({// Stable identity reference so downstream effects keyed on it don't see a// new object on every parent render.const identity = useMemo(- () => ({ platform: "web", version: WEB_VERSION }),+ () => ({ platform: "web", version: WEB_VERSION, os: detectWebOS() }),[],);const localeAdapter = useMemo(() => createBrowserCookieLocaleAdapter(), []);diff --git a/apps/web/platform/client-os.test.ts b/apps/web/platform/client-os.test.tsnew file mode 100644index 0000000000..b61f6ffef1--- /dev/null+++ b/apps/web/platform/client-os.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";+import { detectWebOS } from "./client-os";++describe("detectWebOS", () => {+ it.each([+ ["MacIntel", "Mozilla/5.0", "macos"],+ ["Win32", "Mozilla/5.0", "windows"],+ ["Linux x86_64", "Mozilla/5.0 (X11; Linux x86_64)", "linux"],+ ["Linux armv8l", "Mozilla/5.0 (Linux; Android 15)", "android"],+ ["Linux x86_64", "Mozilla/5.0 (X11; CrOS x86_64)", "chromeos"],+ ["MacIntel", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0)", "ios"],+ ])("maps %s to %s", (platform, userAgent, expected) => {+ expect(detectWebOS({ platform, userAgent } as Navigator)).toBe(expected);+ });+});diff --git a/apps/web/platform/client-os.ts b/apps/web/platform/client-os.tsnew file mode 100644index 0000000000..e448caca71--- /dev/null+++ b/apps/web/platform/client-os.ts@@ -0,0 +1,24 @@+export type CoarseClientOS =+ | "macos"+ | "windows"+ | "linux"+ | "ios"+ | "android"+ | "chromeos"+ | "unknown";++/** Maps browser hints to a coarse OS bucket without retaining the raw user agent. */+export function detectWebOS(+ nav: Pick<Navigator, "platform" | "userAgent"> | undefined =+ typeof navigator === "undefined" ? undefined : navigator,+): CoarseClientOS {+ if (!nav) return "unknown";+ const hint = `${nav.platform} ${nav.userAgent}`.toLowerCase();+ if (/iphone|ipad|ipod/.test(hint)) return "ios";+ if (hint.includes("android")) return "android";+ if (hint.includes("cros")) return "chromeos";+ if (/mac|darwin/.test(hint)) return "macos";+ if (/win/.test(hint)) return "windows";+ if (/linux|x11/.test(hint)) return "linux";+ return "unknown";+}diff --git a/docs/analytics.md b/docs/analytics.mdindex 478b19e6b9..70e15afc65 100644--- a/docs/analytics.md+++ b/docs/analytics.md@@ -720,6 +720,116 @@ issue). Since MUL-4127 it is Prometheus-only, so reconcile`multica_issue_executed_total` against `issue.first_executed_at` rather than aPostHog event.+## Daily client usage and local runtime state++`client_usage_daily` is the operational source of truth for Web/Desktop usage+and Desktop built-in-provider conversion. Its primary key is+`(user_id, client_type, install_id, activity_date)`, where `activity_date` is+derived by the server in UTC. `install_id` is a random UUID stored in the Web+origin or Electron app profile and reused across restarts, upgrades, logout,+and login. Clearing/resetting that profile intentionally creates a new+installation. Web and Desktop never share an installation ID.++Clients report after authentication when that installation has no successful+report for the current UTC day, and re-check on focus/resume. Desktop updates+the same daily row after its first local-runtime probe and whenever the+same-day runtime signature changes. Reports contain only client kind/version,+a coarse OS bucket, optional current workspace context, and aggregate runtime+provider/online/offline counts. The server supplies user, date, and timestamps.+Device names, hostnames, local usernames, filesystem paths, raw user agents,+IP addresses, and raw probe errors are not stored here.++`first_active_at` and `last_active_at` are the first and latest successful+reports **within that UTC day**, not lifetime installation timestamps. Compute+historical first use with `min(first_active_at)` across the installation's daily+rows. The client's UTC day is only a best-effort request throttle; the server's+UTC date is authoritative, so clock skew near midnight can delay the next row+until a later focus/resume without assigning activity to the wrong server day.++Desktop runtime availability is deliberately a daemon-level approximation in+this MVP, not a connection test for each provider. The probe counts locally+detected **built-in provider CLIs**; workspace custom runtime profiles are not+included. Consequently, treat `runtime_count = 0` as "no built-in provider CLI+detected", not proof that the user has no custom profile. If the managed daemon+is running, all detected built-in providers are reported online, and otherwise+they are reported offline. Use `probe_result = 'error'` as unknown rather than+treating a failed probe as zero runtimes. Covering custom profiles requires a+separate inventory contract that remains available after the daemon stops; do+not infer it from this snapshot.++Use this query for a 30-day client split and user-level Desktop built-in-provider+state. It first selects the latest non-null probe for each installation, then+rolls installations up to the user so multi-device users are not double counted+and missing probes remain `unknown` rather than being classified as having no+built-in runtime:++```sql+WITH window_rows AS (+ SELECT *+ FROM client_usage_daily+ WHERE activity_date >= (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date - 29+),+active_clients AS (+ SELECT DISTINCT user_id, client_type, install_id FROM window_rows+),+latest_desktop_probe AS (+ SELECT DISTINCT ON (user_id, install_id)+ user_id, install_id, probe_result, runtime_count, online_count+ FROM window_rows+ WHERE client_type = 'desktop' AND probe_result IS NOT NULL+ ORDER BY user_id, install_id, activity_date DESC, runtime_probed_at DESC+),+desktop_by_user AS (+ SELECT+ a.user_id,+ count(*) AS installation_count,+ count(*) FILTER (WHERE p.probe_result = 'success') AS successful_probe_count,+ coalesce(sum(p.runtime_count) FILTER (WHERE p.probe_result = 'success'), 0) AS runtime_count,+ coalesce(sum(p.online_count) FILTER (WHERE p.probe_result = 'success'), 0) AS online_count+ FROM active_clients a+ LEFT JOIN latest_desktop_probe p USING (user_id, install_id)+ WHERE a.client_type = 'desktop'+ GROUP BY a.user_id+),+desktop_state AS (+ SELECT user_id,+ CASE+ WHEN successful_probe_count < installation_count THEN 'unknown'+ WHEN runtime_count = 0 THEN 'no_builtin_runtime'+ WHEN online_count = 0 THEN 'all_builtin_runtimes_offline'+ ELSE 'builtin_runtime_available'+ END AS runtime_state+ FROM desktop_by_user+)+SELECT+ (SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'web') AS active_web_users,+ (SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'desktop') AS active_desktop_users,+ count(*) FILTER (WHERE runtime_state = 'builtin_runtime_available')+ AS desktop_users_with_builtin_runtime,+ count(*) FILTER (WHERE runtime_state = 'no_builtin_runtime')+ AS desktop_users_without_builtin_runtime,+ round(100.0 * count(*) FILTER (WHERE runtime_state = 'no_builtin_runtime')+ / nullif((SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'desktop'), 0), 2)+ AS desktop_users_without_builtin_runtime_pct,+ count(*) FILTER (WHERE runtime_state = 'all_builtin_runtimes_offline')+ AS desktop_users_all_builtin_runtimes_offline,+ round(100.0 * count(*) FILTER (WHERE runtime_state = 'all_builtin_runtimes_offline')+ / nullif((SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'desktop'), 0), 2)+ AS desktop_users_all_builtin_runtimes_offline_pct,+ count(*) FILTER (WHERE runtime_state = 'unknown') AS desktop_users_unknown+FROM desktop_state;+```++The initial retention policy is 180 UTC days. This MVP deliberately does not+add another in-process background job; operators should run+`DELETE FROM client_usage_daily WHERE activity_date < (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date - 179`+through the existing database-maintenance schedule until a shared retention+worker exists. Deleting a workspace nulls its optional context, while deleting+a user must delete that user's daily rows in the same application transaction+because this table has no foreign keys by repository policy. There is currently+no production account hard-delete path; any future one must add that explicit+cleanup before it deletes the user row.+## GovernanceBefore adding, renaming, or removing any event:diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 51c4d99c80..3b922a1cb3 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -283,7 +283,7 @@ export interface ApiClientIdentity {platform?: string;/** Client/app version string (e.g. "0.1.0", git tag, commit). */version?: string;- /** Operating system the client is running on: "macos" | "windows" | "linux". */+ /** Coarse operating-system bucket (for example "macos", "windows", or "linux"). */os?: string;}@@ -294,6 +294,19 @@ export interface ApiClientOptions {identity?: ApiClientIdentity;}+export interface ClientRuntimeSnapshot {+ probe_result: "success" | "error";+ runtime_count?: number;+ provider_summary?: Record<string, number>;+ online_count?: number;+ offline_count?: number;+}++export interface ClientUsageRequest {+ install_id: string;+ runtime?: ClientRuntimeSnapshot;+}+export interface LoginResponse {token: string;user: User;@@ -801,6 +814,13 @@ export class ApiClient {});}+ async upsertClientUsage(data: ClientUsageRequest): Promise<void> {+ await this.fetch("/api/client-usage", {+ method: "POST",+ body: JSON.stringify(data),+ });+ }+async updateIssue(id: string, data: UpdateIssueRequest): Promise<Issue> {return this.fetch(`/api/issues/${id}`, {method: "PUT",diff --git a/packages/core/api/index.ts b/packages/core/api/index.tsindex 1f3ca87c4c..d1143ebfd5 100644--- a/packages/core/api/index.ts+++ b/packages/core/api/index.ts@@ -5,7 +5,11 @@ export {PreviewTooLargeError,PreviewUnsupportedError,} from "./client";-export type { ApiClientOptions } from "./client";+export type {+ ApiClientOptions,+ ClientRuntimeSnapshot,+ ClientUsageRequest,+} from "./client";export { parseWithFallback, setSchemaLogger } from "./schema";export type { ParseOptions } from "./schema";export { DuplicateIssueErrorBodySchema } from "./schemas";diff --git a/packages/core/client-usage/index.ts b/packages/core/client-usage/index.tsnew file mode 100644index 0000000000..cb49e0dd9d--- /dev/null+++ b/packages/core/client-usage/index.ts@@ -0,0 +1,2 @@+export { getOrCreateInstallId } from "./install-id";+export { ClientUsageReporter, utcDay } from "./reporter";diff --git a/packages/core/client-usage/install-id.test.ts b/packages/core/client-usage/install-id.test.tsnew file mode 100644index 0000000000..ccb67e5011--- /dev/null+++ b/packages/core/client-usage/install-id.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import type { StorageAdapter } from "../types/storage";+import { getOrCreateInstallId } from "./install-id";++function memoryStorage(): StorageAdapter {+ const values = new Map<string, string>();+ return {+ getItem: (key) => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: (key) => values.delete(key),+ };+}++describe("getOrCreateInstallId", () => {+ it("persists one UUID across calls", () => {+ const storage = memoryStorage();+ const generated = "3d267c82-59a9-46b2-a189-56e1504449a7";+ expect(getOrCreateInstallId(storage, () => generated)).toBe(generated);+ expect(getOrCreateInstallId(storage, () => "unused")).toBe(generated);+ });++ it("replaces corrupted persisted values", () => {+ const storage = memoryStorage();+ storage.setItem("multica_install_id", "broken");+ const generated = "c9c7a898-ee7c-44a0-bd0c-66a16461e591";+ expect(getOrCreateInstallId(storage, () => generated)).toBe(generated);+ });+});diff --git a/packages/core/client-usage/install-id.ts b/packages/core/client-usage/install-id.tsnew file mode 100644index 0000000000..fbafeabf42--- /dev/null+++ b/packages/core/client-usage/install-id.ts@@ -0,0 +1,33 @@+import type { StorageAdapter } from "../types/storage";++const INSTALL_ID_KEY = "multica_install_id";+const UUID_PATTERN =+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;++function randomUUID(): string {+ if (typeof globalThis.crypto?.randomUUID === "function") {+ return globalThis.crypto.randomUUID();+ }+ const bytes = new Uint8Array(16);+ globalThis.crypto.getRandomValues(bytes);+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;+}++/** Returns the installation-scoped ID, creating it only when storage has no valid UUID. */+export function getOrCreateInstallId(+ storage: StorageAdapter,+ generate: () => string = randomUUID,+): string {+ const existing = storage.getItem(INSTALL_ID_KEY);+ if (existing && UUID_PATTERN.test(existing)) return existing.toLowerCase();++ const created = generate().toLowerCase();+ if (!UUID_PATTERN.test(created)) {+ throw new Error("install id generator returned an invalid UUID");+ }+ storage.setItem(INSTALL_ID_KEY, created);+ return created;+}diff --git a/packages/core/client-usage/reporter.tsx b/packages/core/client-usage/reporter.tsxnew file mode 100644index 0000000000..109414fc54--- /dev/null+++ b/packages/core/client-usage/reporter.tsx@@ -0,0 +1,76 @@+"use client";++import { useCallback, useEffect, useRef } from "react";+import { getApi } from "../api";+import { useAuthStore } from "../auth";+import type { StorageAdapter } from "../types/storage";+import type { ClientIdentity } from "../platform/types";+import { getOrCreateInstallId } from "./install-id";++const LAST_REPORTED_PREFIX = "multica_client_usage_last_reported";++export function utcDay(date = new Date()): string {+ return date.toISOString().slice(0, 10);+}++export function ClientUsageReporter({+ storage,+ identity,+}: {+ storage: StorageAdapter;+ identity?: ClientIdentity;+}) {+ const userID = useAuthStore((state) => state.user?.id ?? null);+ const userIDRef = useRef(userID);+ userIDRef.current = userID;+ const inFlight = useRef(false);+ const rerun = useRef(false);++ const reportIfNeeded = useCallback(async () => {+ const platform = identity?.platform;+ const activeUserID = userIDRef.current;+ if (!activeUserID || (platform !== "web" && platform !== "desktop"))+ return;+ if (inFlight.current) {+ rerun.current = true;+ return;+ }++ const day = utcDay();+ try {+ const installID = getOrCreateInstallId(storage);+ const reportedKey = `${LAST_REPORTED_PREFIX}:${activeUserID}:${platform}:${installID}`;+ if (storage.getItem(reportedKey) === day) return;+ inFlight.current = true;+ await getApi().upsertClientUsage({ install_id: installID });+ storage.setItem(reportedKey, day);+ } catch {+ // Usage reporting is best-effort and must never interrupt app startup.+ } finally {+ inFlight.current = false;+ if (rerun.current) {+ rerun.current = false;+ void reportIfNeeded();+ }+ }+ }, [identity?.platform, storage]);++ useEffect(() => {+ void reportIfNeeded();+ }, [reportIfNeeded, userID]);++ useEffect(() => {+ const onFocus = () => void reportIfNeeded();+ const onVisibility = () => {+ if (document.visibilityState === "visible") void reportIfNeeded();+ };+ window.addEventListener("focus", onFocus);+ document.addEventListener("visibilitychange", onVisibility);+ return () => {+ window.removeEventListener("focus", onFocus);+ document.removeEventListener("visibilitychange", onVisibility);+ };+ }, [reportIfNeeded]);++ return null;+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 4d28e47227..4b2646a13f 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -113,6 +113,7 @@"./platform": "./platform/index.ts","./shortcuts": "./shortcuts/index.ts","./analytics": "./analytics/index.ts",+ "./client-usage": "./client-usage/index.ts","./i18n": "./i18n/index.ts","./i18n/react": "./i18n/react.ts","./i18n/browser": "./i18n/browser.ts",diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsxindex 34bee14bf5..b8ebec10ea 100644--- a/packages/core/platform/core-provider.tsx+++ b/packages/core/platform/core-provider.tsx@@ -18,6 +18,7 @@ import { defaultStorage } from "./storage";import { AuthInitializer } from "./auth-initializer";import type { CoreProviderProps, ClientIdentity } from "./types";import type { StorageAdapter } from "../types/storage";+import { ClientUsageReporter } from "../client-usage";import {configureShortcutPlatform,configureShortcutRuntime,@@ -117,6 +118,11 @@ export function CoreProvider({cookieAuth={cookieAuth}identity={identity}>+ {/* Desktop's reporter owns both activity and runtime state so it must+ be the only writer for that installation. */}+ {identity?.platform !== "desktop" && (+ <ClientUsageReporter storage={storage} identity={identity} />+ )}<WSProviderwsUrl={wsUrl}authStore={authStore}diff --git a/packages/core/platform/types.ts b/packages/core/platform/types.tsindex c5fd12d074..0ea17a7c66 100644--- a/packages/core/platform/types.ts+++ b/packages/core/platform/types.ts@@ -13,7 +13,7 @@ export interface ClientIdentity {platform?: string;/** Client/app version string (e.g. "0.1.0"). */version?: string;- /** Operating system: "macos" | "windows" | "linux". */+ /** Coarse operating-system bucket (for example "macos", "windows", or "linux"). */os?: string;}diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex 168d52d77c..724b033f4a 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -50,6 +50,13 @@ var daemonStatusCmd = &cobra.Command{RunE: runDaemonStatus,}+var daemonProbeRuntimesCmd = &cobra.Command{+ Use: "probe-runtimes",+ Short: "Probe locally configured runtimes for the Desktop app",+ Hidden: true,+ RunE: runDaemonProbeRuntimes,+}+var daemonRestartCmd = &cobra.Command{Use: "restart",Short: "Restart the running daemon (stop + start)",@@ -125,10 +132,41 @@ func init() {daemonCmd.AddCommand(daemonStopCmd)daemonCmd.AddCommand(daemonRestartCmd)daemonCmd.AddCommand(daemonStatusCmd)+ daemonCmd.AddCommand(daemonProbeRuntimesCmd)daemonCmd.AddCommand(daemonLogsCmd)daemonCmd.AddCommand(daemonDiskUsageCmd)}+type daemonRuntimeProbe struct {+ ProbeResult string `json:"probe_result"`+ RuntimeCount int `json:"runtime_count"`+ ProviderSummary map[string]int `json:"provider_summary"`+}++func runDaemonProbeRuntimes(cmd *cobra.Command, _ []string) error {+ cfg, err := daemon.LoadConfig(daemon.Overrides{+ Profile: resolveProfile(cmd),+ AllowNoAgents: true,+ })+ if err != nil {+ return err+ }+ probe := daemonRuntimeProbeFromAgents(cfg.Agents)+ return json.NewEncoder(cmd.OutOrStdout()).Encode(probe)+}++func daemonRuntimeProbeFromAgents(agents map[string]daemon.AgentEntry) daemonRuntimeProbe {+ probe := daemonRuntimeProbe{+ ProbeResult: "success",+ RuntimeCount: len(agents),+ ProviderSummary: make(map[string]int, len(agents)),+ }+ for provider := range agents {+ probe.ProviderSummary[provider]+++ }+ return probe+}+// daemonDirForProfile returns the state directory for the given profile.// Empty profile → ~/.multica/, named profile → ~/.multica/profiles/<name>/.func daemonDirForProfile(profile string) string {diff --git a/server/cmd/multica/cmd_daemon_probe_test.go b/server/cmd/multica/cmd_daemon_probe_test.gonew file mode 100644index 0000000000..34dbfa4b6e--- /dev/null+++ b/server/cmd/multica/cmd_daemon_probe_test.go@@ -0,0 +1,26 @@+package main++import (+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon"+)++func TestDaemonRuntimeProbeFromAgents(t *testing.T) {+ probe := daemonRuntimeProbeFromAgents(map[string]daemon.AgentEntry{+ "claude": {},+ "codex": {},+ })+ if probe.ProbeResult != "success" || probe.RuntimeCount != 2 || probe.ProviderSummary["codex"] != 1 {+ t.Fatalf("probe = %#v", probe)+ }+}++func TestLoadConfigAllowNoAgentsIsOptIn(t *testing.T) {+ // The production startup path does not set this override. Keep the probe's+ // escape hatch explicit rather than weakening the daemon startup invariant.+ var overrides daemon.Overrides+ if overrides.AllowNoAgents {+ t.Fatal("AllowNoAgents must default to false")+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 843641c56b..a1d67fcd1e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -831,6 +831,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/api/cli-token", h.IssueCliToken)r.Post("/api/upload-file", h.UploadFile)r.Post("/api/feedback", h.CreateFeedback)+ r.With(handler.RequireHumanActor).Post("/api/client-usage", h.UpsertClientUsage)// Note (MUL-4309): the generic OpenAI-compatible passthrough endpoints// (POST /api/llm/v1/chat/completions[/stream]) were intentionallydiff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex acc7fbdfc0..2960e4a223 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -145,6 +145,9 @@ type Overrides struct {RuntimeName stringProfile string // profile name (empty = default)HealthPort int // health check port (0 = use default)+ // AllowNoAgents is reserved for read-only local configuration probes. Daemon+ // startup keeps the default false and still refuses to run with no agent CLI.+ AllowNoAgents bool// DisableAutoUpdate, when true, forces the auto-update poller off. There// is no symmetric "force on" override because the env/default already// resolves to enabled; the flag exists so users can opt out from the CLI.@@ -345,7 +348,7 @@ func LoadConfig(overrides Overrides) (Config, error) {if e, ok := probe("MULTICA_QWEN_PATH", "qwen", "MULTICA_QWEN_MODEL"); ok {agents["qwen"] = e}- if len(agents) == 0 {+ if len(agents) == 0 && !overrides.AllowNoAgents {return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, deveco, openclaw, hermes, pi, cursor-agent, kimi, kiro-cli, agy, qodercli, traecli, grok, or qwen and ensure it is on PATH")}diff --git a/server/internal/handler/client_usage.go b/server/internal/handler/client_usage.gonew file mode 100644index 0000000000..2faab8c74c--- /dev/null+++ b/server/internal/handler/client_usage.go@@ -0,0 +1,227 @@+package handler++import (+ "encoding/json"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "regexp"+ "strings"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/middleware"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const clientUsageBodyLimit = 16 * 1024++var (+ providerNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`)+ clientVersionPattern = regexp.MustCompile(`^[\x20-\x7e]{1,64}$`)+)++type clientUsageRequest struct {+ InstallID string `json:"install_id"`+ Runtime *clientUsageRuntimeProbe `json:"runtime,omitempty"`+}++type clientUsageRuntimeProbe struct {+ ProbeResult string `json:"probe_result"`+ RuntimeCount *int32 `json:"runtime_count,omitempty"`+ ProviderSummary map[string]int `json:"provider_summary,omitempty"`+ OnlineCount *int32 `json:"online_count,omitempty"`+ OfflineCount *int32 `json:"offline_count,omitempty"`+}++type validatedRuntimeProbe struct {+ Result pgtype.Text+ RuntimeCount pgtype.Int4+ ProviderSummary []byte+ OnlineCount pgtype.Int4+ OfflineCount pgtype.Int4+}++// UpsertClientUsage records at most one row per user, client installation, and+// UTC day. Repeated reports refresh the same row; an activity-only report never+// clears a runtime snapshot already collected earlier that day.+func (h *Handler) UpsertClientUsage(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }++ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, clientUsageBodyLimit))+ decoder.DisallowUnknownFields()+ var req clientUsageRequest+ if err := decoder.Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ installID, ok := parseUUIDOrBadRequest(w, strings.TrimSpace(req.InstallID), "install_id")+ if !ok {+ return+ }++ clientType, clientVersion, clientOS := middleware.ClientMetadataFromContext(r.Context())+ clientType = strings.ToLower(strings.TrimSpace(clientType))+ if clientType != "web" && clientType != "desktop" {+ writeError(w, http.StatusBadRequest, "client platform must be web or desktop")+ return+ }+ clientVersion = strings.TrimSpace(clientVersion)+ if clientVersion == "" {+ clientVersion = "unknown"+ }+ if !clientVersionPattern.MatchString(clientVersion) {+ writeError(w, http.StatusBadRequest, "invalid client version")+ return+ }+ clientOS = normalizeClientUsageOS(clientOS)++ var runtime validatedRuntimeProbe+ if req.Runtime != nil {+ if clientType != "desktop" {+ writeError(w, http.StatusBadRequest, "runtime data is only accepted from desktop")+ return+ }+ var err error+ runtime, err = validateClientUsageRuntime(*req.Runtime)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ }++ workspaceUUID := pgtype.UUID{}+ queries := h.Queries+ var tx pgx.Tx+ if workspaceID := h.resolveWorkspaceID(r); workspaceID != "" {+ workspaceUUID, ok = parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ var err error+ tx, err = h.TxStarter.Begin(r.Context())+ if err != nil {+ slog.Error("failed to begin client usage transaction", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to record client usage")+ return+ }+ defer tx.Rollback(r.Context())+ queries = h.Queries.WithTx(tx)+ // Share the explicit workspace delete/create lock protocol: if deletion+ // wins, the row is gone and this report fails; if reporting wins, deletion+ // waits and clears the context after the upsert commits.+ if _, err := queries.LockWorkspaceForChatSessionCreate(r.Context(), workspaceUUID); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusForbidden, "workspace not found")+ return+ }+ slog.Error("failed to lock client usage workspace", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to record client usage")+ return+ }+ if _, err := queries.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{+ UserID: userUUID, WorkspaceID: workspaceUUID,+ }); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusForbidden, "workspace not found")+ return+ }+ slog.Error("failed to validate client usage workspace", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to record client usage")+ return+ }+ }++ if _, err := queries.UpsertClientUsageDaily(r.Context(), db.UpsertClientUsageDailyParams{+ UserID: userUUID,+ ClientType: clientType,+ InstallID: installID,+ WorkspaceID: workspaceUUID,+ ClientVersion: clientVersion,+ Os: clientOS,+ HasRuntimeProbe: req.Runtime != nil,+ ProbeResult: runtime.Result,+ RuntimeCount: runtime.RuntimeCount,+ ProviderSummary: runtime.ProviderSummary,+ OnlineCount: runtime.OnlineCount,+ OfflineCount: runtime.OfflineCount,+ }); err != nil {+ slog.Error("failed to upsert client usage", "error", err, "client_type", clientType)+ writeError(w, http.StatusInternalServerError, "failed to record client usage")+ return+ }+ if tx != nil {+ if err := tx.Commit(r.Context()); err != nil {+ slog.Error("failed to commit client usage", "error", err, "client_type", clientType)+ writeError(w, http.StatusInternalServerError, "failed to record client usage")+ return+ }+ }++ w.WriteHeader(http.StatusNoContent)+}++func normalizeClientUsageOS(value string) string {+ value = strings.ToLower(strings.TrimSpace(value))+ switch value {+ case "macos", "windows", "linux", "ios", "android", "chromeos":+ return value+ default:+ return "unknown"+ }+}++func validateClientUsageRuntime(probe clientUsageRuntimeProbe) (validatedRuntimeProbe, error) {+ result := strings.ToLower(strings.TrimSpace(probe.ProbeResult))+ if result != "success" && result != "error" {+ return validatedRuntimeProbe{}, errors.New("runtime probe_result must be success or error")+ }+ validated := validatedRuntimeProbe{Result: pgtype.Text{String: result, Valid: true}}+ if result == "error" {+ if probe.RuntimeCount != nil || probe.ProviderSummary != nil || probe.OnlineCount != nil || probe.OfflineCount != nil {+ return validatedRuntimeProbe{}, errors.New("failed runtime probes must not include counts")+ }+ return validated, nil+ }++ if probe.RuntimeCount == nil || probe.ProviderSummary == nil || probe.OnlineCount == nil || probe.OfflineCount == nil {+ return validatedRuntimeProbe{}, errors.New("successful runtime probes require all counts")+ }+ if *probe.RuntimeCount < 0 || *probe.RuntimeCount > 1000 || *probe.OnlineCount < 0 || *probe.OfflineCount < 0 || *probe.OnlineCount+*probe.OfflineCount != *probe.RuntimeCount {+ return validatedRuntimeProbe{}, errors.New("invalid runtime counts")+ }+ if len(probe.ProviderSummary) > 32 {+ return validatedRuntimeProbe{}, errors.New("too many runtime providers")+ }+ var providerTotal int64+ for provider, count := range probe.ProviderSummary {+ if !providerNamePattern.MatchString(provider) || count < 0 || count > 1000 {+ return validatedRuntimeProbe{}, errors.New("invalid runtime provider summary")+ }+ providerTotal += int64(count)+ }+ if providerTotal != int64(*probe.RuntimeCount) {+ return validatedRuntimeProbe{}, errors.New("runtime provider counts do not match runtime_count")+ }+ summary, err := json.Marshal(probe.ProviderSummary)+ if err != nil {+ return validatedRuntimeProbe{}, errors.New("invalid runtime provider summary")+ }+ validated.RuntimeCount = pgtype.Int4{Int32: *probe.RuntimeCount, Valid: true}+ validated.ProviderSummary = summary+ validated.OnlineCount = pgtype.Int4{Int32: *probe.OnlineCount, Valid: true}+ validated.OfflineCount = pgtype.Int4{Int32: *probe.OfflineCount, Valid: true}+ return validated, nil+}diff --git a/server/internal/handler/client_usage_test.go b/server/internal/handler/client_usage_test.gonew file mode 100644index 0000000000..58e4b0006a--- /dev/null+++ b/server/internal/handler/client_usage_test.go@@ -0,0 +1,91 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/multica-ai/multica/server/internal/middleware"+)++func ptrInt32(value int32) *int32 { return &value }++func TestValidateClientUsageRuntime(t *testing.T) {+ tests := []struct {+ name string+ probe clientUsageRuntimeProbe+ wantErr bool+ }{+ {name: "probe error", probe: clientUsageRuntimeProbe{ProbeResult: "error"}},+ {name: "successful empty config", probe: clientUsageRuntimeProbe{ProbeResult: "success", RuntimeCount: ptrInt32(0), ProviderSummary: map[string]int{}, OnlineCount: ptrInt32(0), OfflineCount: ptrInt32(0)}},+ {name: "successful mixed config", probe: clientUsageRuntimeProbe{ProbeResult: "success", RuntimeCount: ptrInt32(3), ProviderSummary: map[string]int{"claude": 2, "codex": 1}, OnlineCount: ptrInt32(1), OfflineCount: ptrInt32(2)}},+ {name: "error with counts", probe: clientUsageRuntimeProbe{ProbeResult: "error", RuntimeCount: ptrInt32(0)}, wantErr: true},+ {name: "missing success fields", probe: clientUsageRuntimeProbe{ProbeResult: "success"}, wantErr: true},+ {name: "state total mismatch", probe: clientUsageRuntimeProbe{ProbeResult: "success", RuntimeCount: ptrInt32(2), ProviderSummary: map[string]int{"codex": 2}, OnlineCount: ptrInt32(1), OfflineCount: ptrInt32(0)}, wantErr: true},+ {name: "provider total mismatch", probe: clientUsageRuntimeProbe{ProbeResult: "success", RuntimeCount: ptrInt32(2), ProviderSummary: map[string]int{"codex": 1}, OnlineCount: ptrInt32(1), OfflineCount: ptrInt32(1)}, wantErr: true},+ {name: "unsafe provider", probe: clientUsageRuntimeProbe{ProbeResult: "success", RuntimeCount: ptrInt32(1), ProviderSummary: map[string]int{"Codex Pro": 1}, OnlineCount: ptrInt32(1), OfflineCount: ptrInt32(0)}, wantErr: true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ _, err := validateClientUsageRuntime(tt.probe)+ if (err != nil) != tt.wantErr {+ t.Fatalf("validateClientUsageRuntime() error = %v, wantErr %v", err, tt.wantErr)+ }+ })+ }+}++func TestNormalizeClientUsageOS(t *testing.T) {+ if got := normalizeClientUsageOS(" MacOS "); got != "macos" {+ t.Fatalf("normalizeClientUsageOS() = %q, want macos", got)+ }+ if got := normalizeClientUsageOS("Darwin 24.4"); got != "unknown" {+ t.Fatalf("normalizeClientUsageOS() = %q, want unknown", got)+ }+}++func TestUpsertClientUsageKeepsRuntimeSnapshotOnActivityRefresh(t *testing.T) {+ const installID = "8d98d7db-4d40-4505-bc49-16b76db32721"+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM client_usage_daily WHERE user_id = $1 AND install_id = $2`, testUserID, installID)+ })++ report := func(body any) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ req := newRequest(http.MethodPost, "/api/client-usage", body)+ req.Header.Set("X-Client-Platform", "desktop")+ req.Header.Set("X-Client-Version", "0.1.0")+ req.Header.Set("X-Client-OS", "macos")+ req = req.WithContext(middleware.SetClientMetadata(req.Context(), "desktop", "0.1.0", "macos"))+ testHandler.UpsertClientUsage(w, req)+ return w+ }++ w := report(map[string]any{+ "install_id": installID,+ "runtime": map[string]any{+ "probe_result": "success", "runtime_count": 1,+ "provider_summary": map[string]int{"codex": 1},+ "online_count": 1, "offline_count": 0,+ },+ })+ if w.Code != http.StatusNoContent {+ t.Fatalf("runtime report status = %d: %s", w.Code, w.Body.String())+ }+ if w = report(map[string]any{"install_id": installID}); w.Code != http.StatusNoContent {+ t.Fatalf("activity refresh status = %d: %s", w.Code, w.Body.String())+ }++ var rowCount, runtimeCount, onlineCount int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*), max(runtime_count), max(online_count)+ FROM client_usage_daily+ WHERE user_id = $1 AND client_type = 'desktop' AND install_id = $2+ `, testUserID, installID).Scan(&rowCount, &runtimeCount, &onlineCount); err != nil {+ t.Fatal(err)+ }+ if rowCount != 1 || runtimeCount != 1 || onlineCount != 1 {+ t.Fatalf("daily row = count %d runtime %d online %d", rowCount, runtimeCount, onlineCount)+ }+}diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex 6c5784df09..db0b21e4cd 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -156,6 +156,15 @@ func setupHandlerTestFixture(ctx context.Context, pool *pgxpool.Pool) (string, s}func cleanupHandlerTestFixture(ctx context.Context, pool *pgxpool.Pool) error {+ var hasClientUsageTable bool+ if err := pool.QueryRow(ctx, `SELECT to_regclass('client_usage_daily') IS NOT NULL`).Scan(&hasClientUsageTable); err != nil {+ return err+ }+ if hasClientUsageTable {+ if _, err := pool.Exec(ctx, `DELETE FROM client_usage_daily WHERE user_id IN (SELECT id FROM "user" WHERE email = $1)`, handlerTestEmail); err != nil {+ return err+ }+ }if _, err := pool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, handlerTestWorkspaceSlug); err != nil {return err}diff --git a/server/migrations/207_client_usage_daily.down.sql b/server/migrations/207_client_usage_daily.down.sqlnew file mode 100644index 0000000000..05d739f7c1--- /dev/null+++ b/server/migrations/207_client_usage_daily.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS client_usage_daily;diff --git a/server/migrations/207_client_usage_daily.up.sql b/server/migrations/207_client_usage_daily.up.sqlnew file mode 100644index 0000000000..b277f46d45--- /dev/null+++ b/server/migrations/207_client_usage_daily.up.sql@@ -0,0 +1,27 @@+CREATE TABLE client_usage_daily (+ user_id UUID NOT NULL,+ client_type TEXT NOT NULL CHECK (client_type IN ('web', 'desktop')),+ install_id UUID NOT NULL,+ activity_date DATE NOT NULL,+ workspace_id UUID,+ client_version TEXT NOT NULL,+ os TEXT NOT NULL,+ first_active_at TIMESTAMPTZ NOT NULL,+ last_active_at TIMESTAMPTZ NOT NULL,+ runtime_probed_at TIMESTAMPTZ,+ probe_result TEXT CHECK (probe_result IN ('success', 'error')),+ runtime_count INTEGER CHECK (runtime_count >= 0),+ provider_summary JSONB,+ online_count INTEGER CHECK (online_count >= 0),+ offline_count INTEGER CHECK (offline_count >= 0),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CHECK (first_active_at <= last_active_at),+ CHECK (+ (runtime_probed_at IS NULL AND probe_result IS NULL AND runtime_count IS NULL AND provider_summary IS NULL AND online_count IS NULL AND offline_count IS NULL)+ OR+ (runtime_probed_at IS NOT NULL AND probe_result = 'error' AND runtime_count IS NULL AND provider_summary IS NULL AND online_count IS NULL AND offline_count IS NULL)+ OR+ (runtime_probed_at IS NOT NULL AND probe_result = 'success' AND runtime_count IS NOT NULL AND provider_summary IS NOT NULL AND online_count IS NOT NULL AND offline_count IS NOT NULL AND online_count + offline_count = runtime_count AND jsonb_typeof(provider_summary) = 'object')+ )+);diff --git a/server/migrations/208_client_usage_daily_unique_index.down.sql b/server/migrations/208_client_usage_daily_unique_index.down.sqlnew file mode 100644index 0000000000..95cf1a268b--- /dev/null+++ b/server/migrations/208_client_usage_daily_unique_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS client_usage_daily_identity_date_uidx;diff --git a/server/migrations/208_client_usage_daily_unique_index.up.sql b/server/migrations/208_client_usage_daily_unique_index.up.sqlnew file mode 100644index 0000000000..f6c723ba3d--- /dev/null+++ b/server/migrations/208_client_usage_daily_unique_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY client_usage_daily_identity_date_uidx ON client_usage_daily (user_id, client_type, install_id, activity_date);diff --git a/server/migrations/209_client_usage_daily_primary_key.down.sql b/server/migrations/209_client_usage_daily_primary_key.down.sqlnew file mode 100644index 0000000000..1b7988c6d0--- /dev/null+++ b/server/migrations/209_client_usage_daily_primary_key.down.sql@@ -0,0 +1 @@+ALTER TABLE client_usage_daily DROP CONSTRAINT IF EXISTS client_usage_daily_pkey;diff --git a/server/migrations/209_client_usage_daily_primary_key.up.sql b/server/migrations/209_client_usage_daily_primary_key.up.sqlnew file mode 100644index 0000000000..52a146838f--- /dev/null+++ b/server/migrations/209_client_usage_daily_primary_key.up.sql@@ -0,0 +1 @@+ALTER TABLE client_usage_daily ADD CONSTRAINT client_usage_daily_pkey PRIMARY KEY USING INDEX client_usage_daily_identity_date_uidx;diff --git a/server/migrations/210_client_usage_daily_query_index.down.sql b/server/migrations/210_client_usage_daily_query_index.down.sqlnew file mode 100644index 0000000000..8c3f5b9e0f--- /dev/null+++ b/server/migrations/210_client_usage_daily_query_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS client_usage_daily_activity_client_user_idx;diff --git a/server/migrations/210_client_usage_daily_query_index.up.sql b/server/migrations/210_client_usage_daily_query_index.up.sqlnew file mode 100644index 0000000000..187ede8977--- /dev/null+++ b/server/migrations/210_client_usage_daily_query_index.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY client_usage_daily_activity_client_user_idx ON client_usage_daily (activity_date, client_type, user_id);diff --git a/server/migrations/211_client_usage_daily_workspace_index.down.sql b/server/migrations/211_client_usage_daily_workspace_index.down.sqlnew file mode 100644index 0000000000..7ece8b62a9--- /dev/null+++ b/server/migrations/211_client_usage_daily_workspace_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS client_usage_daily_workspace_idx;diff --git a/server/migrations/211_client_usage_daily_workspace_index.up.sql b/server/migrations/211_client_usage_daily_workspace_index.up.sqlnew file mode 100644index 0000000000..b185f2962c--- /dev/null+++ b/server/migrations/211_client_usage_daily_workspace_index.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY client_usage_daily_workspace_idx ON client_usage_daily (workspace_id) WHERE workspace_id IS NOT NULL;diff --git a/server/pkg/db/generated/client_usage.sql.go b/server/pkg/db/generated/client_usage.sql.gonew file mode 100644index 0000000000..1f28ca4c02--- /dev/null+++ b/server/pkg/db/generated/client_usage.sql.go@@ -0,0 +1,114 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: client_usage.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const upsertClientUsageDaily = `-- name: UpsertClientUsageDaily :one+INSERT INTO client_usage_daily (+ user_id,+ client_type,+ install_id,+ activity_date,+ workspace_id,+ client_version,+ os,+ first_active_at,+ last_active_at,+ runtime_probed_at,+ probe_result,+ runtime_count,+ provider_summary,+ online_count,+ offline_count+) VALUES (+ $1,+ $2,+ $3,+ (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date,+ $4,+ $5,+ $6,+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP,+ CASE WHEN $7::boolean THEN CURRENT_TIMESTAMP ELSE NULL END,+ $8,+ $9,+ $10,+ $11,+ $12+)+ON CONFLICT (user_id, client_type, install_id, activity_date) DO UPDATE SET+ workspace_id = COALESCE(EXCLUDED.workspace_id, client_usage_daily.workspace_id),+ client_version = EXCLUDED.client_version,+ os = EXCLUDED.os,+ last_active_at = EXCLUDED.last_active_at,+ runtime_probed_at = CASE WHEN $7::boolean THEN EXCLUDED.runtime_probed_at ELSE client_usage_daily.runtime_probed_at END,+ probe_result = CASE WHEN $7::boolean THEN EXCLUDED.probe_result ELSE client_usage_daily.probe_result END,+ runtime_count = CASE WHEN $7::boolean THEN EXCLUDED.runtime_count ELSE client_usage_daily.runtime_count END,+ provider_summary = CASE WHEN $7::boolean THEN EXCLUDED.provider_summary ELSE client_usage_daily.provider_summary END,+ online_count = CASE WHEN $7::boolean THEN EXCLUDED.online_count ELSE client_usage_daily.online_count END,+ offline_count = CASE WHEN $7::boolean THEN EXCLUDED.offline_count ELSE client_usage_daily.offline_count END,+ updated_at = CURRENT_TIMESTAMP+RETURNING user_id, client_type, install_id, activity_date, workspace_id, client_version, os, first_active_at, last_active_at, runtime_probed_at, probe_result, runtime_count, provider_summary, online_count, offline_count, created_at, updated_at+`++type UpsertClientUsageDailyParams struct {+ UserID pgtype.UUID `json:"user_id"`+ ClientType string `json:"client_type"`+ InstallID pgtype.UUID `json:"install_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ClientVersion string `json:"client_version"`+ Os string `json:"os"`+ HasRuntimeProbe bool `json:"has_runtime_probe"`+ ProbeResult pgtype.Text `json:"probe_result"`+ RuntimeCount pgtype.Int4 `json:"runtime_count"`+ ProviderSummary []byte `json:"provider_summary"`+ OnlineCount pgtype.Int4 `json:"online_count"`+ OfflineCount pgtype.Int4 `json:"offline_count"`+}++func (q *Queries) UpsertClientUsageDaily(ctx context.Context, arg UpsertClientUsageDailyParams) (ClientUsageDaily, error) {+ row := q.db.QueryRow(ctx, upsertClientUsageDaily,+ arg.UserID,+ arg.ClientType,+ arg.InstallID,+ arg.WorkspaceID,+ arg.ClientVersion,+ arg.Os,+ arg.HasRuntimeProbe,+ arg.ProbeResult,+ arg.RuntimeCount,+ arg.ProviderSummary,+ arg.OnlineCount,+ arg.OfflineCount,+ )+ var i ClientUsageDaily+ err := row.Scan(+ &i.UserID,+ &i.ClientType,+ &i.InstallID,+ &i.ActivityDate,+ &i.WorkspaceID,+ &i.ClientVersion,+ &i.Os,+ &i.FirstActiveAt,+ &i.LastActiveAt,+ &i.RuntimeProbedAt,+ &i.ProbeResult,+ &i.RuntimeCount,+ &i.ProviderSummary,+ &i.OnlineCount,+ &i.OfflineCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex d2d393c0b8..24dc762c15 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -389,6 +389,26 @@ type ChatSession struct {PinnedAt pgtype.Timestamptz `json:"pinned_at"`}+type ClientUsageDaily struct {+ UserID pgtype.UUID `json:"user_id"`+ ClientType string `json:"client_type"`+ InstallID pgtype.UUID `json:"install_id"`+ ActivityDate pgtype.Date `json:"activity_date"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ClientVersion string `json:"client_version"`+ Os string `json:"os"`+ FirstActiveAt pgtype.Timestamptz `json:"first_active_at"`+ LastActiveAt pgtype.Timestamptz `json:"last_active_at"`+ RuntimeProbedAt pgtype.Timestamptz `json:"runtime_probed_at"`+ ProbeResult pgtype.Text `json:"probe_result"`+ RuntimeCount pgtype.Int4 `json:"runtime_count"`+ ProviderSummary []byte `json:"provider_summary"`+ OnlineCount pgtype.Int4 `json:"online_count"`+ OfflineCount pgtype.Int4 `json:"offline_count"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type Comment struct {ID pgtype.UUID `json:"id"`IssueID pgtype.UUID `json:"issue_id"`diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex 456c0e34d4..bd352cd074 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -115,6 +115,9 @@ cleared_issue_properties AS (),deleted_pending_check_suites AS (DELETE FROM github_pending_check_suite WHERE workspace_id = $1+),+cleared_client_usage_workspace AS (+ UPDATE client_usage_daily SET workspace_id = NULL WHERE workspace_id = $1)DELETE FROM workspace WHERE workspace.id = $1`diff --git a/server/pkg/db/queries/client_usage.sql b/server/pkg/db/queries/client_usage.sqlnew file mode 100644index 0000000000..dfd66219d0--- /dev/null+++ b/server/pkg/db/queries/client_usage.sql@@ -0,0 +1,47 @@+-- name: UpsertClientUsageDaily :one+INSERT INTO client_usage_daily (+ user_id,+ client_type,+ install_id,+ activity_date,+ workspace_id,+ client_version,+ os,+ first_active_at,+ last_active_at,+ runtime_probed_at,+ probe_result,+ runtime_count,+ provider_summary,+ online_count,+ offline_count+) VALUES (+ sqlc.arg('user_id'),+ sqlc.arg('client_type'),+ sqlc.arg('install_id'),+ (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date,+ sqlc.narg('workspace_id'),+ sqlc.arg('client_version'),+ sqlc.arg('os'),+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP,+ CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN CURRENT_TIMESTAMP ELSE NULL END,+ sqlc.narg('probe_result'),+ sqlc.narg('runtime_count'),+ sqlc.narg('provider_summary'),+ sqlc.narg('online_count'),+ sqlc.narg('offline_count')+)+ON CONFLICT (user_id, client_type, install_id, activity_date) DO UPDATE SET+ workspace_id = COALESCE(EXCLUDED.workspace_id, client_usage_daily.workspace_id),+ client_version = EXCLUDED.client_version,+ os = EXCLUDED.os,+ last_active_at = EXCLUDED.last_active_at,+ runtime_probed_at = CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN EXCLUDED.runtime_probed_at ELSE client_usage_daily.runtime_probed_at END,+ probe_result = CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN EXCLUDED.probe_result ELSE client_usage_daily.probe_result END,+ runtime_count = CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN EXCLUDED.runtime_count ELSE client_usage_daily.runtime_count END,+ provider_summary = CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN EXCLUDED.provider_summary ELSE client_usage_daily.provider_summary END,+ online_count = CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN EXCLUDED.online_count ELSE client_usage_daily.online_count END,+ offline_count = CASE WHEN sqlc.arg('has_runtime_probe')::boolean THEN EXCLUDED.offline_count ELSE client_usage_daily.offline_count END,+ updated_at = CURRENT_TIMESTAMP+RETURNING *;diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex e8d65adff5..b892b372aa 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -158,5 +158,8 @@ cleared_issue_properties AS (),deleted_pending_check_suites AS (DELETE FROM github_pending_check_suite WHERE workspace_id = $1+),+cleared_client_usage_workspace AS (+ UPDATE client_usage_daily SET workspace_id = NULL WHERE workspace_id = $1)DELETE FROM workspace WHERE workspace.id = $1;