diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index 7c008bd9f9..d3314b185f 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -426,9 +426,9 @@ export const ALLOWED: Allowed[] = [ }, { file: "desktop/src-tauri/src/move_to_cloud.rs", - what: /^\/api\/v2\/(people\/me\/organizations|organizations\/\{\}\{path\})$/, + what: /^\/api\/v2\/(people\/me\/(organizations|desktop-installations)|organizations\/\{\}\{path\})$/, rule: "hand-built-v2", - why: "the move to OpenBot Cloud, from Rust, which has no generated client: the export from the OpenBot on this computer and the import into OpenBot Cloud, in the organization each answers for the person", + why: "the move to OpenBot Cloud, from Rust, which has no generated client: the export from the OpenBot on this computer and the import into OpenBot Cloud, in the organization each answers for the person, and the installation told to OpenBot Cloud after the move's sign-in (recordDesktopInstallation, held to the spec by api/openapi-desktop-installations.test.ts)", }, { file: "desktop/src-tauri/src/move_to_cloud/tests.rs", diff --git a/api/openapi-desktop-installations.test.ts b/api/openapi-desktop-installations.test.ts index 61952e9ced..524a2ea0c6 100644 --- a/api/openapi-desktop-installations.test.ts +++ b/api/openapi-desktop-installations.test.ts @@ -211,3 +211,84 @@ test("the description says which servers may receive the id, every caller, and t ); expect(text).toContain("accepted and dropped, whoever sends it"); }); + +test("Desktop's own sender asks exactly what the spec takes: POST, this address, installationId, an Idempotency-Key, and only 204 counts", () => { + // Move to Cloud's sign-in sends it itself (desktop/src-tauri/src/move_to_cloud.rs), so its + // request is held to the operation here rather than only to a fake in its own tests. + const sender = readFileSync( + join(import.meta.dir, "../desktop/src-tauri/src/move_to_cloud.rs"), + "utf8", + ); + expect(sender).toContain( + `pub const DESKTOP_INSTALLATIONS_PATH: &str = "${PATH}";`, + ); + const start = sender.indexOf("pub fn record_desktop_installation("); + expect(start).toBeGreaterThan(-1); + const body = sender.slice(start, sender.indexOf("\n}\n", start)); + expect(body).toContain(".post("); + expect(body).not.toMatch(/\.(get|put|patch|delete)\(/); + // The body's one property, by the spec's own name for it. + const schema = spec.components.schemas.DesktopInstallation as Schema; + const names = Object.keys(schema.properties ?? {}); + expect(names).toEqual(["installationId"]); + expect(body).toContain(`json!({ "${names[0]}": installation_id })`); + expect(body).toContain('.header("Idempotency-Key", uuid::Uuid::new_v4()'); + // An installation is the person's: the request names no organization. + expect(body).not.toContain("OpenBot-Organization"); + // The spec's one success; anything else is a refusal, and nothing is sent again. + expect(body).toMatch(/204 => Ok\(\(\)\)/); + expect(body).toContain("redirect::Policy::none()"); +}); + +test("the request Desktop's sender makes, as its own test receives it, is one the spec takes", () => { + // desktop/src-tauri/src/move_to_cloud/tests.rs holds the sender's bytes to this file. + const request = JSON.parse( + readFileSync( + join( + import.meta.dir, + "../app/tests/fixtures/desktop-installation-request.json", + ), + "utf8", + ), + ) as { + method: string; + path: string; + content_type: string; + installation_id: string; + body: string; + idempotency_key: string; + absent_headers: string[]; + }; + expect(request.method.toLowerCase()).toBe("post"); + expect(spec.paths[request.path]?.post).toBe(operation); + expect(Object.keys(operation.requestBody?.content ?? {})).toEqual([ + request.content_type, + ]); + const body = JSON.parse(request.body); + expect(RecordDesktopInstallationBody.strict().parse(body)).toEqual({ + installationId: request.installation_id, + }); + const key = ( + spec.components.parameters.IdempotencyKey as unknown as { + schema: { minLength: number; maxLength: number }; + } + ).schema; + expect(request.idempotency_key.length).toBeGreaterThanOrEqual(key.minLength); + expect(request.idempotency_key.length).toBeLessThanOrEqual(key.maxLength); + expect(request.absent_headers).toContain("openbot-organization"); +}); + +test("the window's hand-off key is the one the page reads", () => { + const desktop = readFileSync( + join(import.meta.dir, "../desktop/src-tauri/src/connected/window.rs"), + "utf8", + ); + const page = readFileSync( + join(import.meta.dir, "../app/src/lib/auth/window-session.ts"), + "utf8", + ); + expect(desktop).toContain('append_pair("installation_id", id)'); + expect(page).toContain( + 'export const INSTALLATION_ID_KEY = "installation_id";', + ); +}); diff --git a/app/src/lib/api/request.ts b/app/src/lib/api/request.ts index e03ba0e98c..7c68d0376e 100644 --- a/app/src/lib/api/request.ts +++ b/app/src/lib/api/request.ts @@ -27,6 +27,12 @@ export type ApiRequestOptions = RequestInit & { * `revalidated` in lib/api/revalidated.ts. */ kept?: { etag: string; body: unknown }; + /** + * `false` for a best-effort write that a refusal must leave as it is: a hosted sign-in needing + * renewal (401 `HOSTED_SIGN_IN_RENEWAL_REQUIRED`) starts no renewal, and the write is not kept to be + * sent again. The window's report of a Desktop installation (lib/auth/window-session.ts). + */ + renew?: false; }; /** @@ -69,13 +75,13 @@ export async function apiRequest( url: string, options: ApiRequestOptions = {}, ): Promise { - const { fallback, onResponse, kept, ...init } = options; + const { fallback, onResponse, kept, renew, ...init } = options; if (kept) { const headers = new Headers(init.headers); headers.set("If-None-Match", kept.etag); init.headers = headers; } - const response = await clientRequest(url, init, fallback); + const response = await clientRequest(url, init, fallback, renew); onResponse?.(response); if (response.status === 304 && kept) return kept.body as T; if (response.status === 204) return undefined as T; diff --git a/app/src/lib/auth/window-session.ts b/app/src/lib/auth/window-session.ts index 84c4c0a2cd..947cdcb533 100644 --- a/app/src/lib/auth/window-session.ts +++ b/app/src/lib/auth/window-session.ts @@ -1,4 +1,6 @@ -import { tryClient } from "@/lib/client"; +import { recordDesktopInstallation } from "@/lib/api/generated/product-events/product-events"; +import { idempotencyKey } from "@/lib/api/request"; +import { ClientError, tryClient } from "@/lib/client"; import type { WindowSignInFailure } from "@/lib/desktop/window-sign-in"; import { signInReturnPath } from "./resume"; @@ -10,6 +12,13 @@ import { signInReturnPath } from "./resume"; * reaches a server or a log, and it is taken off the address at once, so neither the history nor a * reload has it. The page then asks this OpenBot, from its own origin, for a session in exchange * (`POST /api/auth/window/session`), and the answer sets the session cookie as any sign-in does. + * + * On OpenBot Cloud, while the person shares usage data, Desktop also puts its installation's + * usage-data id in the fragment (`&installation_id=…`). Once the code is traded, the page tells + * OpenBot Cloud which installation signed in (`recordDesktopInstallation`), so usage data can join + * what the installation did before the sign-in with what the person does after it. Desktop decides: + * it never puts the id in the fragment for a company's OpenBot, its staging copy, or with usage data + * off, and the page sends only what it was given. */ /** Where the window's code is swapped for a session. Sign-in's own, outside the API. */ @@ -21,8 +30,21 @@ export type WindowSignIn = { codeVerifier: string | null; /** A path on this app, or home. Never another origin. */ next: string; + /** + * The OpenBot Desktop installation's usage-data id, a random (version 4) UUID, when Desktop put one + * in. Null when it didn't (another OpenBot than Cloud, usage data off, an older Desktop) or when + * what it put is not one. + */ + installationId: string | null; }; +/** The fragment's key for the installation's id, as Desktop writes it (connected/window.rs). */ +export const INSTALLATION_ID_KEY = "installation_id"; + +/** A random (version 4) UUID, in either case: the only id the operation takes. */ +const VERSION_4_UUID = + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + /** * Read the code, its verifier and where to go from the address's fragment, and take the fragment off * the address and out of the history at once. @@ -37,9 +59,51 @@ export function takeWindowSignIn(): WindowSignIn { code: fragment.get("code") || null, codeVerifier: fragment.get("code_verifier") || null, next: signInReturnPath(fragment.get("next")) ?? "/", + installationId: onlyInstallationId(fragment.getAll(INSTALLATION_ID_KEY)), }; } +/** The one id Desktop put in, when it is one: none, two or a malformed one is no id at all. */ +function onlyInstallationId(given: string[]): string | null { + const [id] = given; + return given.length === 1 && VERSION_4_UUID.test(id) ? id : null; +} + +/** + * Tell OpenBot which Desktop installation the person just signed in from. Best effort, once per + * sign-in: a new Idempotency-Key, no retry, and with keepalive, so it still leaves as the page goes + * on. Never throws. Only a 204 counts: anything else is logged by its status alone, never with the + * id or what came back. An OpenBot without the operation answers 404, which changes nothing. + */ +export async function recordInstallation( + installationId: string, +): Promise { + let status = 0; + try { + await recordDesktopInstallation( + { installationId }, + { "Idempotency-Key": idempotencyKey() }, + { + keepalive: true, + // A refusal asking for the hosted sign-in to be renewed starts no renewal here, and the + // report is not kept to be sent again: it is sent once, and the window goes on. + renew: false, + onResponse: (response) => { + status = response.status; + }, + }, + ); + } catch (error) { + if (error instanceof ClientError) status = error.status; + if (status) console.warn(NOT_RECORDED, status); + else console.warn("The Desktop installation could not be recorded."); + return; + } + if (status !== 204) console.warn(NOT_RECORDED, status); +} + +const NOT_RECORDED = "The Desktop installation was not recorded."; + /** How the swap ended: signed in, or why not. */ export type WindowSessionAnswer = | { signedIn: true } @@ -78,22 +142,27 @@ export async function redeemWindowSignIn( /** What the page does with the window, kept here so a test can stand in for it. */ export const windowSessionDeps = { go: (path: string) => window.location.replace(path), + record: recordInstallation, }; let once: Promise | null = null; /** * Take the fragment and swap its code, once per page however often the page is drawn: the code is - * spent by the first try. Signed in, the window goes on to `next`, replacing this page in the - * history. + * spent by the first try. Signed in, the page records the installation when Desktop gave its id, + * without waiting for the answer, and the window goes on to `next`, replacing this page in the + * history. A failed swap records nothing. */ export function finishWindowSignIn(): Promise { once ??= (async (): Promise => { - const { code, codeVerifier, next } = takeWindowSignIn(); + const { code, codeVerifier, next, installationId } = takeWindowSignIn(); if (!code || !codeVerifier) return { signedIn: false, reason: "invalid_code" }; const answer = await redeemWindowSignIn(code, codeVerifier); - if (answer.signedIn) windowSessionDeps.go(next); + if (answer.signedIn) { + if (installationId) void windowSessionDeps.record(installationId); + windowSessionDeps.go(next); + } return answer; })(); return once; diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index ad5b937d15..92bb8b5a7e 100644 --- a/app/src/lib/client.ts +++ b/app/src/lib/client.ts @@ -353,6 +353,8 @@ async function refusal( fallback: string | undefined, /** The request that was refused, as it was sent, for a write a renewal sends again. */ sent?: { path: string; init: RequestInit }, + /** `false`: a refusal that asks for a renewal starts none (`ApiRequestOptions.renew`). */ + renew?: false, ): Promise { const body = (await response.json().catch(() => null)) as { error?: unknown; @@ -385,7 +387,7 @@ async function refusal( * A hosted OpenBot's sign-in needing renewal, which is never being signed out: renewed in the * background, and the write it interrupted is sent again once the page is back. */ - if (renewalRequired(error)) + if (renew !== false && renewalRequired(error)) renewHostedSignIn( response.headers.get(SIGN_IN_HEADER), sent ? await keepPendingWrite(sent.path, sent.init) : null, @@ -404,12 +406,20 @@ export async function clientRequest( path: string, init: RequestInit, fallback?: string, + /** `false`: a refusal that asks for a renewal starts none, and nothing is kept to send again. */ + renew?: false, ): Promise { const response = await request(path, init); // A 304 is an answer only to a request that named the copy it holds (`If-None-Match`). if (response.status === 304 && new Headers(init.headers).has("If-None-Match")) return response; - if (!response.ok) throw await refusal(response, fallback, { path, init }); + if (!response.ok) + throw await refusal( + response, + fallback, + renew === false ? undefined : { path, init }, + renew, + ); return response; } diff --git a/app/tests/desktop-window-installation.test.ts b/app/tests/desktop-window-installation.test.ts new file mode 100644 index 0000000000..7e081b6bac --- /dev/null +++ b/app/tests/desktop-window-installation.test.ts @@ -0,0 +1,351 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + spyOn, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { getRecordDesktopInstallationMockHandler } from "@/lib/api/generated/product-events/product-events.msw"; +import { RecordDesktopInstallationBody } from "@/lib/api/generated/product-events/product-events.zod"; +import { + RENEWAL_REQUIRED, + renewalDeps, + SIGN_IN_HEADER, +} from "@/lib/auth/renewal"; +import fixture from "./fixtures/desktop-window-signed-in-address.json"; + +/** + * The window's page telling OpenBot Cloud which OpenBot Desktop installation signed in + * (`recordDesktopInstallation`), from the id Desktop puts in the hand-off fragment. + * + * Across both boundaries, neither side mocked: the addresses are the ones Desktop's own + * `signed_in_address` builds (fixtures/desktop-window-signed-in-address.json, which a Desktop test + * holds it to), read by the page's own `takeWindowSignIn`; and the report goes out through the + * generated client to the handler generated from the shared spec, its body checked against the + * spec's strict schema. + */ + +type Sent = { + body: unknown; + idempotencyKey: string | null; + keepalive: boolean; + organization: string | null; +}; + +let recorded: Sent[] = []; +/** `keepalive` as the page handed it to fetch, per report: msw's Request does not carry it here. */ +let keepalives: (boolean | undefined)[] = []; +let trades: number[] = []; +let tradeAnswers: number[] = []; +let recordAnswer: number | "network" | "renewal" = 204; +/** While set, the trade's answer waits for it. */ +let tradeHeld: Promise | null = null; +/** A trade answer that is no answer at all: the request fails. */ +const NO_ANSWER = -1; + +const server = setupServer( + http.post("*/api/auth/window/session", async () => { + if (tradeHeld) await tradeHeld; + const status = + tradeAnswers.length > 1 ? tradeAnswers.shift() : tradeAnswers[0]; + trades.push(status ?? 200); + if (status === NO_ANSWER) return HttpResponse.error(); + return status === undefined || status === 200 + ? HttpResponse.json({ ok: true }) + : HttpResponse.json({ error: "no" }, { status }); + }), + getRecordDesktopInstallationMockHandler(async ({ request }) => { + recorded.push({ + body: await request.clone().json(), + idempotencyKey: request.headers.get("Idempotency-Key"), + keepalive: keepalives.at(-1) === true, + organization: request.headers.get("OpenBot-Organization"), + }); + if (recordAnswer === "network") throw HttpResponse.error(); + if (recordAnswer === "renewal") + throw HttpResponse.json( + { + status: 401, + title: "Sign in again", + type: "about:blank", + code: RENEWAL_REQUIRED, + }, + { status: 401, headers: { [SIGN_IN_HEADER]: "/sign" } }, + ); + if (recordAnswer !== 204) + throw HttpResponse.json( + { status: recordAnswer, title: "no", type: "about:blank" }, + { status: recordAnswer }, + ); + }), +); + +beforeAll(() => { + GlobalRegistrator.register({ url: "https://my.open.bot/" }); + server.listen({ onUnhandledRequest: "error" }); + const sendOn = globalThis.fetch; + globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + if (url.includes("/api/v2/people/me/desktop-installations")) + keepalives.push(init?.keepalive); + return sendOn(input, init); + }) as typeof fetch; +}); +afterEach(() => { + recorded = []; + keepalives = []; + trades = []; + tradeAnswers = []; + recordAnswer = 204; + tradeHeld = null; + server.resetHandlers(); +}); +afterAll(async () => { + server.close(); + await GlobalRegistrator.unregister(); +}); + +let fresh = 0; +/** The page's module as a new page loads it: `finishWindowSignIn` runs once per page. */ +async function newPage(address: string) { + window.history.replaceState(null, "", address); + fresh += 1; + const page = (await import( + `../src/lib/auth/window-session.ts?page=${fresh}` + )) as typeof import("../src/lib/auth/window-session"); + const went: string[] = []; + page.windowSessionDeps.go = (path: string) => { + went.push(path); + }; + return { page, went }; +} + +/** Until the fire-and-forget report has been answered (or `n` of them). */ +async function settled(n = 1) { + for (let i = 0; i < 100 && recorded.length < n; i += 1) + await new Promise((resolve) => setTimeout(resolve, 5)); + await new Promise((resolve) => setTimeout(resolve, 20)); +} + +const withoutFragment = (address: string) => address.split("#")[0]; + +describe("the hand-off address Desktop builds", () => { + test("with the id: the page reads it with the code, and takes the whole fragment off the address", async () => { + const { page } = await newPage(fixture.with_id); + const taken = page.takeWindowSignIn(); + expect(taken).toEqual({ + code: fixture.code, + codeVerifier: fixture.code_verifier, + // Desktop's `next` (`/c/a b?x=1&y=2`), the same path and query, as the address spells it. + next: "/c/a%20b?x=1&y=2", + installationId: fixture.installation_id, + }); + expect(window.location.hash).toBe(""); + expect(window.location.href).toBe(withoutFragment(fixture.with_id)); + }); + + test("without it (another OpenBot than Cloud, usage data off, an older Desktop): no id", async () => { + const { page } = await newPage(fixture.without_id); + expect(page.takeWindowSignIn().installationId).toBeNull(); + }); + + test("the key is the one Desktop writes", async () => { + const { page } = await newPage(fixture.with_id); + expect(page.INSTALLATION_ID_KEY).toBe("installation_id"); + expect(new URL(fixture.with_id).hash).toContain( + `&${page.INSTALLATION_ID_KEY}=${fixture.installation_id}`, + ); + }); + + test("anything but a random (version 4) UUID is no id", async () => { + for (const id of [ + "", + "not-an-id", + // Version 1 carries a time and a hardware address: never taken. + "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + `${fixture.installation_id}x`, + `${fixture.installation_id.slice(0, -1)}`, + ]) { + const { page } = await newPage( + `https://my.open.bot/desktop/signed-in#code=c&code_verifier=v&next=%2F&installation_id=${encodeURIComponent(id)}`, + ); + expect(page.takeWindowSignIn().installationId).toBeNull(); + } + const upper = fixture.installation_id.toUpperCase(); + const { page } = await newPage( + `https://my.open.bot/desktop/signed-in#code=c&code_verifier=v&next=%2F&installation_id=${upper}`, + ); + expect(page.takeWindowSignIn().installationId).toBe(upper); + }); + + test("the id twice is no id, even the same one twice: the code is still read", async () => { + const other = "0b6e2d4f-1c88-4c7d-9a35-3f2c9a648e1b"; + for (const extra of [other, fixture.installation_id]) { + const { page } = await newPage( + `${fixture.with_id}&installation_id=${extra}`, + ); + const taken = page.takeWindowSignIn(); + expect(taken.installationId).toBeNull(); + expect(taken.code).toBe(fixture.code); + expect(window.location.hash).toBe(""); + } + }); +}); + +describe("once the code is traded", () => { + test("the page records the installation once, exactly as the spec takes it, and goes on", async () => { + const { page, went } = await newPage(fixture.with_id); + expect(await page.finishWindowSignIn()).toEqual({ signedIn: true }); + await settled(); + expect(trades).toEqual([200]); + expect(recorded).toHaveLength(1); + const [sent] = recorded; + expect(sent.body).toEqual({ installationId: fixture.installation_id }); + expect(RecordDesktopInstallationBody.strict().parse(sent.body)).toEqual({ + installationId: fixture.installation_id, + }); + expect(sent.idempotencyKey).toMatch(/^[0-9a-f]{32}$/); + // So it still leaves as the window goes on to `next`. + expect(sent.keepalive).toBe(true); + // An installation is the person's: the request names no organization. + expect(sent.organization).toBeNull(); + expect(went).toHaveLength(1); + }); + + test("nothing is recorded while the trade is still waiting for its answer", async () => { + let answer = () => {}; + tradeHeld = new Promise((resolve) => { + answer = resolve; + }); + const { page, went } = await newPage(fixture.with_id); + const finished = page.finishWindowSignIn(); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(recorded).toEqual([]); + expect(went).toEqual([]); + answer(); + expect(await finished).toEqual({ signedIn: true }); + await settled(); + expect(trades).toEqual([200]); + expect(recorded).toHaveLength(1); + }); + + test("drawn twice, the page trades once and records once", async () => { + const { page } = await newPage(fixture.with_id); + await Promise.all([page.finishWindowSignIn(), page.finishWindowSignIn()]); + await page.finishWindowSignIn(); + await settled(); + expect(trades).toEqual([200]); + expect(recorded).toHaveLength(1); + }); + + test("refused once for where it came from (403), then traded: recorded once", async () => { + tradeAnswers = [403, 200]; + const { page } = await newPage(fixture.with_id); + expect(await page.finishWindowSignIn()).toEqual({ signedIn: true }); + await settled(); + expect(trades).toEqual([403, 200]); + expect(recorded).toHaveLength(1); + }); + + test("no id in the fragment: nothing recorded, the window still goes on", async () => { + const { page, went } = await newPage(fixture.without_id); + expect(await page.finishWindowSignIn()).toEqual({ signedIn: true }); + await settled(0); + expect(recorded).toEqual([]); + expect(went).toHaveLength(1); + }); + + // A 200 is a success the operation never gives (it answers 204): not recorded, and said so. + for (const answer of [200, 404, 401, 429, 500, "network"] as const) + test(`the report answered ${answer}: the window goes on, the refusal is logged without the id, no retry`, async () => { + recordAnswer = answer; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const { page, went } = await newPage(fixture.with_id); + expect(await page.finishWindowSignIn()).toEqual({ signedIn: true }); + await settled(); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(recorded).toHaveLength(1); + expect(went).toHaveLength(1); + const logged = JSON.stringify(warn.mock.calls); + expect(logged).not.toContain(fixture.installation_id); + if (answer !== "network") expect(logged).toContain(String(answer)); + } finally { + warn.mockRestore(); + } + }); +}); + +test("the report answered 401 asking for the hosted sign-in to be renewed: no renewal, nothing kept to send again", async () => { + recordAnswer = "renewal"; + const navigated: string[] = []; + const opened: string[] = []; + const { navigate, openInBrowser } = renewalDeps; + renewalDeps.navigate = (address) => { + navigated.push(address); + }; + renewalDeps.openInBrowser = async (address) => { + opened.push(address); + return true; + }; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + window.sessionStorage.clear(); + const { page, went } = await newPage(fixture.with_id); + expect(await page.finishWindowSignIn()).toEqual({ signedIn: true }); + await settled(); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(recorded).toHaveLength(1); + expect(went).toHaveLength(1); + expect(navigated).toEqual([]); + expect(opened).toEqual([]); + expect(window.sessionStorage.length).toBe(0); + const logged = JSON.stringify(warn.mock.calls); + expect(logged).toContain("401"); + expect(logged).not.toContain(fixture.installation_id); + } finally { + warn.mockRestore(); + renewalDeps.navigate = navigate; + renewalDeps.openInBrowser = openInBrowser; + window.sessionStorage.clear(); + } +}); + +describe("a trade that fails records nothing", () => { + for (const [status, reason] of [ + [400, "invalid_code"], + // Refused for where it came from twice: the second 403 is the answer. + [403, "refused"], + [500, "refused"], + [NO_ANSWER, "unreachable"], + ] as const) + test(`${status}: ${reason}`, async () => { + tradeAnswers = [status]; + const { page, went } = await newPage(fixture.with_id); + expect(await page.finishWindowSignIn()).toEqual({ + signedIn: false, + reason, + }); + await settled(0); + expect(recorded).toEqual([]); + expect(went).toEqual([]); + }); + + test("no code in the fragment", async () => { + const { page } = await newPage( + `https://my.open.bot/desktop/signed-in#installation_id=${fixture.installation_id}`, + ); + expect(await page.finishWindowSignIn()).toEqual({ + signedIn: false, + reason: "invalid_code", + }); + await settled(0); + expect(trades).toEqual([]); + expect(recorded).toEqual([]); + }); +}); diff --git a/app/tests/desktop-window-sign-in.test.tsx b/app/tests/desktop-window-sign-in.test.tsx index d2666b05c5..1451648bc4 100644 --- a/app/tests/desktop-window-sign-in.test.tsx +++ b/app/tests/desktop-window-sign-in.test.tsx @@ -8,6 +8,7 @@ import { getGetDeploymentResponseMock } from "@/lib/api/generated/organization-s import { GetDeploymentResponse } from "@/lib/api/generated/organization-settings/organization-settings.zod"; import { GetServiceTermsResponse } from "@/lib/api/generated/people/people.zod"; import { personBody } from "./accounts-api"; +import handOff from "./fixtures/desktop-window-signed-in-address.json"; import { still } from "./page-still"; import { test } from "./renderer-crash"; @@ -51,6 +52,8 @@ const ORIGIN = "http://openbot.test"; const RELAY = "http://127.0.0.1:4999"; const ORGANIZATION = "/api/v2/organizations/default"; const ME = `${ORGANIZATION}/people/me`; +/** Where the page tells OpenBot which Desktop installation signed in (`recordDesktopInstallation`). */ +const INSTALLATIONS = "/api/v2/people/me/desktop-installations"; const SESSION_COOKIE = "openbot.session_token"; type Example = { value: Record }; @@ -80,11 +83,15 @@ type Sent = { body: unknown; /** The page's address when the request went out. */ pageUrl: string; + /** Whether it carried the window's session cookie. */ + withSession: boolean; }; /** One OpenBot, answering every request the page makes to its address. */ class FakeOpenBot { sent: Sent[] = []; + /** What the page wrote to its console. */ + console: string[] = []; /** OpenBot's requests and Desktop's commands (`desktop:`), in the order they came. */ order: string[] = []; signedIn = false; @@ -138,6 +145,7 @@ class FakeOpenBot { origin: headers.origin, body: request.postData() ? JSON.parse(request.postData() ?? "") : null, pageUrl: page.url(), + withSession, }); const json = (status: number, body: unknown, extra = {}) => route.fulfill({ @@ -231,6 +239,9 @@ class FakeOpenBot { }), openbotVersion: "v1.2.8", }); + // recordDesktopInstallation, as the server answers it with a session. + if (path === INSTALLATIONS && method === "POST") + return route.fulfill({ status: 204 }); if (path === `${ME}/terms`) return json(200, GetServiceTermsResponse.parse(NO_TERMS)); if (path === `${ME}/preferences`) @@ -458,6 +469,7 @@ async function inWindow( // The whole app is one script here, and a loaded machine takes a while to run it. page.setDefaultTimeout(90_000); page.on("pageerror", (error) => console.error(error)); + page.on("console", (message) => openbot.console.push(message.text())); await page.route(`${origin}/**`, (route) => openbot.handle(route, page)); // Routed after OpenBot, so it answers first: what stands between the window and OpenBot. await options.between?.(page); @@ -569,6 +581,48 @@ describe.skipIf(!asked)( // Replaced, never pushed: back doesn't return to the page with the code. expect(await historyAdded(page)).toBe(0); expect(named(calls, "window_sign_in_failed")).toEqual([]); + // No installation id in this hand-off, so the page tells OpenBot of none. + expect(openbot.asked(INSTALLATIONS)).toEqual([]); + }, + ); + }, 240_000); + + test(`with Desktop's installation id, tells OpenBot which installation signed in, once, after the trade, in ${engine}`, async () => { + await inWindow( + { + engine, + path: `${fragment("/channel/c_1?message=m1")}&installation_id=${handOff.installation_id}`, + }, + async (page, openbot) => { + await conversation(page); + expect(landed(page)).toBe("/channel/c_1?message=m1"); + // Sent without waiting for its answer, so it may arrive just after the window lands. + for ( + let i = 0; + i < 50 && openbot.asked(INSTALLATIONS).length === 0; + i += 1 + ) + await page.waitForTimeout(100); + await page.waitForTimeout(300); + expect(openbot.asked(INSTALLATIONS)).toHaveLength(1); + const [recorded] = openbot.asked(INSTALLATIONS); + expect(recorded).toMatchObject({ + method: "POST", + origin: ORIGIN, + body: { installationId: handOff.installation_id }, + pageUrl: `${ORIGIN}/desktop/signed-in`, + // With the session the trade just set, and answered 204: nothing was logged as refused. + withSession: true, + }); + expect( + openbot.console.filter((line) => + line.includes("The Desktop installation"), + ), + ).toEqual([]); + // After the code was traded, never before it. + expect(openbot.order.indexOf(INSTALLATIONS)).toBeGreaterThan( + openbot.order.indexOf("/api/auth/window/session"), + ); }, ); }, 240_000); diff --git a/app/tests/fixtures/desktop-installation-request.json b/app/tests/fixtures/desktop-installation-request.json new file mode 100644 index 0000000000..b512edd3d6 --- /dev/null +++ b/app/tests/fixtures/desktop-installation-request.json @@ -0,0 +1,10 @@ +{ + "_about": "The request OpenBot Desktop's Move to Cloud sends to record its installation (move_to_cloud::record_desktop_installation), as a local server receives it. A Rust test (move_to_cloud/tests.rs) holds the sender's bytes to this file, and api/openapi-desktop-installations.test.ts holds this file to the spec. The Idempotency-Key is new per report; idempotency_key is one the sender made, kept for its shape.", + "method": "POST", + "path": "/api/v2/people/me/desktop-installations", + "content_type": "application/json", + "installation_id": "3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88", + "body": "{\"installationId\":\"3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88\"}", + "idempotency_key": "6f1d3b7a-2c4e-4a8f-9b0d-5e7c1a3f9d24", + "absent_headers": ["openbot-organization", "origin"] +} diff --git a/app/tests/fixtures/desktop-window-signed-in-address.json b/app/tests/fixtures/desktop-window-signed-in-address.json new file mode 100644 index 0000000000..3e9e129b5e --- /dev/null +++ b/app/tests/fixtures/desktop-window-signed-in-address.json @@ -0,0 +1,10 @@ +{ + "_about": "OpenBot Desktop sends its window to OpenBot's /desktop/signed-in page with the sign-in in the address's fragment, built by signed_in_address in desktop/src-tauri/src/connected/window.rs. Given origin, code, code_verifier and next (a path on that origin), the fragment is code, code_verifier and next, form-encoded as URLSearchParams reads them. For OpenBot Cloud only, and only while the person shares usage data, installation_id (a lower-case random version 4 UUID) is added last. with_id and without_id are the exact addresses the function builds from these inputs, with and without installation_id. The Desktop test and the page's test both read this file; regenerate it from the function, never by hand.", + "origin": "https://my.open.bot", + "code": "c0de+/=x", + "code_verifier": "v3r1f13r-_.~", + "next": "/c/a b?x=1&y=2", + "installation_id": "3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88", + "with_id": "https://my.open.bot/desktop/signed-in#code=c0de%2B%2F%3Dx&code_verifier=v3r1f13r-_.%7E&next=%2Fc%2Fa+b%3Fx%3D1%26y%3D2&installation_id=3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88", + "without_id": "https://my.open.bot/desktop/signed-in#code=c0de%2B%2F%3Dx&code_verifier=v3r1f13r-_.%7E&next=%2Fc%2Fa+b%3Fx%3D1%26y%3D2" +} diff --git a/app/tests/no-fixed-settle-waits.test.ts b/app/tests/no-fixed-settle-waits.test.ts index 370a821d3a..005dcbf268 100644 --- a/app/tests/no-fixed-settle-waits.test.ts +++ b/app/tests/no-fixed-settle-waits.test.ts @@ -59,6 +59,10 @@ const ALLOWED: Record = { most: 1, why: "lets three seconds of the access read's clock go by", }, + "desktop-window-sign-in.test.tsx": { + most: 2, + why: "polls the fake OpenBot for the installation report the page sends without waiting, then proves no second one follows", + }, "first-message-thinking.test.tsx": { most: 2, why: "photographs what a first message shows a set time after Send, and after a run starts with nothing said yet", diff --git a/desktop/TELEMETRY.md b/desktop/TELEMETRY.md index 98f849f27f..87f1d55ebf 100644 --- a/desktop/TELEMETRY.md +++ b/desktop/TELEMETRY.md @@ -22,11 +22,26 @@ The bundled CLI is pinned to `copilotkit@c18d337` (`desktop/intelligence-cli.jso The added state fields are not readable by older desktop releases because their parsers reject unknown fields. After a downgrade, those releases disable native telemetry until a compatible version reads the state again. Do not treat a downgrade as proof that telemetry is still active. +## OpenBot Cloud sign-in link + +OpenBot Cloud's events carry Cloud's own `deployment_id`, so on their own they can't be joined to what this installation did before. The installation id is the random UUID this installation's usage data is sent under, as `deployment_id`. After a sign-in to OpenBot Cloud, OpenBot Cloud is told the installation id once (`recordDesktopInstallation`, `POST /api/v2/people/me/desktop-installations`, body `{"installationId": ""}` and nothing else), so the two can be joined. + +- **Only OpenBot Cloud.** Sharing usage data is consent to CopilotKit, not to a company's own server. Only OpenBot Cloud's own address is told the installation id: `api.open.bot` or `my.open.bot`, over https, on the default port. A company's OpenBot never is. Nor is OpenBot Cloud's staging copy (`api-staging.open.bot`, `my-staging.open.bot`), or any other address. +- **Only while sharing usage data.** With Settings' switch or the Finishing-setup checkbox off, or `COPILOTKIT_TELEMETRY_DISABLED` / `DO_NOT_TRACK` set, there is no installation id to give. Turning usage data off stops the next send. It does not undo a link already made. +- **Two ways, one operation.** + - The window's sign-in (OpenBot Cloud's button, Sign in again, choosing again from Settings). The desktop adds the installation id to the address it hands the window, beside the sign-in's code: `/desktop/signed-in#…&installation_id=`. The fragment never reaches a server or a log. OpenBot Cloud's page reads it, takes it off the address, and sends only the installation id, with its new session, once it has traded the code. A page from before this change ignores the key, and the sign-in works as before. The desktop's log says `[connect] the window signs in at , with this installation's id` or `…, without the installation's id`. Turning usage data off while the page trades the code does not stop that one send. + - Move to Cloud. Right after its own sign-in, the desktop sends it itself, with that sign-in, on its own thread, so the move never waits. Just before the one request, and again once the sign-in's token is in hand, it checks four things: usage data is still on under the same installation id, the sign-in has not ended, no sign-out has begun, and no more than 20 seconds have passed. Otherwise nothing is sent. It goes with the sign-in, not with the move: a move cancelled or failed after its sign-in has still sent it. A report that was skipped is never sent later. +- **When nothing is sent.** A launch that resumes a saved sign-in. A sign-in to any other OpenBot. A sign-in through the desktop app, not the window (an OpenBot whose sign-in metadata names no window sign-in). A Move to Cloud that reuses a sign-in made earlier in the same launch. +- **Failures.** Each send has its own Idempotency-Key and is never retried. Only a `204` counts. Anything else is logged by its status alone, a `404` from a Cloud without the operation included: `[move] the installation wasn't recorded: `, or `no answer`, `no credential`, `too late` or `not wanted now` when nothing was answered or sent. The page logs the status to its console. Neither logs the installation id or what Cloud wrote back, and the person sees no change. A `401` asking for the hosted sign-in to be renewed starts no renewal and is not sent again. Desktop follows no redirect. A `204` is logged as `[move] the installation report was accepted`: accepted, which is not the same as an event sent (below). +- **What OpenBot Cloud does with it.** Where its product telemetry is on, it sends `oss.runtime.openbot.desktop_installation_linked` ([product telemetry](../docs/TELEMETRY.md#openbot-desktop-signed-in-to-openbot-cloud)). Where it is off, a valid report is accepted and dropped. +- **What an analyst sees.** This installation's events by `deployment_id` equal to the link's `installation_id`, and the person's OpenBot Cloud events by the link's `deployment_id` and `user_id`. It is a join, not a merge: no PostHog person is aliased. Where Account attribution (above) has run, the installation id is already tied to the CopilotKit PostHog person, so the link also joins OpenBot Cloud's pseudonym to that account. A new installation id (usage data off and on again, or another CopilotKit account) starts unlinked, and earlier links stay. Query G in [telemetry-queries.sql](../docs/telemetry-queries.sql) does the join. +- **Not covered here: a sign-out of OpenBot Cloud.** It doesn't make a new installation id. Only the CopilotKit account above, or usage data off and on again, does. So a second person who signs in to OpenBot Cloud on the same computer links the same installation. That is a follow-up. + ## Desktop-only boundary The account bridge runs only in the native desktop shell. The shell starts the personal edition; it does not identify Enterprise application users. Its server handoff uses a separate `.openbot-desktop-telemetry.yml` override, selected only when the native launch supplies desktop telemetry context (or opt-out) and the installation is personal. The shared Compose file and Enterprise deployment charts are unchanged. Ordinary Compose startup does not load the override. Desktop defaults precede user Compose overrides, preserving a server-level opt-out. A separate final suppression override makes native opt-out win even over an override that enables telemetry. If the optional Compose settings probe is unsupported or fails, or a telemetry override cannot be written, startup logs it and continues without that override, opted out or not: telemetry never keeps OpenBot from starting. The desktop identity reaches the server only through that override, so a server started without it has none. -The override forwards only the installation UUID, sampling/suppression settings, sink address and closed desktop version/platform metadata. It contains variable names, not account data or credentials. No email, name, prompt, response, recording, filename or user URL is added. The configured sink address is transport configuration, not captured browsing content. The CLI protocol rejects extra fields. Opaque account linking remains pseudonymous identification; it is not anonymous collection. This change adds no content collection or new product event names. +The override forwards only the installation UUID, sampling/suppression settings, sink address and closed desktop version/platform metadata. It contains variable names, not account data or credentials. No email, name, prompt, response, recording, filename or user URL is added. The configured sink address is transport configuration, not captured browsing content. The CLI protocol rejects extra fields. Opaque account linking remains pseudonymous identification; it is not anonymous collection. The override adds no content collection or new product event names. ## Event allowlist diff --git a/desktop/src-tauri/src/connected/cloud.rs b/desktop/src-tauri/src/connected/cloud.rs index 7ae965ad5e..7ecd3bbc1f 100644 --- a/desktop/src-tauri/src/connected/cloud.rs +++ b/desktop/src-tauri/src/connected/cloud.rs @@ -50,6 +50,17 @@ pub fn of(address: &str) -> Option { .find(|cloud| host == cloud.api || host == cloud.web) } +/** +Whether a sign-in at `address` may be told this installation's usage-data id +(`recordDesktopInstallation`): only when it is OpenBot Cloud itself, by either of its names, over +https on the usual port (`of`), and never its staging copy. Settings' Share usage data is consent +to CopilotKit, which runs OpenBot Cloud, not to a company's own OpenBot, nor to the copy where +CopilotKit's own people try each merge, so neither is ever handed the id. +*/ +pub fn links_installation(address: &str) -> bool { + of(address).is_some_and(|cloud| !cloud.staging) +} + /// The name this app connects to for `host`: an OpenBot Cloud's name for programs when `host` is /// its name for browsers, and `host` itself otherwise. pub fn for_programs(host: &str) -> &str { @@ -91,6 +102,32 @@ mod tests { } } + #[test] + fn only_openbot_clouds_own_address_is_told_the_installation() { + for address in [ + "https://api.open.bot", + "https://my.open.bot", + "https://API.OPEN.BOT", + "https://My.Open.Bot/", + ] { + assert!(links_installation(address), "{address}"); + } + for address in [ + "https://api-staging.open.bot", + "https://my-staging.open.bot", + "http://api.open.bot", + "https://api.open.bot:8443", + "https://api.open.bot.example.com", + "https://xapi.open.bot", + "https://openbot.example.com", + "http://127.0.0.1:3001", + "not an address", + "", + ] { + assert!(!links_installation(address), "{address}"); + } + } + #[test] fn a_browser_name_becomes_the_name_for_programs_and_any_other_stays() { assert_eq!(for_programs("my.open.bot"), "api.open.bot"); diff --git a/desktop/src-tauri/src/connected/sign_in.rs b/desktop/src-tauri/src/connected/sign_in.rs index 6c3a15d8c4..79c46cd1b1 100644 --- a/desktop/src-tauri/src/connected/sign_in.rs +++ b/desktop/src-tauri/src/connected/sign_in.rs @@ -466,6 +466,11 @@ impl Session { &self.address } + /// Whether this sign-in has ended: signed out, or refused for good when refreshed. + pub fn has_ended(&self) -> bool { + self.live.lock().unwrap().ended + } + /// The address's host, as the sentences name it. pub fn host(&self) -> &str { &self.host @@ -1832,10 +1837,13 @@ mod tests { let store = in_memory(); let session = openbot.sign_in(store.clone()); assert!(store.get(&openbot.address()).unwrap().is_some()); + assert!(!session.has_ended()); session.sign_out(no_browser).unwrap(); assert_eq!(openbot.revoke_requests().len(), 2); assert_eq!(store.get(&openbot.address()).unwrap(), None); assert!(session.access().is_err()); + // Ended, so nothing more is sent with it. + assert!(session.has_ended()); } /// The fake checks S256 as the real one does: a code presented with another verifier is @@ -2099,8 +2107,10 @@ mod tests { let session = openbot.sign_in(store.clone()); let access = session.access().unwrap(); openbot.end_sessions(); + assert!(!session.has_ended()); let problem = session.after_refused(&access).expect_err("ended"); assert_eq!(kind_of(&problem), Some(Kind::SessionEnded)); + assert!(session.has_ended(), "refused for good when refreshed"); assert_eq!( problem.said, format!( diff --git a/desktop/src-tauri/src/connected/window.rs b/desktop/src-tauri/src/connected/window.rs index d07d0abb93..beb683f3d9 100644 --- a/desktop/src-tauri/src/connected/window.rs +++ b/desktop/src-tauri/src/connected/window.rs @@ -200,15 +200,34 @@ pub fn valid_next(next: Option<&str>) -> Result { } } -/// Where the window goes to trade `code` for its session cookie, and then on to `next` (a path, -/// `valid_next`). Everything secret is in the fragment, which the browser never sends anywhere. -pub fn signed_in_address(window: &WindowSignIn, code: &Code, next: &str) -> String { +/** +Where the window goes to trade `code` for its session cookie, and then on to `next` (a path, +`valid_next`). Everything secret is in the fragment, which the browser never sends anywhere. + +`installation_id`, when given, is this installation's usage-data id, last in the fragment: the page +tells OpenBot Cloud with its own session once it has traded the code (`recordDesktopInstallation`). +The caller gives it only for OpenBot Cloud itself and only while the person shares usage data +(`cloud::links_installation`). The page's test reads the same fixed addresses this one checks +(`app/tests/fixtures/desktop-window-signed-in-address.json`). +*/ +pub fn signed_in_address( + window: &WindowSignIn, + code: &Code, + next: &str, + installation_id: Option<&str>, +) -> String { // Encoded as a form is: the page reads it with `URLSearchParams`. let mut form = reqwest::Url::parse("form:/").expect("a fixed address"); - form.query_pairs_mut() - .append_pair("code", &code.code) - .append_pair("code_verifier", &code.verifier) - .append_pair("next", next); + { + let mut pairs = form.query_pairs_mut(); + pairs + .append_pair("code", &code.code) + .append_pair("code_verifier", &code.verifier) + .append_pair("next", next); + if let Some(id) = installation_id { + pairs.append_pair("installation_id", id); + } + } let fragment = form.query().unwrap_or_default(); format!("{}{SIGNED_IN_PATH}#{fragment}", window.origin) } @@ -478,7 +497,7 @@ mod tests { code: "c0de+/=".into(), verifier: "v3r1f13r".into(), }; - let address = signed_in_address(&window, &code, "/c/a b?x=1&y=2"); + let address = signed_in_address(&window, &code, "/c/a b?x=1&y=2", None); let parsed = reqwest::Url::parse(&address).unwrap(); assert_eq!(parsed.origin().ascii_serialization(), window.origin); assert_eq!(parsed.path(), SIGNED_IN_PATH); @@ -492,9 +511,63 @@ mod tests { assert_eq!(fragment["code"], "c0de+/="); assert_eq!(fragment["code_verifier"], "v3r1f13r"); assert_eq!(fragment["next"], "/c/a b?x=1&y=2"); + assert!(!fragment.contains_key("installation_id")); assert_eq!(format!("{code:?}"), "Code { .. }"); } + /** + The addresses the window is sent to, with this installation's id and without it, exactly as + OpenBot's page is tested to read them: the page's test reads the same file. The id is the + fragment's last pair, and nothing before it changes. + */ + #[test] + fn the_signed_in_address_is_the_one_the_page_is_tested_to_read() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../../app/tests/fixtures/desktop-window-signed-in-address.json" + )) + .unwrap(); + let text = |key: &str| fixture[key].as_str().unwrap().to_owned(); + let mut keys: Vec<&String> = fixture.as_object().unwrap().keys().collect(); + keys.sort(); + assert_eq!( + keys, + [ + "_about", + "code", + "code_verifier", + "installation_id", + "next", + "origin", + "with_id", + "without_id" + ], + "only the keys the page's test reads" + ); + let window = WindowSignIn { + sign_in_endpoint: format!("{}/api/auth/window/sign-in", text("origin")), + origin: text("origin"), + }; + let code = Code { + code: text("code"), + verifier: text("code_verifier"), + }; + let id = text("installation_id"); + assert_eq!(uuid::Uuid::parse_str(&id).unwrap().get_version_num(), 4); + assert_eq!(id, id.to_ascii_lowercase()); + let next = text("next"); + assert!(next.contains(' ') && next.contains('?') && next.contains('&')); + + let with_id = signed_in_address(&window, &code, &next, Some(&id)); + let without_id = signed_in_address(&window, &code, &next, None); + assert_eq!(with_id, text("with_id")); + assert_eq!(without_id, text("without_id")); + assert_eq!( + with_id, + format!("{without_id}&installation_id={id}"), + "the id is added last and nothing else changes" + ); + } + use super::super::fake_openbot::{ FakeOpenBot, Shape, PERSON_EMAIL, SESSION_COOKIE, WINDOW_SESSION_PATH, }; diff --git a/desktop/src-tauri/src/desktop_connected.rs b/desktop/src-tauri/src/desktop_connected.rs index ff462b166c..3d6d89526b 100644 --- a/desktop/src-tauri/src/desktop_connected.rs +++ b/desktop/src-tauri/src/desktop_connected.rs @@ -74,6 +74,10 @@ pub struct State { /// The window's cookies, in a test: the mock webview keeps none. #[cfg(test)] pub(crate) jar_for_test: Mutex>, + /// How many sign-outs this run has begun (`sign_out_with`, "Use this computer" and Change + /// included), counted as each one starts: a sign-in's report of this installation + /// (`desktop_move`) is not sent once another sign-out has begun since that sign-in. + sign_outs: std::sync::atomic::AtomicU64, } /// The window's cookies in a test, by name and value (`use_jar_for_test`). @@ -1309,15 +1313,40 @@ fn connect_window_now( } } keep(app, &choice::window_signed_in_at(address, &window.origin))?; - log::info!("[connect] the window signs in at {host}"); + let installation = window_installation_id(app, address, &window); + if installation.is_some() { + log::info!("[connect] the window signs in at {host}, with this installation's id"); + } else { + log::info!("[connect] the window signs in at {host}, without the installation's id"); + } show_window_at( app, address, &window, - &window::signed_in_address(&window, &code, next), + &window::signed_in_address(&window, &code, next, installation.as_deref()), ) } +/** +This installation's usage-data id for the window's sign-in page to tell OpenBot Cloud with its own +session (`recordDesktopInstallation`), or None. Only when both the address signed in to and the +origin the window's page runs on are OpenBot Cloud itself (`cloud::links_installation`: never its +staging copy, never a company's OpenBot), since the page sends it to its own origin; and only while +the person shares usage data (`desktop_telemetry::installation_id`). A launch that resumes a saved +sign-in never comes here, so never hands it over. +*/ +fn window_installation_id( + app: &tauri::AppHandle, + address: &str, + window: &window::WindowSignIn, +) -> Option { + use openbot_desktop_lib::connected::cloud::links_installation; + if !(links_installation(address) && links_installation(&window.origin)) { + return None; + } + crate::desktop_telemetry::installation_id(app) +} + /// A sign-in waiting for the browser, kept for Cancel in place of any earlier one, which is /// cancelled. fn begin_attempt(app: &tauri::AppHandle) -> Arc { @@ -1747,6 +1776,14 @@ fn forget_origin(app: &tauri::AppHandle, origin: &str) { .retain(|trusted| trusted != origin); } +/// How many sign-outs this run has begun (`sign_out_with`). +pub(crate) fn sign_outs(app: &tauri::AppHandle) -> u64 { + state(app) + .connected + .sign_outs + .load(std::sync::atomic::Ordering::SeqCst) +} + /// Sign out of the OpenBot on record: revoked there as far as it answers, forgotten here, and the /// relay stopped. The address stays. The next sign-in names no organisation: it works in the one /// the person picks as they sign in (`choice::signed_in_at`). @@ -1769,6 +1806,11 @@ pub fn sign_out_after_page(app: &tauri::AppHandle) { /// Sign out, asking OpenBot to end the window's session first when `at_openbot`. fn sign_out_with(app: &tauri::AppHandle, at_openbot: bool) { + // Counted before anything is revoked: from here, nothing more is told about an earlier sign-in. + state(app) + .connected + .sign_outs + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); if let Some(attempt) = state(app).connected.attempt.lock().unwrap().take() { attempt.cancel(); } @@ -2011,3 +2053,94 @@ pub(crate) fn showing_for_test(app: &tauri::AppHandle, ori *state(app).connected.relay_for_test.lock().unwrap() = Some(origin.to_owned()); crate::trust_owned_app(app, origin); } + +#[cfg(test)] +mod installation_tests { + use super::*; + + fn window_at(origin: &str) -> WindowSignIn { + WindowSignIn { + sign_in_endpoint: format!("{origin}/api/auth/window/sign-in"), + origin: origin.to_owned(), + } + } + + /** + The window's sign-in page is handed this installation's id only when the address signed in to + and the window's origin, where the page sends it, are both OpenBot Cloud itself, and only while + the person shares usage data. Never OpenBot Cloud's staging copy, never a company's OpenBot. + */ + #[test] + fn the_window_hands_the_id_only_to_openbot_cloud_while_sharing() { + if crate::test_support::isolated_process( + "desktop_connected::installation_tests::the_window_hands_the_id_only_to_openbot_cloud_while_sharing", + ) { + return; + } + std::env::remove_var("COPILOTKIT_TELEMETRY_DISABLED"); + std::env::remove_var("DO_NOT_TRACK"); + openbot_desktop_lib::usage_data::set_off(false); + let app = tauri::test::mock_builder() + .manage(crate::desktop_telemetry::DesktopTelemetry::for_tests( + crate::test_support::temp_root("window-installation-id"), + true, + )) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + let app = app.handle(); + let id = crate::desktop_telemetry::installation_id(app).unwrap(); + let given = + |address: &str, origin: &str| window_installation_id(app, address, &window_at(origin)); + + assert_eq!( + given("https://api.open.bot", "https://my.open.bot"), + Some(id.clone()) + ); + for (address, origin) in [ + ( + "https://api-staging.open.bot", + "https://my-staging.open.bot", + ), + ( + "https://openbot.example.com", + "https://my.openbot.example.com", + ), + ("https://openbot.example.com", "https://openbot.example.com"), + // Either side not OpenBot Cloud's own is enough to hand nothing over. + ("https://api.open.bot", "https://my-staging.open.bot"), + ("https://api-staging.open.bot", "https://my.open.bot"), + ("https://api.open.bot", "https://my.open.bot:8443"), + ("http://127.0.0.1:3000", "http://127.0.0.1:3001"), + ] { + assert_eq!(given(address, origin), None, "{address} {origin}"); + } + + // Usage data off: nothing, even for OpenBot Cloud. + openbot_desktop_lib::usage_data::set_off(true); + assert_eq!(given("https://api.open.bot", "https://my.open.bot"), None); + openbot_desktop_lib::usage_data::set_off(false); + std::env::set_var("DO_NOT_TRACK", "1"); + assert_eq!(given("https://api.open.bot", "https://my.open.bot"), None); + std::env::remove_var("DO_NOT_TRACK"); + assert_eq!( + given("https://api.open.bot", "https://my.open.bot"), + Some(id) + ); + } + + /// The window's address is built with what the gate gave, and every sign-in of the window comes + /// through `connect_window_now`: Connect's (the first screen, Sign in again, Settings' Change) + /// and the window's own sign-in screen. None resumes a saved sign-in. + #[test] + fn every_window_sign_in_is_built_with_the_gates_answer() { + let source = include_str!("desktop_connected.rs"); + let code = &source[..source.find("mod installation_tests").unwrap()]; + assert_eq!(code.matches("window::signed_in_address(").count(), 1); + assert!(code.contains( + "&window::signed_in_address(&window, &code, next, installation.as_deref())," + )); + assert!(code.contains("let installation = window_installation_id(app, address, &window);")); + assert_eq!(code.matches("connect_window_now(app, ").count(), 2); + assert_eq!(code.matches("window_installation_id(app, ").count(), 1); + } +} diff --git a/desktop/src-tauri/src/desktop_move.rs b/desktop/src-tauri/src/desktop_move.rs index 5996f308a0..66e03ef6c0 100644 --- a/desktop/src-tauri/src/desktop_move.rs +++ b/desktop/src-tauri/src/desktop_move.rs @@ -583,12 +583,15 @@ fn signed_in( let session = match kept { Some(session) => session, None => { + // Counted before the sign-in starts: a sign-out begun from here on stops its report. + let sign_outs_then = crate::desktop_connected::sign_outs(app); let session = crate::desktop_connected::sign_in_for_move(app, address, opened) .map_err(|mut problem| { problem.kind = Some("sign-in"); problem })?; *state(app).signed_in.lock().unwrap() = Some(session.clone()); + report_installation(app, &session, sign_outs_then); session } }; @@ -596,6 +599,95 @@ fn signed_in( Ok(session) } +/// A fresh sign-in's report of this installation to OpenBot Cloud, and what it is checked against +/// just before it goes (`installation_wanted`). +pub(crate) struct InstallationReport { + session: std::sync::Arc, + /// The installation's usage-data id as it was at the sign-in. + installation_id: String, + /// Sign-outs begun before the sign-in started (`desktop_connected::sign_outs`). + sign_outs_then: u64, + /// The sign-in and `RECORD_INSTALLATION_WITHIN`: nothing goes out after it. + until: std::time::Instant, +} + +/** +After the move's own fresh sign-in, tell OpenBot Cloud which installation this is +(`recordDesktopInstallation`), so usage data can join what the installation did before the sign-in +with what the person does in OpenBot Cloud. On a thread of its own: the move never waits on it. A +sign-in kept from earlier in this run has told it already, or resumed one, so only a fresh one comes +here. Nothing at all when usage data is not shared now. +*/ +fn report_installation( + app: &tauri::AppHandle, + session: &std::sync::Arc, + sign_outs_then: u64, +) { + let until = std::time::Instant::now() + moving::RECORD_INSTALLATION_WITHIN; + let Some(installation_id) = crate::desktop_telemetry::installation_id(app) else { + return; + }; + let report = InstallationReport { + session: session.clone(), + installation_id, + sign_outs_then, + until, + }; + let app = app.clone(); + let started = std::thread::Builder::new() + .name("record-installation".into()) + .spawn(move || { + let base = report.session.address().to_owned(); + send_installation(&app, &report, &base); + }); + if let Err(error) = started { + log::warn!("[move] the installation wasn't recorded: {error}"); + } +} + +/** +Whether the report is still wanted, just before it goes: the sign-in is to OpenBot Cloud itself +(`cloud::links_installation`, never its staging copy or a company's OpenBot); the person still +shares usage data, and under the same id; the sign-in has not ended; no sign-out has begun since +it started; and its time (`until`) has not passed. +*/ +pub(crate) fn installation_wanted( + app: &tauri::AppHandle, + report: &InstallationReport, +) -> bool { + openbot_desktop_lib::connected::cloud::links_installation(report.session.address()) + && crate::desktop_telemetry::installation_id(app).as_deref() + == Some(report.installation_id.as_str()) + && !report.session.has_ended() + && crate::desktop_connected::sign_outs(app) == report.sign_outs_then + && std::time::Instant::now() < report.until +} + +/// The report sent once to `base` (the sign-in's own address) when it is still wanted, and its +/// outcome logged by status alone. None when it was not wanted and nothing was sent. +pub(crate) fn send_installation( + app: &tauri::AppHandle, + report: &InstallationReport, + base: &str, +) -> Option> { + if !installation_wanted(app, report) { + log::info!("[move] the installation wasn't recorded: not wanted now"); + return None; + } + let sent = moving::record_desktop_installation( + base, + &moving::SignedIn(report.session.clone()), + &report.installation_id, + report.until, + &|| installation_wanted(app, report), + ); + match &sent { + Ok(()) => log::info!("[move] the installation report was accepted"), + Err(refused) => log::info!("[move] the installation wasn't recorded: {refused}"), + } + Some(sent) +} + fn move_now( app: &tauri::AppHandle, address: &str, @@ -980,3 +1072,220 @@ fn forget_root(app: &tauri::AppHandle, root: &Path) { } crate::refresh_menus(app); } + +#[cfg(test)] +mod installation_report_tests { + use super::*; + use openbot_desktop_lib::connected::{address, credentials, sign_in}; + use std::io::{BufRead, BufReader, Read, Write}; + use std::sync::{Arc, Mutex}; + + /// A stand-in OpenBot on 127.0.0.1: any refresh is handed a token, a revocation is taken, and + /// the installation's report is answered 204. Keeps each request's path. + fn openbot() -> (String, Arc>>) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + let paths: Arc>> = Arc::default(); + let kept = paths.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + if reader.read_line(&mut line).is_err() { + continue; + } + let mut length = 0; + loop { + let mut header = String::new(); + if reader.read_line(&mut header).is_err() || header.trim().is_empty() { + break; + } + if let Some((name, value)) = header.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse().unwrap_or(0); + } + } + } + let mut body = vec![0; length]; + let _ = reader.read_exact(&mut body); + let path = line + .split_whitespace() + .nth(1) + .unwrap_or_default() + .to_owned(); + let (status, answer) = if path.ends_with("/token") { + ( + "200 OK", + r#"{"access_token":"a","refresh_token":"r","expires_in":3600}"#, + ) + } else if path.ends_with("/revoke") { + ("200 OK", "{}") + } else { + ("204 No Content", "") + }; + kept.lock().unwrap().push(path); + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", + answer.len() + ); + } + }); + (address, paths) + } + + /// A sign-in at `address` whose tokens come from the stand-in at `local`: the address the gate + /// reads, while the report itself goes to the stand-in (`send_installation`'s `base`). + fn signed_in_at( + address: &str, + local: &str, + store: &credentials::Store, + ) -> Arc { + let metadata = address::Metadata { + authorization_endpoint: format!("{local}/authorize"), + token_endpoint: format!("{local}/token"), + revocation_endpoint: Some(format!("{local}/revoke")), + end_session_endpoint: None, + scopes: vec![], + window: None, + }; + store.set(address, "saved").unwrap(); + Arc::new(sign_in::resume(address, &metadata, store.clone()).unwrap()) + } + + fn reports(paths: &Arc>>) -> usize { + paths + .lock() + .unwrap() + .iter() + .filter(|path| path.as_str() == moving::DESKTOP_INSTALLATIONS_PATH) + .count() + } + + /** + The move's report of the installation goes only while every check holds just before it goes: a + sign-in to OpenBot Cloud itself, usage data still shared under the same id, the sign-in not + ended, no sign-out begun since it started, and within its 20 seconds (a deadline handed in, so + the test does not wait). Each failing check sends nothing at all; with all of them holding, one + report goes. + */ + #[test] + fn the_moves_report_goes_only_while_every_check_holds() { + if crate::test_support::isolated_process( + "desktop_move::installation_report_tests::the_moves_report_goes_only_while_every_check_holds", + ) { + return; + } + std::env::remove_var("COPILOTKIT_TELEMETRY_DISABLED"); + std::env::remove_var("DO_NOT_TRACK"); + openbot_desktop_lib::usage_data::set_off(false); + let app = tauri::test::mock_builder() + .manage(Shell::default()) + .manage(crate::desktop_telemetry::DesktopTelemetry::for_tests( + crate::test_support::temp_root("move-report-telemetry"), + true, + )) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + let app = app.handle(); + let store = credentials::Store::of(keyring_core::mock::Store::new().unwrap()); + crate::desktop_connected::use_for_test( + app, + crate::test_support::temp_root("move-report-config"), + store.clone(), + ); + let (local, paths) = openbot(); + let id = crate::desktop_telemetry::installation_id(app).unwrap(); + let report = |address: &str| InstallationReport { + session: signed_in_at(address, &local, &store), + installation_id: id.clone(), + sign_outs_then: crate::desktop_connected::sign_outs(app), + until: std::time::Instant::now() + moving::RECORD_INSTALLATION_WITHIN, + }; + let send = |report: &InstallationReport| send_installation(app, report, &local); + + // Every check holds: one report, recorded. + let cloud = report("https://api.open.bot"); + assert_eq!(send(&cloud), Some(Ok(()))); + assert_eq!(reports(&paths), 1); + + // OpenBot Cloud's staging copy, and a company's OpenBot: nothing. + for elsewhere in [ + "https://api-staging.open.bot", + "https://openbot.example.com", + ] { + assert_eq!(send(&report(elsewhere)), None, "{elsewhere}"); + } + assert_eq!(reports(&paths), 1); + + // Usage data turned off in Settings, or by either environment opt-out: nothing. + openbot_desktop_lib::usage_data::set_off(true); + assert_eq!(send(&cloud), None); + openbot_desktop_lib::usage_data::set_off(false); + for variable in ["COPILOTKIT_TELEMETRY_DISABLED", "DO_NOT_TRACK"] { + std::env::set_var(variable, "1"); + assert_eq!(send(&cloud), None, "{variable}"); + std::env::remove_var(variable); + } + assert_eq!(reports(&paths), 1); + + // Another id than the one read at the sign-in (off and on again makes a new one): nothing. + let other_id = InstallationReport { + installation_id: "0b6e2d4f-1c88-4a35-8e1b-3f2c9a648c7d".into(), + ..report("https://api.open.bot") + }; + assert_eq!(send(&other_id), None); + + // Past its 20 seconds: nothing. + let late = InstallationReport { + until: std::time::Instant::now() - std::time::Duration::from_millis(1), + ..report("https://api.open.bot") + }; + assert_eq!(send(&late), None); + assert_eq!(reports(&paths), 1); + + // A sign-out begun since the sign-in started: nothing, and each one is counted. + let before = report("https://api.open.bot"); + let counted = crate::desktop_connected::sign_outs(app); + crate::desktop_connected::sign_out_now(app); + assert_eq!(crate::desktop_connected::sign_outs(app), counted + 1); + assert_eq!(send(&before), None); + assert_eq!(reports(&paths), 1); + + // The sign-in itself ended: nothing. + let ended = report("https://api.open.bot"); + ended.session.sign_out(|_| Ok(())).unwrap(); + assert!(ended.session.has_ended()); + assert_eq!(send(&ended), None); + assert_eq!(reports(&paths), 1); + + // And with every check holding again, it goes again: the checks above are what stopped it. + assert_eq!(send(&report("https://my.open.bot")), Some(Ok(()))); + assert_eq!(reports(&paths), 2); + } + + /// Only the move's own fresh sign-in reports the installation: a sign-in kept from earlier in + /// the run told it already, or was resumed, and never sends. + #[test] + fn only_the_moves_fresh_sign_in_reports_the_installation() { + let source = include_str!("desktop_move.rs"); + let code = &source[..source.find("mod installation_report_tests").unwrap()]; + assert_eq!(code.matches("report_installation(app, ").count(), 1); + let signed_in = &code[code.find("fn signed_in<").unwrap()..]; + let signed_in = &signed_in[..signed_in.find("\n}\n").unwrap()]; + let fresh = signed_in.find("None => {").unwrap(); + let sign_in = signed_in + .find("sign_in_for_move(app, address, opened)") + .unwrap(); + let reported = signed_in + .find("report_installation(app, &session, sign_outs_then);") + .unwrap(); + assert!(fresh < sign_in && sign_in < reported); + let counted = signed_in + .find("let sign_outs_then = crate::desktop_connected::sign_outs(app);") + .unwrap(); + assert!(fresh < counted && counted < sign_in); + assert!(!signed_in[..fresh].contains("report_installation")); + } +} diff --git a/desktop/src-tauri/src/desktop_telemetry.rs b/desktop/src-tauri/src/desktop_telemetry.rs index 949294547a..8b977e36f0 100644 --- a/desktop/src-tauri/src/desktop_telemetry.rs +++ b/desktop/src-tauri/src/desktop_telemetry.rs @@ -308,6 +308,41 @@ pub fn usage_data_now() -> UsageData { } } +/** +This installation's usage-data id, as OpenBot Cloud is told it (`recordDesktopInstallation`), while +the person shares usage data (`usage_data_now`: Settings' switch, and no environment opt-out); None +otherwise. It is the id the desktop's own events are sent under as their `deployment_id` +(`telemetry::Telemetry::install_id`), so what the installation did before a sign-in joins what the +person does after it. + +Settings is read again once the id is in hand: turning sharing off marks it off before the emitter +forgets the id (`set_usage_data_in`), and from that moment there is no id to give. Only a random +(version 4) UUID is given, in lower case, as the operation takes it; the emitter has never made any +other kind, and one read back from an older file that is not one is not sent. +*/ +pub fn installation_id(app: &tauri::AppHandle) -> Option { + if !usage_data_now().shared { + return None; + } + let id = app.try_state::()?.emitter.install_id()?; + if !usage_data_now().shared { + return None; + } + as_installation_id(&id) +} + +/// `id` as the operation takes it, or None: a random (version 4) UUID of the standard (RFC 4122) +/// variant, which is what the spec's pattern and the page's check accept, given in lower case with +/// hyphens. Anything else (another version or variant, the nil UUID, braces, a URN, spaces) is None. +fn as_installation_id(id: &str) -> Option { + let parsed = uuid::Uuid::try_parse(id).ok()?; + let hyphenated = parsed.hyphenated().to_string(); + (parsed.get_version_num() == 4 + && parsed.get_variant() == uuid::Variant::RFC4122 + && hyphenated.eq_ignore_ascii_case(id)) + .then_some(hyphenated) +} + /// Turn sharing on or off from Settings. Kept for the next launch, and applied at once to the /// desktop's own events and to the CLI. The server reads it the next time OpenBot starts. pub fn set_usage_data( @@ -1620,6 +1655,104 @@ mod tests { assert!(cli.calls().starts_with("telemetry link --installation-id ")); } + /// Only what the operation's pattern takes is given (`installationId` in the spec, and the page's + /// check in app/src/lib/auth/window-session.ts): a version 4 UUID of the standard variant, + /// hyphenated, given in lower case. Nothing else is turned into one. + #[test] + fn only_an_id_the_operation_takes_is_given() { + let given = "3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88"; + assert_eq!(as_installation_id(given).as_deref(), Some(given)); + assert_eq!( + as_installation_id("3F2C9A64-8E1B-4C7D-9A35-0B6E2D4F1C88").as_deref(), + Some(given) + ); + for refused in [ + // the variant: Microsoft's (c), NCS (7) and the future's (e), not RFC 4122's (8, 9, a, b) + "3f2c9a64-8e1b-4c7d-ca35-0b6e2d4f1c88", + "3f2c9a64-8e1b-4c7d-7a35-0b6e2d4f1c88", + "3f2c9a64-8e1b-4c7d-ea35-0b6e2d4f1c88", + // other versions, and the nil and max UUIDs + "3f2c9a64-8e1b-1c7d-9a35-0b6e2d4f1c88", + "018f2c9a-648e-7b4c-9a35-0b6e2d4f1c88", + "00000000-0000-0000-0000-000000000000", + "ffffffff-ffff-ffff-ffff-ffffffffffff", + // the same UUID spelled any other way + "3f2c9a648e1b4c7d9a350b6e2d4f1c88", + "{3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88}", + "urn:uuid:3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88", + " 3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88", + "3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88\n", + "", + "not an id", + ] { + assert_eq!(as_installation_id(refused), None, "{refused:?}"); + } + } + + /** + OpenBot Cloud is told this installation's id only while the person shares usage data: Settings' + switch on and neither environment opt-out set. Then it is the emitter's own id, which every + desktop event is sent under as `deployment_id`, as a lower-case random (version 4) UUID. Off + either way, or with no id yet, there is nothing to give. + */ + #[test] + fn the_installation_id_is_given_only_while_sharing_usage_data() { + if crate::test_support::isolated_process( + "desktop_telemetry::tests::the_installation_id_is_given_only_while_sharing_usage_data", + ) { + return; + } + std::env::remove_var("COPILOTKIT_TELEMETRY_DISABLED"); + std::env::remove_var("DO_NOT_TRACK"); + usage_data::set_off(false); + let app = tauri::test::mock_builder() + .manage(DesktopTelemetry::for_tests( + temp_root("installation-id-sharing"), + true, + )) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + let state = app.state::(); + + // Sharing: the emitter's own id, a lower-case version 4 UUID. + let id = installation_id(app.handle()).expect("sharing gives the id"); + assert_eq!(Some(&id), state.emitter.install_id().as_ref()); + assert_eq!(uuid::Uuid::parse_str(&id).unwrap().get_version_num(), 4); + assert_eq!(id, id.to_ascii_lowercase()); + + // Settings' switch off: none, from the moment it is marked off. + usage_data::set_off(true); + assert_eq!(installation_id(app.handle()), None); + usage_data::set_off(false); + assert_eq!(installation_id(app.handle()), Some(id.clone())); + + // Either environment opt-out: none, whatever Settings says. + for variable in ["COPILOTKIT_TELEMETRY_DISABLED", "DO_NOT_TRACK"] { + std::env::set_var(variable, "1"); + assert_eq!(installation_id(app.handle()), None, "{variable}"); + std::env::remove_var(variable); + } + assert_eq!(installation_id(app.handle()), Some(id)); + + // An emitter with no id yet (not sharing when it opened), or no emitter at all: none. + let not_sharing = tauri::test::mock_builder() + .manage(DesktopTelemetry::for_tests( + temp_root("installation-id-not-sharing"), + false, + )) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + assert_eq!( + not_sharing.state::().emitter.install_id(), + None + ); + assert_eq!(installation_id(not_sharing.handle()), None); + let without = tauri::test::mock_builder() + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + assert_eq!(installation_id(without.handle()), None); + } + /// The environment opt-out wins: Settings cannot turn sharing on over it. #[test] fn settings_cannot_share_over_the_environment_opt_out() { diff --git a/desktop/src-tauri/src/move_to_cloud.rs b/desktop/src-tauri/src/move_to_cloud.rs index 5768d9f89b..414a9b3aca 100644 --- a/desktop/src-tauri/src/move_to_cloud.rs +++ b/desktop/src-tauri/src/move_to_cloud.rs @@ -1076,6 +1076,99 @@ struct Answered { /// organization-keeping OpenBot has (box A: `/api/v2/people/me/organizations` answered 404). pub const THIS_COMPUTERS_ORGANIZATION: &str = "default"; +/// Where OpenBot is told which OpenBot Desktop installation the caller signed in from +/// (`recordDesktopInstallation`). The person's, not an organization's: it names none. +pub const DESKTOP_INSTALLATIONS_PATH: &str = "/api/v2/people/me/desktop-installations"; + +/// How long after a sign-in its report of the installation (`record_desktop_installation`) may +/// still go out: never later. +pub const RECORD_INSTALLATION_WITHIN: Duration = Duration::from_secs(20); + +/// Why `record_desktop_installation` recorded nothing. Each says no more than a status, never the +/// id or what the server wrote back, which could repeat it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RecordRefused { + /// No credential to send (the sign-in ended, or its refresh failed): nothing was sent. + NoCredential, + /// The time for it had passed by the moment it was to go: nothing was sent. + TooLate, + /// The caller's checks no longer held once the credential was in hand (usage data turned off, + /// a sign-out begun, the sign-in ended): nothing was sent. + NotWanted, + /// It went out, and no answer was read: it is not sent again. + Unanswered, + /// It went out, and OpenBot answered something other than 204 (a 404 from an OpenBot that + /// predates the operation too, and a redirect, which is not followed). + Answered(u16), +} + +impl std::fmt::Display for RecordRefused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RecordRefused::NoCredential => f.write_str("no credential"), + RecordRefused::TooLate => f.write_str("too late"), + RecordRefused::NotWanted => f.write_str("not wanted now"), + RecordRefused::Unanswered => f.write_str("no answer"), + RecordRefused::Answered(status) => write!(f, "{status}"), + } + } +} + +/** +Tell the OpenBot at `base` which OpenBot Desktop installation the caller signed in from +(`recordDesktopInstallation`): `installation_id`, the random id the installation's usage data is +sent under, and nothing else, with the sign-in's own `credentials`. Once, with a new Idempotency-Key, +and never again whatever the answer: not after a 401 (no refresh), a 429 or a failure to connect. +It names no organization, and follows no redirect. Only a 204 counts. Nothing goes out at or after +`until`, which a token refresh is held to as well. The caller decides whether it is wanted at all +(OpenBot Cloud only, usage data shared, the sign-in fresh and still on): `still_wanted` is asked +again once the credential is in hand, right before the one request, since a refresh can take time +in which the person turns sharing off or signs out. +*/ +pub fn record_desktop_installation( + base: &str, + credentials: &dyn Credentials, + installation_id: &str, + until: Instant, + still_wanted: &dyn Fn() -> bool, +) -> Result<(), RecordRefused> { + if Instant::now() >= until { + return Err(RecordRefused::TooLate); + } + let client = reqwest::blocking::Client::builder() + .connect_timeout(Duration::from_secs(5)) + .timeout(Duration::from_secs(10)) + .redirect(reqwest::redirect::Policy::none()) + .default_headers(crate::client_version::headers()) + .build() + .map_err(|_| RecordRefused::Unanswered)?; + let (name, value) = credentials + .header_by(Some(until)) + .map_err(|_| RecordRefused::NoCredential)?; + // A refresh may have taken the time that was left, or the person may have opted out or signed + // out while it ran. + if Instant::now() >= until { + return Err(RecordRefused::TooLate); + } + if !still_wanted() { + return Err(RecordRefused::NotWanted); + } + let response = client + .post(format!( + "{}{DESKTOP_INSTALLATIONS_PATH}", + base.trim_end_matches('/') + )) + .header(name, value) + .header("Idempotency-Key", uuid::Uuid::new_v4().to_string()) + .json(&serde_json::json!({ "installationId": installation_id })) + .send() + .map_err(|_| RecordRefused::Unanswered)?; + match response.status().as_u16() { + 204 => Ok(()), + status => Err(RecordRefused::Answered(status)), + } +} + impl Api { /// The API at `base`, in the organization `organization` (an id or a slug). pub fn at( diff --git a/desktop/src-tauri/src/move_to_cloud/tests.rs b/desktop/src-tauri/src/move_to_cloud/tests.rs index eb467fa8ec..a8b649db87 100644 --- a/desktop/src-tauri/src/move_to_cloud/tests.rs +++ b/desktop/src-tauri/src/move_to_cloud/tests.rs @@ -2831,3 +2831,257 @@ fn an_import_that_finishes_soon_is_seen_within_seconds() { let waited: Duration = clock.slept.iter().sum(); assert!(waited <= Duration::from_secs(14), "waited {waited:?}"); } + +/// The sign-in's token, as `record_desktop_installation` is handed it. A second one is never asked +/// for: the operation is not sent again after a 401. +#[derive(Default)] +struct OneToken { + asked_again: std::sync::atomic::AtomicUsize, +} + +impl Credentials for OneToken { + fn header(&self) -> Result<(&'static str, String), CredentialFailure> { + Ok(("Authorization", format!("Bearer {BEARER}"))) + } + fn after_refused(&self, _used: &str) -> Result<(&'static str, String), CredentialFailure> { + self.asked_again + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(("Authorization", "Bearer refreshed".into())) + } +} + +/// What a fake OpenBot was sent: method, path, headers (names in lower case) and body. +type Reported = Arc, Vec)>>>; + +/// A fake OpenBot that answers every request with `status` (and `location`, for a redirect), and +/// keeps what it was sent. +fn recording(status: u16, location: Option) -> (String, Reported) { + let received: Reported = Arc::default(); + let kept = received.clone(); + let address = serve(move |request| { + kept.lock().unwrap().push(( + request.method.clone(), + request.path.clone(), + request.headers.clone(), + request.body.clone(), + )); + Response { + status, + headers: location + .iter() + .map(|to| ("Location".to_owned(), to.clone())) + .collect(), + body: Vec::new(), + } + }); + (address, received) +} + +const INSTALLATION: &str = "3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88"; + +fn soon() -> Instant { + Instant::now() + RECORD_INSTALLATION_WITHIN +} + +/// One request, exactly as the spec's `recordDesktopInstallation` takes it: POST to the person's own +/// address with the id alone in a JSON body, the sign-in's Bearer token, a new random (version 4) +/// Idempotency-Key, and no organization. A 204 is recorded. +#[test] +fn the_installation_is_recorded_with_one_request_as_the_spec_takes_it() { + let (address, received) = recording(204, None); + let token = OneToken::default(); + assert_eq!( + record_desktop_installation(&address, &token, INSTALLATION, soon(), &|| true), + Ok(()) + ); + let received = received.lock().unwrap(); + assert_eq!(received.len(), 1); + let (method, path, headers, body) = &received[0]; + assert_eq!(method, "POST"); + assert_eq!(path, DESKTOP_INSTALLATIONS_PATH); + assert_eq!( + String::from_utf8(body.clone()).unwrap(), + format!(r#"{{"installationId":"{INSTALLATION}"}}"#) + ); + assert_eq!(headers["content-type"], "application/json"); + assert_eq!(headers["authorization"], format!("Bearer {BEARER}")); + let key = uuid::Uuid::parse_str(&headers["idempotency-key"]).unwrap(); + assert_eq!(key.get_version_num(), 4, "{key}"); + assert!(!headers.contains_key("openbot-organization"), "{headers:?}"); + assert!(!headers.contains_key("origin"), "{headers:?}"); + assert_eq!( + token.asked_again.load(std::sync::atomic::Ordering::SeqCst), + 0 + ); + + // Each sign-in's report has its own key. + drop(received); + let (again, sent_again) = recording(204, None); + record_desktop_installation(&again, &token, INSTALLATION, soon(), &|| true).unwrap(); + let first = uuid::Uuid::parse_str(&headers_of(&sent_again)["idempotency-key"]).unwrap(); + assert_ne!(first, key); +} + +/// The request as the spec is tested to take it (app/tests/fixtures/desktop-installation-request.json, +/// which api/openapi-desktop-installations.test.ts holds to the spec): the sender's bytes, not a +/// description of them. +#[test] +fn the_installation_request_is_the_one_the_spec_is_tested_to_take() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../../app/tests/fixtures/desktop-installation-request.json" + )) + .unwrap(); + let text = |key: &str| fixture[key].as_str().unwrap().to_owned(); + let (address, received) = recording(204, None); + record_desktop_installation( + &address, + &OneToken::default(), + &text("installation_id"), + soon(), + &|| true, + ) + .unwrap(); + let received = received.lock().unwrap(); + assert_eq!(received.len(), 1); + let (method, path, headers, body) = &received[0]; + assert_eq!(*method, text("method")); + assert_eq!(*path, text("path")); + assert_eq!(String::from_utf8(body.clone()).unwrap(), text("body")); + assert_eq!(headers["content-type"], text("content_type")); + for absent in fixture["absent_headers"].as_array().unwrap() { + assert!(!headers.contains_key(absent.as_str().unwrap()), "{absent}"); + } + // The key is new each time; it has the shape of the one kept in the file. + let key = &headers["idempotency-key"]; + let kept = text("idempotency_key"); + assert_eq!(key.len(), kept.len()); + assert_eq!(uuid::Uuid::parse_str(key).unwrap().get_version_num(), 4); + assert_eq!(uuid::Uuid::parse_str(&kept).unwrap().get_version_num(), 4); + assert_eq!(key.to_lowercase(), *key); +} + +fn headers_of(received: &Reported) -> BTreeMap { + received.lock().unwrap()[0].2.clone() +} + +/// Any answer but 204 is not recorded and is said by its status alone; nothing is sent again, +/// whatever it was: not after a 401 (no fresh token is asked for), a 429 or a 500. A 404 is what an +/// OpenBot that predates the operation answers. +#[test] +fn any_answer_but_204_is_its_status_and_nothing_is_sent_again() { + for status in [404, 401, 429, 500, 503, 200] { + let (address, received) = recording(status, None); + let token = OneToken::default(); + assert_eq!( + record_desktop_installation(&address, &token, INSTALLATION, soon(), &|| true), + Err(RecordRefused::Answered(status)) + ); + assert_eq!(received.lock().unwrap().len(), 1, "{status}"); + assert_eq!( + token.asked_again.load(std::sync::atomic::Ordering::SeqCst), + 0, + "{status}" + ); + assert_eq!( + RecordRefused::Answered(status).to_string(), + status.to_string() + ); + } +} + +/// A redirect is not followed: the address it names is sent nothing. +#[test] +fn a_redirect_is_not_followed() { + let (elsewhere, sent_elsewhere) = recording(204, None); + let (address, received) = recording( + 307, + Some(format!("{elsewhere}{DESKTOP_INSTALLATIONS_PATH}")), + ); + assert_eq!( + record_desktop_installation( + &address, + &OneToken::default(), + INSTALLATION, + soon(), + &|| true + ), + Err(RecordRefused::Answered(307)) + ); + assert_eq!(received.lock().unwrap().len(), 1); + assert_eq!(sent_elsewhere.lock().unwrap().len(), 0); +} + +/// Past its time, nothing goes out; and an OpenBot that can't be reached is not tried again. +#[test] +fn nothing_goes_out_late_and_an_unreachable_openbot_is_not_tried_again() { + let (address, received) = recording(204, None); + assert_eq!( + record_desktop_installation( + &address, + &OneToken::default(), + INSTALLATION, + Instant::now() - Duration::from_millis(1), + &|| true + ), + Err(RecordRefused::TooLate) + ); + assert_eq!(received.lock().unwrap().len(), 0); + + let closed = TcpListener::bind("127.0.0.1:0").unwrap(); + let nobody = format!("http://{}", closed.local_addr().unwrap()); + drop(closed); + assert_eq!( + record_desktop_installation(&nobody, &OneToken::default(), INSTALLATION, soon(), &|| { + true + }), + Err(RecordRefused::Unanswered) + ); +} + +/// A credential whose reading takes as long as a refresh, during which the person signs out (or +/// turns usage data off): the caller's checks are asked again once it is in hand. +struct SignedOutWhileReading { + signed_out: Arc, +} + +impl Credentials for SignedOutWhileReading { + fn header(&self) -> Result<(&'static str, String), CredentialFailure> { + self.signed_out + .store(true, std::sync::atomic::Ordering::SeqCst); + Ok(("Authorization", format!("Bearer {BEARER}"))) + } + fn after_refused(&self, _used: &str) -> Result<(&'static str, String), CredentialFailure> { + Err(CredentialFailure::NoCredential("not asked for".into())) + } +} + +/// The checks still hold when the report starts, and a sign-out begins while its credential is read: +/// nothing is sent. The same report with checks that still hold afterwards goes out once. +#[test] +fn a_sign_out_while_the_credential_is_read_sends_nothing() { + let (address, received) = recording(204, None); + let signed_out = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let credentials = SignedOutWhileReading { + signed_out: signed_out.clone(), + }; + let still_signed_in = || !signed_out.load(std::sync::atomic::Ordering::SeqCst); + assert!(still_signed_in()); + assert_eq!( + record_desktop_installation( + &address, + &credentials, + INSTALLATION, + soon(), + &still_signed_in + ), + Err(RecordRefused::NotWanted) + ); + assert_eq!(received.lock().unwrap().len(), 0); + assert_eq!(RecordRefused::NotWanted.to_string(), "not wanted now"); + + assert_eq!( + record_desktop_installation(&address, &credentials, INSTALLATION, soon(), &|| true), + Ok(()) + ); + assert_eq!(received.lock().unwrap().len(), 1); +} diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 2b7f346b27..77b4bf4ff0 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -31,7 +31,7 @@ With product telemetry on, every run also states the shared Intelligence analyti ## Events and interpretation -The event names are `oss.runtime.openbot.run_accepted`, `.run_terminal`, `.run_stop_requested`, `.capability`, `.result_viewed`, `.result_copied`, `.exception`, `.nudge_shown`, `.nudge_clicked` and `.nudge_dismissed`. Common properties include `schema_version`, `app_id`, `event_id`, `occurred_at`, `deployment_id`, `deployment_kind`, `user_id`, `environment`, `openbot_version` and `openbot_edition`. `deployment_kind` is `cloud` for OpenBot Cloud, `desktop` for OpenBot Desktop and `self_hosted` for any other server. On OpenBot Cloud, whose `deployment_id` is `openbot-cloud`, `run_accepted` and `run_terminal` also carry `org_id`, the organization's opaque internal id, never its name; no other deployment sends it. `openbot_version` is the release the running server is, as its image is tagged and without the tag's `v` (`1.1.0`, `1.1.0-rc.2`); an internal build is `1.1.0-internal`; a development server or a local image build is `unknown`. `openbot_edition` is `team` or `personal`. Together they let a staged rollout be watched release by release. `environment` (and `deployment_environment`, the same value) says what kind of deployment sent the event, decided by the build it runs and not by `NODE_ENV`, which a Compose install and OpenBot Desktop leave empty: a build with a version (a release, a release candidate or an internal build) is `production`; a development server or a local image build, whose `openbot_version` is `unknown`, is `development`; a test run (`NODE_ENV=test`) is `test`. Events sent before this say `unknown`. Those that carry an `openbot_version` other than `unknown` came from such a build and count as `production`; those with no `openbot_version` at all predate it and cannot be told apart. [The queries](telemetry-queries.sql) read history this way. Run events carry known thread/run/root/parent IDs, `attempt_id=run_id`, a numeric `attempt` only when available, `trigger`, `surface` and `purpose`. Unknown linkage stays unknown. +The event names are `oss.runtime.openbot.run_accepted`, `.run_terminal`, `.run_stop_requested`, `.capability`, `.result_viewed`, `.result_copied`, `.exception`, `.nudge_shown`, `.nudge_clicked`, `.nudge_dismissed` and `.desktop_installation_linked` (its own properties [below](#openbot-desktop-signed-in-to-openbot-cloud)). Common properties include `schema_version`, `app_id`, `event_id`, `occurred_at`, `deployment_id`, `deployment_kind`, `user_id`, `environment`, `openbot_version` and `openbot_edition`. `deployment_kind` is `cloud` for OpenBot Cloud, `desktop` for OpenBot Desktop and `self_hosted` for any other server. On OpenBot Cloud, whose `deployment_id` is `openbot-cloud`, `run_accepted` and `run_terminal` also carry `org_id`, the organization's opaque internal id, never its name; no other deployment sends it. `openbot_version` is the release the running server is, as its image is tagged and without the tag's `v` (`1.1.0`, `1.1.0-rc.2`); an internal build is `1.1.0-internal`; a development server or a local image build is `unknown`. `openbot_edition` is `team` or `personal`. Together they let a staged rollout be watched release by release. `environment` (and `deployment_environment`, the same value) says what kind of deployment sent the event, decided by the build it runs and not by `NODE_ENV`, which a Compose install and OpenBot Desktop leave empty: a build with a version (a release, a release candidate or an internal build) is `production`; a development server or a local image build, whose `openbot_version` is `unknown`, is `development`; a test run (`NODE_ENV=test`) is `test`. Events sent before this say `unknown`. Those that carry an `openbot_version` other than `unknown` came from such a build and count as `production`; those with no `openbot_version` at all predate it and cannot be told apart. [The queries](telemetry-queries.sql) read history this way. Run events carry known thread/run/root/parent IDs, `attempt_id=run_id`, a numeric `attempt` only when available, `trigger`, `surface` and `purpose`. Unknown linkage stays unknown. `run_accepted` records entry into agent execution, rather than every HTTP run/connect request. Only runs OpenBot started as work are counted: a person's, a routine's, a subagent's or a hop's. The runtime's own runs on a Bot, naming a new conversation or offering suggestions, carry no OpenBot context and emit no run events. `run_terminal` records the observed `outcome`, bounded `failure_category`, duration, `is_root` and up to 256 `result_message_ids`. A run that ended because its model provider failed also carries `refusal_kind`, one closed name for what went wrong: `usage_limit` (a plan's usage limit, until it resets), `usage_credits`, `rate_limit`, `billing`, `key`, `model`, `outdated_client`, `too_many_tools`, `too_long`, `too_large`, `provider_down`, `connection_dropped`, `no_response`, `unreachable`, `declined` (the model declined to answer), `unknown` or `other`. It is `null` on every other run, and never carries the provider's words. An actual protocol finish without an explicit failure is normal completion; source errors, cancellation and timeout remain distinct. The host may emit `run_stop_requested` with a bounded stop reason; this records a request, not a terminal outcome. A run OpenBot knows it stopped ends `cancelled` with `failure_category` `none`: a person's Stop (on a browser run or on a thread a headless turn runs in), a stop that reaches a subagent, a headless cancel or pause, and a paused hop. A headless turn stopped at its deadline ends `timeout`. A lost lock is not a stop. Missing terminal evidence is unknown. A child run never determines its parent's outcome. Human initiation, scheduled routines, followups and subagents remain separate triggers. @@ -85,6 +85,21 @@ OpenBot Desktop reports its own updates with four events. `oss.desktop.update_st An internal build reports its version with an `internal` label, as in `1.1.0-internal`, without the commit count and hash, so it is not counted as the release; the server says the same. Every Desktop event also carries `deployment_id`, the install id it is sent under. The Desktop hands that id to its server as `CPK_TELEMETRY_ID`, which the server's events carry as their `deployment_id`, so Desktop and server events join on it. +## OpenBot Desktop signed in to OpenBot Cloud + +A Desktop that runs its own server joins it through `CPK_TELEMETRY_ID` (above). One signed in to OpenBot Cloud has no server of its own, and OpenBot Cloud's events carry Cloud's own `deployment_id`. So after a sign-in to OpenBot Cloud, while the person shares usage data, the installation id (the install id above) is reported once to `POST /api/v2/people/me/desktop-installations` (`recordDesktopInstallation`): + +```json +{"installationId":"3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88"} +``` + +- **Who sends it.** After the window's sign-in, OpenBot Cloud's `/desktop/signed-in` page, with its new session, once it has traded the code; Desktop hands it the id in the address's fragment. After Move to Cloud's sign-in, Desktop itself, with that sign-in. Only OpenBot Cloud's own address is given the id: never a company's OpenBot or Cloud's staging copy, since sharing usage data is consent to CopilotKit, not to a company's server ([desktop telemetry](../desktop/TELEMETRY.md#openbot-cloud-sign-in-link) says when nothing is sent). +- **What the server sends.** `oss.runtime.openbot.desktop_installation_linked`, with the caller's `user_id` pseudonym, `installation_id` (the installation id, in lower case) and `credential` (`session` for the page, `app_token` for Desktop's own sign-in). Nothing else about the person or the computer. +- **Counted once.** The event id is made from the deployment, the pseudonym and the installation id in lower case, so the same person and installation is one event however often, and by whichever sign-in, it is reported: the window and Move to Cloud both sending it for one person, or a sign-in again, still count once by `event_id`. Another person or another installation is another event. +- **When it is dropped.** Where product telemetry is off, a valid report is answered `204` and nothing is sent. Each report has its own Idempotency-Key; the sender never retries, so a report sent to a server without the operation (`404`) is lost, not resent. +- **The join.** Desktop's events by `deployment_id` equal to `installation_id`, and the person's OpenBot Cloud events by the link event's `deployment_id` and `user_id`. It is a join, not a merge: no PostHog person is aliased. Query G in [telemetry-queries.sql](telemetry-queries.sql). +- **Not covered here.** A sign-out of OpenBot Cloud doesn't make a new installation id, so a second person who signs in to OpenBot Cloud on the same computer links the same installation ([desktop TELEMETRY.md](../desktop/TELEMETRY.md#openbot-cloud-sign-in-link)). That is a follow-up. + ## Delivery and reporting limits Sending is best effort through the existing transport. There is no local event journal, application-level telemetry retry, replay or exactly-once producer guarantee. Stable event IDs support deduplication in PostHog queries; physical sink/destination deduplication remains an external transport concern. Shared sender completion does not acknowledge destination receipt, and opt-out or unavailable transport can leave gaps. diff --git a/docs/desktop-install.md b/docs/desktop-install.md index 0f1eeb8be6..fa77d05bbd 100644 --- a/docs/desktop-install.md +++ b/docs/desktop-install.md @@ -148,6 +148,13 @@ current UUID through `CPK_TELEMETRY_ID` when it starts. Only the native desktop separate telemetry Compose override; shared Compose and Enterprise charts are unchanged. The handoff adds no readable PII or user content. Opaque account linking is pseudonymous, not anonymous. +A sign-in to OpenBot Cloud, while the person shares usage data, also tells OpenBot Cloud the +installation id (the UUID above) once: OpenBot Cloud's page sends it after the window's sign-in, and the desktop +sends it after Move to Cloud's. It joins this installation's events with OpenBot Cloud's pseudonym +for the person. Only OpenBot Cloud's own address is told, never a company's OpenBot or Cloud's +staging copy, since sharing usage data is consent to CopilotKit +([OpenBot Cloud sign-in link](../desktop/TELEMETRY.md#openbot-cloud-sign-in-link)). + Nothing here can keep OpenBot from opening. Sign-in and Start never wait for `telemetry link`: Start hands the runtime the identity as it stands and links afterwards, so an account change found then reaches the runtime at the next Start. Required CLI calls preempt optional linking, and duplicate diff --git a/docs/telemetry-queries.sql b/docs/telemetry-queries.sql index f85118cbfe..7acf2cee73 100644 --- a/docs/telemetry-queries.sql +++ b/docs/telemetry-queries.sql @@ -167,3 +167,45 @@ WHERE event IN ('oss.runtime.openbot.nudge_shown', AND coalesce(properties.openbot_version,'unknown')!='unknown')) AND properties.event_id IS NOT NULL GROUP BY nudge, place, moment; + +-- G. OpenBot Desktop installations linked to OpenBot Cloud people +-- (desktop_installation_linked; docs/TELEMETRY.md). Each event_id is one +-- person and installation, so distinct event_ids are links, however often +-- and by whichever sign-in (the window's page, Move to Cloud) they were +-- reported. Desktop's own events carry the installation id as their deployment_id; +-- the person's OpenBot Cloud events carry the link's deployment_id and user_id. +-- A join, not a merge: no PostHog person is aliased. +-- One row per link: the keys to the person's OpenBot Cloud events +-- (cloud_deployment_id, cloud_user_id) and the installation's Desktop events +-- as delivered, before and after the link. Join the Cloud events on those keys +-- for what the person did in OpenBot Cloud. No link exists before the server +-- change is deployed: set the links' start to that date, and the Desktop +-- events' start as far back as the question needs. +WITH links AS ( + SELECT properties.event_id AS link_id, + any(properties.installation_id) AS installation_id, + any(properties.deployment_id) AS cloud_deployment_id, + any(properties.user_id) AS cloud_user_id, + min(timestamp) AS linked_at + FROM events + WHERE event='oss.runtime.openbot.desktop_installation_linked' + AND timestamp >= toDateTime('2026-12-04 00:00:00', 'UTC') + AND properties.app_id='openbot' + AND properties.environment='production' + AND properties.event_id IS NOT NULL + GROUP BY link_id +), +desktop AS ( + SELECT properties.deployment_id AS installation_id, + min(timestamp) AS first_desktop_event, + count() AS desktop_events + FROM events + WHERE event LIKE 'oss.desktop.%' + AND timestamp >= toDateTime('2026-11-01 00:00:00', 'UTC') + AND properties.deployment_id IN (SELECT installation_id FROM links) + GROUP BY installation_id +) +SELECT l.installation_id, l.cloud_deployment_id, l.cloud_user_id, l.linked_at, + d.first_desktop_event, d.desktop_events +FROM links l +LEFT JOIN desktop d ON d.installation_id=l.installation_id;