File size: 20,717 Bytes
fd2c364 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
// Mock posthog-js before importing telemetry service
let identifiedUserId: string | undefined;
let anonymousDistinctId = "ph-test-distinct-id";
let latestPostHogConfig:
| (Record<string, unknown> & { before_send: (event: unknown) => unknown })
| undefined;
const mockPosthog = {
init: vi.fn(),
capture: vi.fn(),
captureException: vi.fn(),
opt_in_capturing: vi.fn(),
opt_out_capturing: vi.fn(),
has_opted_out_capturing: vi.fn(() => false),
identify: vi.fn((userId: string) => {
identifiedUserId = userId;
}),
get_property: vi.fn((property: string) =>
property === "$user_id" ? identifiedUserId : undefined,
),
get_distinct_id: vi.fn(() => identifiedUserId ?? anonymousDistinctId),
reset: vi.fn((resetDeviceId = false) => {
identifiedUserId = undefined;
anonymousDistinctId = resetDeviceId
? "ph-reset-device-id"
: "ph-reset-distinct-id";
}),
};
mockPosthog.init.mockImplementation((_, config) => {
latestPostHogConfig = config;
return mockPosthog;
});
vi.mock("posthog-js", () => ({
default: mockPosthog,
}));
import {
clearPendingCloudTelemetryConsent,
clearPendingLocalTelemetryRevocation,
clearTelemetryData,
configureTelemetry,
getPendingCloudTelemetryConsent,
getPendingLocalTelemetryRevocationId,
getTelemetryConsent,
getTelemetryDistinctId,
getTelemetryDistinctIdForConsentSync,
initializePostHogClient,
isTelemetryEnabled,
setTelemetryBackendContext,
setTelemetryCloudContext,
setTelemetryConsent,
setTelemetryIdentity,
subscribeTelemetryConsent,
trackEvent,
trackException,
trackInstall,
trackSessionStart,
} from "#/services/telemetry";
// Mock import.meta.env for tests
vi.stubGlobal("import.meta", {
env: {
DEV: false,
VITE_DO_NOT_TRACK: undefined,
},
});
describe("Telemetry Service", () => {
beforeEach(async () => {
// Clear localStorage before each test
localStorage.clear();
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 mock
vi.clearAllMocks();
identifiedUserId = undefined;
anonymousDistinctId = "ph-test-distinct-id";
mockPosthog.has_opted_out_capturing.mockReturnValue(false);
mockPosthog.get_distinct_id.mockImplementation(
() => identifiedUserId ?? anonymousDistinctId,
);
await setTelemetryIdentity(null);
setTelemetryBackendContext({});
});
afterEach(() => {
configureTelemetry({});
localStorage.clear();
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", () => {
it("retries one named Canvas client with runtime configuration", async () => {
configureTelemetry({
apiKey: "phc_embedded",
apiHost: "https://events.example.com",
uiHost: "https://posthog.example.com",
});
configureTelemetry({
apiKey: undefined,
apiHost: undefined,
uiHost: undefined,
});
mockPosthog.init.mockImplementationOnce(() => null);
await setTelemetryConsent("granted");
await expect(initializePostHogClient()).resolves.toBe(mockPosthog);
expect(mockPosthog.init).toHaveBeenCalledTimes(2);
expect(mockPosthog.init).toHaveBeenCalledWith(
"phc_embedded",
expect.objectContaining({
api_host: "https://events.example.com",
ui_host: "https://posthog.example.com",
persistence_name: "agent-canvas",
consent_persistence_name: "agent-canvas-consent",
person_profiles: "always",
capture_pageview: "history_change",
autocapture: true,
}),
"agent-canvas",
);
expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
const config = mockPosthog.init.mock.calls[1][1];
expect(
config.before_send({
event: "test_event",
properties: { client_source: "incorrect", custom: "value" },
}),
).toEqual({
event: "test_event",
properties: expect.objectContaining({
client_source: "agent_canvas",
client_version: expect.any(String),
package_name: "@openhands/agent-canvas",
package_version: expect.any(String),
backend_kind: null,
agent_server_version: "unknown",
automation_sdk_version: "unknown",
backend_version: "unknown",
custom: "value",
}),
});
setTelemetryBackendContext({
backendKind: "local",
agentServerVersion: "1.36.2",
automationSdkVersion: "1.36.3",
});
expect(
config.before_send({
event: "backend_context_event",
properties: { backend_kind: "cloud", custom: "value" },
}),
).toEqual({
event: "backend_context_event",
properties: expect.objectContaining({
backend_kind: "cloud",
agent_server_version: "1.36.2",
automation_sdk_version: "1.36.3",
backend_version: "1.36.2",
custom: "value",
}),
});
});
});
describe("Cloud identity and context", () => {
it("identifies a consented Cloud user and adds Cloud event context", async () => {
await setTelemetryConsent("granted");
setTelemetryCloudContext({
userId: "user-a",
email: "a@example.com",
orgId: "org-a",
});
await setTelemetryIdentity("user-a", { email: "a@example.com" });
expect(mockPosthog.identify).toHaveBeenCalledWith("user-a", {
email: "a@example.com",
});
await expect(getTelemetryDistinctId()).resolves.toBe("user-a");
expect(latestPostHogConfig).toBeDefined();
expect(
latestPostHogConfig!.before_send({
event: "cloud_event",
properties: {},
}),
).toEqual({
event: "cloud_event",
properties: expect.objectContaining({
cloud_user_id: "user-a",
cloud_user_email: "a@example.com",
cloud_org_id: "org-a",
}),
});
});
it("resets before switching Cloud accounts and restores consent", async () => {
await setTelemetryConsent("granted");
await setTelemetryIdentity("user-a");
vi.clearAllMocks();
await setTelemetryIdentity("user-b");
expect(mockPosthog.reset).toHaveBeenCalledWith(false);
expect(mockPosthog.opt_in_capturing).toHaveBeenCalledOnce();
expect(mockPosthog.identify).toHaveBeenCalledWith("user-b", {});
});
it("clears identity on logout without changing the device", async () => {
await setTelemetryConsent("granted");
await setTelemetryIdentity("user-a");
vi.clearAllMocks();
await setTelemetryIdentity(null);
expect(mockPosthog.reset).toHaveBeenCalledWith(false);
expect(mockPosthog.opt_in_capturing).toHaveBeenCalledOnce();
expect(mockPosthog.identify).not.toHaveBeenCalled();
});
it("removes identity on denial and reapplies it after consent returns", async () => {
await setTelemetryConsent("granted");
await setTelemetryIdentity("user-a");
vi.clearAllMocks();
await setTelemetryConsent("denied");
expect(mockPosthog.reset).toHaveBeenCalledWith(false);
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
vi.clearAllMocks();
await setTelemetryConsent("granted");
expect(mockPosthog.identify).toHaveBeenCalledWith("user-a", {});
});
it("syncs denial for the actor that existed before PostHog reset", async () => {
await setTelemetryConsent("granted");
await setTelemetryIdentity("user-a");
await setTelemetryConsent("denied");
expect(mockPosthog.get_distinct_id()).toBe("ph-reset-distinct-id");
expect(getPendingLocalTelemetryRevocationId()).toBe("user-a");
await expect(getTelemetryDistinctIdForConsentSync()).resolves.toBe(
"user-a",
);
clearPendingLocalTelemetryRevocation("user-a");
expect(getPendingLocalTelemetryRevocationId()).toBeNull();
});
it("clears Cloud user context for local events", async () => {
await setTelemetryConsent("granted");
setTelemetryCloudContext({
userId: "user-a",
email: "a@example.com",
orgId: "org-a",
});
setTelemetryCloudContext(null);
expect(latestPostHogConfig).toBeDefined();
expect(
latestPostHogConfig!.before_send({
event: "local_event",
properties: {},
}),
).toEqual({
event: "local_event",
properties: expect.objectContaining({
cloud_user_id: null,
cloud_user_email: null,
cloud_org_id: null,
}),
});
});
});
describe("getTelemetryConsent", () => {
it("returns 'pending' when no consent has been set", () => {
expect(getTelemetryConsent()).toBe("pending");
});
it("returns 'granted' when consent is granted", () => {
localStorage.setItem("openhands-telemetry-consent", "granted");
expect(getTelemetryConsent()).toBe("granted");
});
it("returns 'denied' when consent is denied", () => {
localStorage.setItem("openhands-telemetry-consent", "denied");
expect(getTelemetryConsent()).toBe("denied");
});
it("treats same-origin locked Cloud cookie auth as granted", () => {
localStorage.setItem("openhands-telemetry-consent", "denied");
(
window as unknown as Record<string, unknown>
).__AGENT_CANVAS_LOCK_TO_CLOUD__ = window.location.origin;
expect(getTelemetryConsent()).toBe("granted");
});
});
describe("setTelemetryConsent", () => {
it("stores granted consent in localStorage", async () => {
await setTelemetryConsent("granted");
expect(localStorage.getItem("openhands-telemetry-consent")).toBe(
"granted",
);
});
it("stores denied consent in localStorage", async () => {
await setTelemetryConsent("denied");
expect(localStorage.getItem("openhands-telemetry-consent")).toBe(
"denied",
);
});
it("applies consent synchronously once the shared client is initialized", async () => {
await setTelemetryConsent("denied");
vi.clearAllMocks();
const update = setTelemetryConsent("granted");
expect(mockPosthog.opt_in_capturing).toHaveBeenCalledTimes(1);
await update;
});
it("marks an explicit pre-login choice for backend reconciliation", async () => {
const listener = vi.fn();
const unsubscribe = subscribeTelemetryConsent(listener);
await setTelemetryConsent("granted");
expect(getPendingCloudTelemetryConsent()).toBe("granted");
expect(listener).toHaveBeenCalledTimes(1);
unsubscribe();
});
it("applies capture consent before notifying identity reconcilers", async () => {
const listener = vi.fn(() => {
expect(getTelemetryConsent()).toBe("granted");
expect(mockPosthog.opt_in_capturing).toHaveBeenCalledTimes(1);
});
const unsubscribe = subscribeTelemetryConsent(listener);
await setTelemetryConsent("granted");
expect(listener).toHaveBeenCalledTimes(1);
unsubscribe();
});
it("does not mark consent mirrored from backend settings as pending", async () => {
await setTelemetryConsent("granted", { syncToCloud: false });
expect(getPendingCloudTelemetryConsent()).toBeNull();
});
it("does not re-emit PostHog opt-in for unchanged granted consent", async () => {
await setTelemetryConsent("granted");
vi.clearAllMocks();
await setTelemetryConsent("granted", { syncToCloud: false });
expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();
});
it("only clears the pending decision it expects", async () => {
await setTelemetryConsent("granted");
clearPendingCloudTelemetryConsent("denied");
expect(getPendingCloudTelemetryConsent()).toBe("granted");
clearPendingCloudTelemetryConsent("granted");
expect(getPendingCloudTelemetryConsent()).toBeNull();
});
});
describe("isTelemetryEnabled", () => {
it("returns false when consent is pending", () => {
expect(isTelemetryEnabled()).toBe(false);
});
it("returns true when consent is granted", async () => {
await setTelemetryConsent("granted");
expect(isTelemetryEnabled()).toBe(true);
});
it("returns false when consent is denied", async () => {
await setTelemetryConsent("denied");
expect(isTelemetryEnabled()).toBe(false);
});
});
describe("trackInstall", () => {
it("sends install event immediately without consent (new behavior)", async () => {
// No consent set - should still send the install event
await trackInstall();
expect(mockPosthog.capture).toHaveBeenCalledTimes(1);
expect(mockPosthog.capture).toHaveBeenCalledWith(
"canvas_install",
expect.objectContaining({
platform: expect.any(String),
user_agent: expect.any(String),
}),
);
});
it("only sends install event once", async () => {
await trackInstall();
await trackInstall();
await trackInstall();
// Should only be called once
expect(mockPosthog.capture).toHaveBeenCalledTimes(1);
});
it("includes correct event data", async () => {
await trackInstall();
expect(mockPosthog.capture).toHaveBeenCalledWith(
"canvas_install",
expect.objectContaining({
platform: expect.any(String),
user_agent: expect.any(String),
referrer: expect.any(String),
url_origin: expect.any(String),
embedded: expect.any(Boolean),
}),
);
});
it("restores opt-out state after sending install event when consent not granted", async () => {
// No consent set
await trackInstall();
// Should opt out capturing after sending install event
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
});
it("does not restore opt-out state when consent is granted", async () => {
// Grant consent first
await setTelemetryConsent("granted");
vi.clearAllMocks(); // Clear the opt_in call from setTelemetryConsent
await trackInstall();
// Should NOT call opt_out_capturing when consent is granted
expect(mockPosthog.opt_out_capturing).not.toHaveBeenCalled();
});
});
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();
});
it("returns the PostHog distinct ID when consent is granted", async () => {
await setTelemetryConsent("granted");
await expect(getTelemetryDistinctId()).resolves.toBe(
"ph-test-distinct-id",
);
});
});
describe("trackEvent", () => {
it("does not send event when consent is not granted", async () => {
await trackEvent("test_event", { foo: "bar" });
expect(mockPosthog.capture).not.toHaveBeenCalled();
});
it("sends custom event when consent is granted", async () => {
await setTelemetryConsent("granted");
await trackEvent("custom_action", { button: "submit" });
expect(mockPosthog.capture).toHaveBeenCalledWith("custom_action", {
button: "submit",
});
});
it("does not repair SDK opt-out or capture when consent is denied", async () => {
await setTelemetryConsent("denied");
vi.clearAllMocks();
mockPosthog.has_opted_out_capturing.mockReturnValue(true);
await trackEvent("custom_action");
expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();
expect(mockPosthog.capture).not.toHaveBeenCalled();
});
it("repairs a stale SDK opt-out before a consented custom event", async () => {
localStorage.setItem("openhands-telemetry-consent", "granted");
mockPosthog.has_opted_out_capturing.mockReturnValue(true);
await trackEvent("custom_action");
expect(mockPosthog.opt_in_capturing).toHaveBeenCalledTimes(1);
expect(mockPosthog.capture).toHaveBeenCalledWith("custom_action", {});
});
it("stops an initialized client when telemetry is disabled", async () => {
await setTelemetryConsent("granted");
vi.clearAllMocks();
configureTelemetry(false);
await trackEvent("custom_action");
expect(mockPosthog.opt_out_capturing).toHaveBeenCalledTimes(1);
expect(mockPosthog.capture).not.toHaveBeenCalled();
configureTelemetry({});
});
it("does not let a consent refresh override a hard disable", async () => {
await setTelemetryConsent("denied");
configureTelemetry(false);
vi.clearAllMocks();
await setTelemetryConsent("granted", { syncToCloud: false });
expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();
configureTelemetry({});
});
});
describe("trackSessionStart", () => {
it("repairs a stale SDK opt-out before recording the session", async () => {
localStorage.setItem("openhands-telemetry-consent", "granted");
mockPosthog.has_opted_out_capturing.mockReturnValue(true);
await trackSessionStart();
expect(mockPosthog.opt_in_capturing).toHaveBeenCalledTimes(1);
expect(mockPosthog.capture).toHaveBeenCalledWith(
"canvas_new_session",
expect.any(Object),
);
});
});
describe("trackException", () => {
it("uses the consent-aware boundary", async () => {
await setTelemetryConsent("granted");
const error = new Error("failure");
await trackException(error, { error_source: "test" });
expect(mockPosthog.captureException).toHaveBeenCalledWith(error, {
error_source: "test",
});
});
});
describe("clearTelemetryData", () => {
it("clears all telemetry data from localStorage", async () => {
await setTelemetryConsent("granted");
await setTelemetryIdentity("user-a");
localStorage.setItem("openhands-telemetry-first-use", "true");
await clearTelemetryData();
expect(localStorage.getItem("openhands-telemetry-consent")).toBeNull();
expect(getPendingCloudTelemetryConsent()).toBeNull();
expect(localStorage.getItem("openhands-telemetry-first-use")).toBeNull();
expect(mockPosthog.reset).toHaveBeenCalledWith(true);
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
await expect(getTelemetryDistinctIdForConsentSync()).resolves.toBe(
"user-a",
);
});
it("falls back to opting out if the SDK cannot reset", async () => {
await setTelemetryConsent("granted");
mockPosthog.reset.mockImplementationOnce(() => {
throw new Error("reset failed");
});
vi.clearAllMocks();
await expect(clearTelemetryData()).resolves.toBeUndefined();
expect(mockPosthog.opt_out_capturing).toHaveBeenCalledOnce();
});
});
describe("PostHog integration", () => {
it("calls opt_in_capturing when consent is granted", async () => {
await setTelemetryConsent("granted");
expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
});
it("calls opt_out_capturing when consent is denied", async () => {
await setTelemetryConsent("denied");
expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
});
});
});
|