π OpenHands: AI-Driven Development
fix: Add --disable-telemetry runtime flag for self-hosted canvas (#16908)
Lila Garciaf26d734a8482
diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex 03ffcc27b4..0882d6b592 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -145,6 +145,31 @@ describe("static-server.mjs", () => {expect(config.lockToCloud).toBeNull();});+ it("defaults disableTelemetry to false", () => {+ const config = parseArgs([], {});+ expect(config.disableTelemetry).toBe(false);+ });++ it("parses --disable-telemetry", () => {+ const config = parseArgs(["--disable-telemetry"], {});+ expect(config.disableTelemetry).toBe(true);+ });++ it("enables disableTelemetry from AGENT_CANVAS_DISABLE_TELEMETRY=1", () => {+ const config = parseArgs([], { AGENT_CANVAS_DISABLE_TELEMETRY: "1" });+ expect(config.disableTelemetry).toBe(true);+ });++ it("enables disableTelemetry from AGENT_CANVAS_DISABLE_TELEMETRY=true", () => {+ const config = parseArgs([], { AGENT_CANVAS_DISABLE_TELEMETRY: "true" });+ expect(config.disableTelemetry).toBe(true);+ });++ it("ignores a falsy AGENT_CANVAS_DISABLE_TELEMETRY value", () => {+ const config = parseArgs([], { AGENT_CANVAS_DISABLE_TELEMETRY: "0" });+ expect(config.disableTelemetry).toBe(false);+ });+it("defaults basePath to root", () => {const config = parseArgs([]);expect(config.basePath).toBe("/");@@ -477,6 +502,57 @@ describe("static-server.mjs", () => {});});+ describe("disable-telemetry injection", () => {+ async function startServerWithDisabledTelemetry(dir: string) {+ const origin = await startServer(dir, { disableTelemetry: true });+ return origin;+ }++ it("exposes window.__AGENT_CANVAS_DO_NOT_TRACK__ when enabled", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );++ const origin = await startServerWithDisabledTelemetry(buildDir);+ const body = await (await fetch(`${origin}/`)).text();++ expect(body).toContain("window.__AGENT_CANVAS_DO_NOT_TRACK__=true");+ });++ it("injects the flag into the SPA fallback index.html", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );++ const origin = await startServerWithDisabledTelemetry(buildDir);+ const response = await fetch(`${origin}/some/deep/route`);+ const body = await response.text();++ expect(response.status).toBe(200);+ expect(body).toContain("window.__AGENT_CANVAS_DO_NOT_TRACK__=true");+ });++ it("does not inject the flag when telemetry is not disabled", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );++ const origin = await startServer(buildDir);+ const body = await (await fetch(`${origin}/`)).text();++ expect(body).not.toContain("__AGENT_CANVAS_DO_NOT_TRACK__");+ });+ });+describe("session key injection", () => {async function startServerWithKey(dir: string, sessionApiKey: string) {const server = await startStaticServer({diff --git a/__tests__/services/telemetry.test.ts b/__tests__/services/telemetry.test.tsindex db233122bc..2ab8ba24cb 100644--- a/__tests__/services/telemetry.test.ts+++ b/__tests__/services/telemetry.test.ts@@ -74,6 +74,8 @@ describe("Telemetry Service", () => {sessionStorage.clear();delete (window as unknown as Record<string, unknown>).__AGENT_CANVAS_LOCK_TO_CLOUD__;+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_DO_NOT_TRACK__;// Reset mockvi.clearAllMocks();identifiedUserId = undefined;@@ -92,6 +94,8 @@ describe("Telemetry Service", () => {sessionStorage.clear();delete (window as unknown as Record<string, unknown>).__AGENT_CANVAS_LOCK_TO_CLOUD__;+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_DO_NOT_TRACK__;});describe("PostHog ownership", () => {@@ -457,6 +461,40 @@ describe("Telemetry Service", () => {});});+ describe("runtime do-not-track global", () => {+ it("reports consent as denied when the global is set", () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_DO_NOT_TRACK__ = true;++ expect(getTelemetryConsent()).toBe("denied");+ expect(isTelemetryEnabled()).toBe(false);+ });++ it("suppresses the install event even without consent", async () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_DO_NOT_TRACK__ = true;++ await trackInstall();++ expect(mockPosthog.capture).not.toHaveBeenCalled();+ });++ it("does not suppress tracking when the global is not true", async () => {+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_DO_NOT_TRACK__ = false;++ await trackInstall();++ expect(mockPosthog.capture).toHaveBeenCalledWith(+ "canvas_install",+ expect.any(Object),+ );+ });+ });+describe("getTelemetryDistinctId", () => {it("returns null when consent is not granted", async () => {await expect(getTelemetryDistinctId()).resolves.toBeNull();diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex 87db114584..a0c0812c7b 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -77,7 +77,13 @@ const ASSET_LIKE_EXTENSIONS = new Set([// Args// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-export function parseArgs(argv = process.argv.slice(2)) {+function isEnvFlagEnabled(value) {+ if (typeof value !== "string") return false;+ const normalized = value.trim().toLowerCase();+ return normalized === "1" || normalized === "true";+}++export function parseArgs(argv = process.argv.slice(2), env = process.env) {const config = {port: 3001,host: "::",@@ -91,6 +97,8 @@ export function parseArgs(argv = process.argv.slice(2)) {lockToCloud: null,basePath: "/",vscodeBasePath: null,+ // Also settable via the --disable-telemetry flag below.+ disableTelemetry: isEnvFlagEnabled(env.AGENT_CANVAS_DISABLE_TELEMETRY),};for (let i = 0; i < argv.length; i++) {@@ -149,6 +157,9 @@ export function parseArgs(argv = process.argv.slice(2)) {case "--auth-required":config.authRequired = true;break;+ case "--disable-telemetry":+ config.disableTelemetry = true;+ break;case "--reject-prefix": {const prefix = argv[++i];if (!prefix || !prefix.startsWith("/")) {@@ -244,6 +255,12 @@ OPTIONS:--lock-to-cloud <cloud-url> Lock backend setup to a single OpenHands CloudURL. Hides manual/local backend setup and thecustom Cloud URL field in the pre-built frontend.+ --disable-telemetry Disable all product telemetry (including the+ anonymous install event) in the pre-built+ frontend at runtime, without VITE_DO_NOT_TRACK+ baked in. Injects+ window.__AGENT_CANVAS_DO_NOT_TRACK__ = true.+ Equivalent to AGENT_CANVAS_DISABLE_TELEMETRY=1.--base-path <path> Mount the SPA under <path> (default: /).For example, --base-path /canvas servesindex.html and assets under /canvas.@@ -321,6 +338,12 @@ ROUTING:* editor control can render here at all. Absent means this origin serves no* editor β which is the correct answer for the public-mode instance, whose* route table deliberately omits it.+ *+ * - `disableTelemetry`: sets `window.__AGENT_CANVAS_DO_NOT_TRACK__ = true` so a+ * published bundle disables all telemetry (including the anonymous install+ * event) at runtime without VITE_DO_NOT_TRACK baked in. Read by+ * `isDoNotTrackEnabled()` in `#/services/telemetry`. Enabled by+ * AGENT_CANVAS_DISABLE_TELEMETRY=1 or the --disable-telemetry flag.*/function makeConfigInjectionScript(sessionApiKey,@@ -329,6 +352,7 @@ function makeConfigInjectionScript(lockToCloud,basePath,vscodeBasePath,+ disableTelemetry,) {const parts = [];@@ -384,6 +408,10 @@ function makeConfigInjectionScript();}+ if (disableTelemetry) {+ parts.push(`window.__AGENT_CANVAS_DO_NOT_TRACK__=true;`);+ }+if (parts.length === 0) return "";return `<script>(function(){${parts.join("")}}());</script>`;@@ -404,6 +432,7 @@ async function serveInjectedIndexHtml(lockToCloud,basePath,vscodeBasePath,+ disableTelemetry,} = {},) {let content;@@ -420,6 +449,7 @@ async function serveInjectedIndexHtml(lockToCloud,basePath,vscodeBasePath,+ disableTelemetry,);// Inject right before </head> so the key is available before any app code runs.// replace() targets the first (and only) </head> in well-formed HTML.@@ -469,6 +499,7 @@ function needsRuntimeInjection(injectionOpts) {injectionOpts.runtimeServicesInfo ||injectionOpts.lockToCloud ||injectionOpts.vscodeBasePath ||+ injectionOpts.disableTelemetry ||(injectionOpts.basePath && injectionOpts.basePath !== "/"),);}@@ -614,6 +645,7 @@ export function startStaticServer(config) {lockToCloud: config.lockToCloud || null,basePath: normalizeBasePath(config.basePath),vscodeBasePath: config.vscodeBasePath || null,+ disableTelemetry: config.disableTelemetry || false,};const basePath = injectionOpts.basePath;const rejectPrefixes = config.rejectPrefixes ?? [];diff --git a/src/services/telemetry.ts b/src/services/telemetry.tsindex e3dde89b7f..05edaa4211 100644--- a/src/services/telemetry.ts+++ b/src/services/telemetry.ts@@ -24,6 +24,11 @@* Users can disable all telemetry (including install tracking) via:* - Setting VITE_DO_NOT_TRACK=1 environment variable* - Browser's Do Not Track setting+ * - Injecting window.__AGENT_CANVAS_DO_NOT_TRACK__ = true at runtime, which the+ * static server does from AGENT_CANVAS_DISABLE_TELEMETRY=1 (or the equivalent+ * --disable-telemetry flag) so a precompiled bundle can opt out without+ * VITE_DO_NOT_TRACK baked into the image. Under this flag the PostHog client+ * is never initialized, so consent mirrored from a backend cannot opt it in.*/import type { BootstrapConfig, CaptureResult, PostHog } from "posthog-js";@@ -95,6 +100,20 @@ let pendingBootstrap: BootstrapConfig | undefined;let telemetryConfig: TelemetryConfig = {};let telemetryDisabled = false;+/** Deployment-level opt-out injected by static-server.mjs (see file header). */+function isRuntimeDoNotTrackEnabled(): boolean {+ return (+ typeof window !== "undefined" &&+ (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_DO_NOT_TRACK__ === true+ );+}++/** True when telemetry must stay fully off: the SDK is never initialized. */+function isTelemetryHardDisabled(): boolean {+ return telemetryDisabled || isRuntimeDoNotTrackEnabled();+}+interface TelemetryIdentity {distinctId: string;properties: Record<string, unknown>;@@ -231,7 +250,7 @@ export function configureTelemetry(config: TelemetryConfiguration): void {}function getResolvedTelemetryConfig(): Required<TelemetryConfig> | null {- if (telemetryDisabled) return null;+ if (isTelemetryHardDisabled()) return null;return {apiKey: telemetryConfig.apiKey || DEFAULT_POSTHOG_API_KEY,@@ -286,6 +305,11 @@ function isDoNotTrackEnabled(): boolean {return true;}+ // Runtime-injected window global (see file header).+ if (isRuntimeDoNotTrackEnabled()) {+ return true;+ }+// Check Node.js environment variable (SSR/testing)if (typeof process !== "undefined" && process.env?.DO_NOT_TRACK === "1") {return true;@@ -546,7 +570,7 @@ export async function setTelemetryConsent(const previousConsent = getTelemetryConsent();const unchanged = previousConsent === consent;localStorage.setItem(TELEMETRY_CONSENT_KEY, consent);- if (telemetryDisabled) return;+ if (isTelemetryHardDisabled()) return;if (unchanged) return;// Reuse an initialized client synchronously so a same-flush identify()