diff --git a/desktop/TELEMETRY.md b/desktop/TELEMETRY.md index e1db061e04..16b13249ed 100644 --- a/desktop/TELEMETRY.md +++ b/desktop/TELEMETRY.md @@ -56,7 +56,7 @@ All desktop event names begin with `oss.desktop.`. The Rust `EventData` enum and For `model_chosen`, providers are `openai`, `anthropic`, `google`, `xai`, `cloudflare`, `compatible`, or `none`; credential paths are `subscription`, `api_key`, `oauth`, or `none`. OpenAI and Anthropic plan sign-ins use `subscription`. xAI's and Cloudflare's native sign-ins use their named provider with `oauth` (Google's did, before Gemini took an API key only); Google's and xAI's API-key routes use `compatible`, matching the picker’s endpoint choice. A compatible endpoint uses `api_key` only when a nonblank key is supplied or its saved key is explicitly selected; keyless endpoints use `none`. Skipping model setup uses provider and credential path `none`. `custom_base_url` records only whether a nonblank base URL was selected, never its value. -`setup_failed` is sent by the desktop itself, never by the window, from every failed install or Start (once: a step that already said it failed is not counted again, and a Start cancelled by Stop is not a failure), and from every failed `local setup`, `local start`, `local update`, `local connect`, the Learning model's setup after Start, and an Account-step check that stops setup (an engine too small, or one local setup does not run on). `step` is the last screen shown; `failing_step` names the part that failed by the setup rows' step names (`install_engine`, `services`, `local_setup`, `account_check`, ...). `error_class` comes from the step, or where the step says nothing, from the failure's words, of which only the class is kept. `cli_reason` and `cli_failure` are the CLI's closed reason and the desktop's closed failure category. `resources`, for an engine too small, has `cpu_short`, `memory_short` and `disk_short`, and what setup needs against what was measured: CPUs in thousandths, memory and disk in MiB; anything not measured is absent. +`setup_failed` is sent by the desktop itself, never by the window, from every failed install or Start (once: a step that already said it failed is not counted again, and a Start cancelled by Stop is not a failure), and from every failed `local setup`, `local start`, `local update`, `local connect`, the Learning model's setup after Start, and an Account-step check that stops setup (an engine too small, or one local setup does not run on). `step` is the last screen shown, including one shown after a connection is kept (`install` when none). Setup ending clears it (`activated`, `openbot_connect` `completed`, `setup_abandoned`, `setup_restart_required`, or a kept connection that closes an open setup session); a connection kept with no setup session open, such as an organization switch, leaves it as it was. `failing_step` names the part that failed by the setup rows' step names (`install_engine`, `services`, `local_setup`, `account_check`, ...). `error_class` comes from the step, or where the step says nothing, from the failure's words, of which only the class is kept. `cli_reason` and `cli_failure` are the CLI's closed reason and the desktop's closed failure category. `resources`, for an engine too small, has `cpu_short`, `memory_short` and `disk_short`, and what setup needs against what was measured: CPUs in thousandths, memory and disk in MiB; anything not measured is absent. `setup_stalled` and `ui_stalled` report a hang, which is not a failure and so is never a `setup_failed`. Both are sent by the desktop itself, never by the window, with closed names and seconds only: never what the window showed, a log line, or what the step was working on. @@ -64,13 +64,21 @@ For `model_chosen`, providers are `openai`, `anthropic`, `google`, `xai`, `cloud `ui_stalled` is a setup window that stopped taking what the desktop sends it. While the setup, start or update screens show, the page invokes `setup_heartbeat` every five seconds, and as soon as a row's progress reaches it, with the highest progress number it has taken (`setup:progress` carries one). The heartbeat is never awaited and runs off the window's thread. Progress left untaken for over 30 seconds while the window is shown, not minimised and, on macOS, not covered is a stall. The Desktop log says `[ui] the window has not answered for 31s during start_machine` when it is noticed and `[ui] the window stopped answering for 42s during start_machine` when it ends, and that end sends one `ui_stalled` with `stalled_seconds` and `step`, the setup row the desktop was reporting, by the same names as `failing_step`. It ends when the page catches up, the window leaves the screen, the window loads another page, or OpenBot quits. A page that has just loaded counts what was sent before it listened as taken, and a page that sends no heartbeat (OpenBot itself) is not watched. -`setup_abandoned` is setup ending before activation, or before a connection from the first screen completed (`openbot_connect`): Quit during setup, or, on the next launch, a crash. `setup_restart_required` is setup ending for the Windows restart that turning on Windows Subsystem for Linux needs, at the step it was on: Restart now, or Windows ending the app while that restart is owed (a restart from the Start menu). It is saved before Windows ends the app and sent by the launch after the restart, which carries on the same setup under the same installation UUID; that exit is never a `setup_abandoned`. A Quit while the restart is owed is still `setup_abandoned`. +`setup_abandoned` is setup ending before activation, or before a connection to an OpenBot that runs elsewhere is kept: Quit during setup, or, on the next launch, a crash. The app keeps a connection in three ways. Connect through the relay keeps it once signed in and that OpenBot answered, just before `openbot_connect` `completed` is counted when the window named the screen it was pressed on (`screen`). The window's own sign-in keeps it once the browser sign-in came back, just before the window trades its code for its session at that OpenBot. Move to Cloud keeps it once the move is saved. Keeping it closes any setup session still open, whether or not a `completed` was sent, and nothing starts one while it is kept. + +`step_viewed` still counts each launch, and the first screen whenever it shows again, while a connection is kept, but neither a quit nor a crash then sends `setup_abandoned`, even after a Sign in again that started, failed or was cancelled. The first screen shows again for Sign in again once a sign-in ended, at launch or while OpenBot shows, or once the window's own sign-in was let go (OpenBot's page could not trade its code, or that OpenBot no longer signs the window in); for a saved OpenBot that cannot be reached; and for the choice made again from Settings. A setup session the last run left open (a crash, or an earlier version, which started one at every launch) is closed without a `setup_abandoned` by a launch that finds the connection kept. + +`setup_abandoned` was also sent for a quit or a crash of a connected app by releases before this rule, at `welcome` or `connect_openbot`, and one that such a release recorded on quit but had not yet sent is still sent after the update, so compare `setup_abandoned` from before and after the rule by `openbot_version` (the app version every event carries). + +`step_viewed` `welcome` is sent at once when OpenBot (Self-Contained) is chosen on a first screen shown again, before the window shows anything and even when the window then resumes past Welcome: the choice starts a setup on this computer at its first screen, as a first launch does, and a quit or a crash before `activated` abandons it as any other; an installation that was activated before stays activated, so a quit or a crash then sends no `setup_abandoned`. A screen said twice in a row is counted once, as every `step_viewed` is, unless setup ended between the two; usage data turned off and back on in Settings starts afresh, so the first screen after it is counted, and a setup failure before any screen is placed at `install`. + +`setup_restart_required` is setup ending for the Windows restart that turning on Windows Subsystem for Linux needs, at the step it was on: Restart now, or Windows ending the app while that restart is owed (a restart from the Start menu). It is saved before Windows ends the app and sent by the launch after the restart, which carries on the same setup under the same installation UUID; that exit is never a `setup_abandoned`. A Quit while the restart is owed is still `setup_abandoned`. `windows_probe` is one of the Windows readiness check's probes, which the setup window waits on before it shows its first screen, that ran long or was stopped at its limit. Sent by the desktop itself, once per such probe, on Windows only. `probe` is which one, by what it asks: `virtualization`, `administrator`, `wsl_feature`, `wsl_service`, `virtual_machine_platform_feature`, `wsl_version`, `wsl_system_start` (`wsl.exe --system`, which starts WSL's own VM) or `docker`. `outcome` is `slow` (it answered, after the probe's slow mark) or `timed_out` (it was stopped at its limit and counted as no answer). `duration_ms` is how long it ran. Slow marks are well under the limits: 5 seconds for the PowerShell probes and `wsl_version` (limit 30), 3 for `docker` (limit 10), and 20 for `wsl_system_start` (limit 60; a cold start measured about 6). A probe that answers in good time sends nothing. Never the command, its output, its error or a path. `business_opened` is OpenBot for Business's booker coming on screen because it was picked: on the first screen (`welcome`) or in Move to Cloud (`move_to_cloud`), once for each place each time the setup window's page loads (coming back to setup from OpenBot loads it again), however often it is picked again there. `business_booked` is a call booked in its calendar, said by Calendly from its own origin and the calendar's frame. The window sends both, with the place and nothing else: never the time booked or anything typed into the calendar. The calendar's address carries the same place as `utm_content` beside `utm_source=openbot_app` and `utm_medium=in_app`, which Calendly keeps on the booking, so a booking and these events name the same screen. -`openbot_connect` is the first screen's connection to an OpenBot that runs elsewhere, by the screen it was made on: OpenBot Cloud's sign-in (`cloud`) or a company's OpenBot by its address (`connect_openbot`). It counts that screen whenever it shows: on a first setup, and on a later launch that shows it again, such as a saved connection whose sign-in ended (Sign in again) or the choice of where OpenBot runs made again from Settings. The window sends `started` when the person presses Sign in, Connect, Try again or Sign in again, then `failed` when the address check or the browser sign-in fails, or `cancelled` when the person presses Cancel. The desktop itself sends `completed` once signed in and that OpenBot is shown, since the window has gone to it by then. Each ending has `duration_ms` from the press, and the outcomes are `sign_in`'s. A Cancel pressed just as the sign-in completes can give `cancelled` and then `completed` for one go: it did connect. `completed` also ends the setup session, as `activated` does for OpenBot on this computer, so a quit afterwards is not `setup_abandoned`; it is not `activated`, since nothing started here. Move to Cloud signs in its own way and never sends it. Opening a connection again with the sign-in this computer already has sends nothing, and a sign-in left behind when the screen goes says nothing when it ends. Never the address, its host or the sentence about what went wrong. It is not `sign_in`, which stays the Account step's CopilotKit sign-in. +`openbot_connect` is the first screen's connection to an OpenBot that runs elsewhere, by the screen it was made on: OpenBot Cloud's sign-in (`cloud`) or a company's OpenBot by its address (`connect_openbot`). It counts that screen whenever it shows: on a first setup, and on a later launch that shows it again, such as a saved connection whose sign-in ended (Sign in again) or the choice of where OpenBot runs made again from Settings. Shown again once a connection is kept, its `step_viewed` starts no setup session (see `setup_abandoned`). The window sends `started` when the person presses Sign in, Connect, Try again or Sign in again, then `failed` when the address check or the browser sign-in fails, or `cancelled` when the person presses Cancel. The desktop itself sends `completed` once signed in and the window has gone to that OpenBot: through the relay, once that OpenBot is shown; through the window's own sign-in, once the window goes to the page that trades its code, so before the trade. Each ending has `duration_ms` from the press, and the outcomes are `sign_in`'s. A Cancel pressed just as the sign-in completes can give `cancelled` and then `completed` for one go: it did connect. `completed` also ends the setup session, as `activated` does for OpenBot on this computer, so a quit afterwards is not `setup_abandoned`; it is not `activated`, since nothing started here. Move to Cloud signs in its own way and never sends it. Opening a connection again with the sign-in this computer already has sends nothing, and a sign-in left behind when the screen goes says nothing when it ends. Never the address, its host or the sentence about what went wrong. It is not `sign_in`, which stays the Account step's CopilotKit sign-in. `engine_measured` is what the Account step's check measured of the engine local setup runs on, too small or not: `resources` as `setup_failed` carries it for an engine too small, CPUs in thousandths and memory and free disk in MiB, against what setup needs. Sent by the desktop itself, never by the window, once a launch and again only when the engine's CPUs or memory change (a Podman machine made bigger). Free disk is sent with them, but a change in it alone, as the downloads fill the disk, sends nothing new. Every install that goes through the Account step runs that check, so each one whose engine answers it sends one; an engine not known yet, or one that does not answer, is not measured and sends nothing, and neither does a reinstall that goes straight to Install. Nothing is kept while usage data is off, so turning it on again in the same launch still sends the size. OpenBot Cloud and a company's OpenBot run nothing on this computer, so a connection never sends it. Never the engine's name, a drive, a path or a hostname. @@ -82,7 +90,7 @@ Image timing covers an explicit missing-only Compose pull, excluding startup and ## Delivery and verification -Events persist before sending and keep their event IDs across retries. The queue holds at most 256 events, dropping the oldest on overflow. An event the sink refuses (a 4xx other than 408 and 429) is dropped and the queue goes on; a 429, 408, 5xx or no answer holds the whole queue for a backoff from 10 seconds to 30 minutes with jitter, or the sink's `Retry-After` when that is longer (at most a day). Background delivery, bounded quit flushing, and replay on relaunch use the existing CopilotKit ingest contract. A crash before activation records abandonment on the next launch. Telemetry failures do not block setup. +Events persist before sending and keep their event IDs across retries. The queue holds at most 256 events, dropping the oldest on overflow. An event the sink refuses (a 4xx other than 408 and 429) is dropped and the queue goes on; a 429, 408, 5xx or no answer holds the whole queue for a backoff from 10 seconds to 30 minutes with jitter, or the sink's `Retry-After` when that is longer (at most a day). Background delivery, bounded quit flushing, and replay on relaunch use the existing CopilotKit ingest contract. A crash during a setup session (before activation) records abandonment on the next launch, unless that launch finds a connection kept. Telemetry failures do not block setup. The ingest must accept the new `oss.desktop.*` namespace: [oss-path-to-production #290](https://github.com/CopilotKit/oss-path-to-production/pull/290), merged on 2026-09-12. A successful HTTP response alone does not prove downstream acceptance; production ingest acknowledges filtered events too. Production desktop delivery depends on that change being deployed. diff --git a/desktop/src-tauri/src/connected_ipc_tests.rs b/desktop/src-tauri/src/connected_ipc_tests.rs index 28e7e3a9f7..fc58a1b589 100644 --- a/desktop/src-tauri/src/connected_ipc_tests.rs +++ b/desktop/src-tauri/src/connected_ipc_tests.rs @@ -1,7 +1,8 @@ // Included by main.rs: the app connected to an OpenBot that runs elsewhere, through the shell's own // registered commands, its window rules and its Stop and Quit. The sign-in and the relay themselves -// are tested in the library (`connected`), against a full OpenBot stand-in; here only a `/health` -// stand-in is used. +// are tested in the library (`connected`), against a full OpenBot stand-in; here small stand-ins +// answer only what the shell asks: `/health`, the token endpoint and, for a sign-in through the +// browser, the window stand-in (`window_ipc_tests.rs`). mod connected_ipc { use super::*; use openbot_desktop_lib::connected::{choice, credentials}; @@ -83,6 +84,7 @@ mod connected_ipc { desktop_connected::sign_out_of_openbot, desktop_connected::use_this_computer, desktop_connected::take_connection_notice, + record_setup_event, ]) .build(context) .unwrap(); @@ -288,6 +290,539 @@ mod connected_ipc { } } + /// An app with `connection.json` in `config` (connected to `ADDRESS` when `connected`) and + /// usage data kept in `data`, launched as `desktop_telemetry::initialize` launches it once it + /// has read the usage-data setting (`open_then_launch`), sending nowhere. + fn launched_with_usage_data(connected: bool, data: &std::path::Path) -> Connected { + launched_connected_to(connected.then_some(ADDRESS), data) + } + + /// The same, connected to `address` when one is given. + fn launched_connected_to(address: Option<&str>, data: &std::path::Path) -> Connected { + let shell = Connected::new(); + if let Some(address) = address { + shell.choose(choice::Mode::Connected, address, None); + } + desktop_telemetry::initialize_for_test(shell.handle(), data.to_path_buf()); + shell + } + + /// The next launch after `after`: a new app on the same `connection.json`, as `after` left it, + /// and the same usage data in `data`. + fn relaunched(after: &Connected, data: &std::path::Path) -> Connected { + let shell = Connected::new(); + desktop_connected::use_for_test(shell.handle(), after.config.clone(), shell.store.clone()); + desktop_telemetry::initialize_for_test(shell.handle(), data.to_path_buf()); + shell + } + + fn queued(shell: &Connected) -> Vec { + shell + .app + .state::() + .queued() + } + + /// The window's own event, through `record_setup_event` from the setup window. + fn window_says(shell: &Connected, event: &serde_json::Value) { + assert_eq!( + shell.ask_with(SETUP, "record_setup_event", serde_json::json!({ "event": event })), + Ok(serde_json::Value::Null), + "{event}" + ); + } + + /// A quit of `shell`, then the next launch of an app on the same files: the quit leaves `shown` + /// queued and nothing more (no `setup_abandoned`), and the next launch adds only its own + /// `welcome`. The usage data in `data` is removed afterwards. + fn quit_and_relaunch_without_abandonment( + shell: Connected, + data: &std::path::Path, + shown: Vec, + what: &str, + ) { + use openbot_desktop_lib::telemetry::{EventData, Step}; + desktop_telemetry::shutdown(shell.handle()); + assert_eq!(queued(&shell), shown, "{what}: on quit"); + let next = relaunched(&shell, data); + let mut expected = shown; + expected.push(EventData::StepViewed { + step: Step::Welcome, + }); + assert_eq!(queued(&next), expected, "{what}: next launch"); + drop(next); + drop(shell); + let _ = std::fs::remove_dir_all(data); + } + + /// Connect pressed on the first screen's address, through `connect_to_openbot` from the setup + /// window, as the window asks it: when `named`, after its own `started` and with the screen and + /// its wait (`ConnectToOpenBot.tsx`, which always names the screen today); otherwise with the + /// address alone, the defensive case. What it adds to usage data: `started` and the shell's + /// `completed`, from the press, when named; nothing otherwise. + fn connect_from_the_first_screen( + shell: &Connected, + address: &str, + named: bool, + ) -> Vec { + use openbot_desktop_lib::telemetry::{ConnectOutcome, ConnectScreen, EventData}; + let mut asked = serde_json::json!({ "address": address }); + if named { + window_says( + shell, + &serde_json::json!({ + "kind": "openbot_connect", "screen": "connect_openbot", "outcome": "started" + }), + ); + asked["screen"] = "connect_openbot".into(); + asked["waitedMs"] = 400.into(); + } + shell + .ask_with(SETUP, "connect_to_openbot", asked) + .expect("connected"); + if !named { + return Vec::new(); + } + // From the press: the window's 400 ms, then the sign-in's own time. + let took = queued(shell).last().and_then(|event| match event { + EventData::OpenbotConnect { + outcome: ConnectOutcome::Completed, + duration_ms, + .. + } => *duration_ms, + _ => None, + }); + assert!(took.is_some_and(|ms| ms >= 400), "{:?}", queued(shell)); + vec![ + EventData::OpenbotConnect { + screen: ConnectScreen::ConnectOpenbot, + outcome: ConnectOutcome::Started, + duration_ms: None, + }, + EventData::OpenbotConnect { + screen: ConnectScreen::ConnectOpenbot, + outcome: ConnectOutcome::Completed, + duration_ms: took, + }, + ] + } + + /// Once setup ended with a connection (the choice on record is connected), every launch and + /// every first screen shown again is counted and starts no setup session: here a launch that + /// opens that OpenBot, and a Sign in again or a Change from Settings (the same view). Neither a + /// quit nor a crash then says `setup_abandoned`, at once or at the next launch, also after a + /// Sign in again that started and failed. With no connection on record the same launch and + /// screens are a first setup, which a quit or a crash abandons at the last step. Choosing + /// OpenBot (Self-Contained) on the screen shown again (`use_this_computer`) starts a setup on + /// this computer at its first screen, before the window shows anything, which a quit or a crash + /// abandons; the window's own first view then is not counted twice. + /// + /// Each launch goes through `open_then_launch`, as `initialize` does, the window's events are + /// its own JSON (`App.tsx`, `useConnectToOpenBot`; pinned in `App.test.tsx`), and what is kept + /// is checked as the quit or the crash leaves it, then after the next launch of an app on the + /// same files and the `connection.json` the last run kept. + #[test] + fn a_first_screen_shown_again_after_a_connection_is_not_abandoned_on_quit_or_crash() { + use openbot_desktop_lib::telemetry::{ConnectOutcome, ConnectScreen, EventData, Step}; + let viewed = |step: &str| serde_json::json!({ "kind": "step_viewed", "step": step }); + let started = serde_json::json!({ + "kind": "openbot_connect", "screen": "connect_openbot", "outcome": "started" + }); + let failed = serde_json::json!({ + "kind": "openbot_connect", "screen": "connect_openbot", "outcome": "failed", + "duration_ms": 9000 + }); + let step = |step| EventData::StepViewed { step }; + let connect = |outcome, duration_ms| EventData::OpenbotConnect { + screen: ConnectScreen::ConnectOpenbot, + outcome, + duration_ms, + }; + struct Case { + connected: bool, + window: Vec, + /// This computer chosen, then the window's first local view or none before the exit. + this_computer: Option, + recorded: Vec, + abandoned: Option, + } + let shown_again_then_this_computer = vec![ + step(Step::Welcome), + step(Step::ConnectOpenbot), + step(Step::Welcome), + ]; + let cases = [ + // A launch that opens the OpenBot it is connected to: no setup screen at all. + Case { + connected: true, + window: vec![], + this_computer: None, + recorded: vec![step(Step::Welcome)], + abandoned: None, + }, + // Sign in again, or Change from Settings. + Case { + connected: true, + window: vec![viewed("connect_openbot")], + this_computer: None, + recorded: vec![step(Step::Welcome), step(Step::ConnectOpenbot)], + abandoned: None, + }, + Case { + connected: true, + window: vec![viewed("connect_openbot"), started.clone(), failed.clone()], + this_computer: None, + recorded: vec![ + step(Step::Welcome), + step(Step::ConnectOpenbot), + connect(ConnectOutcome::Started, None), + connect(ConnectOutcome::Failed, Some(9000)), + ], + abandoned: None, + }, + Case { + connected: true, + window: vec![viewed("connect_openbot")], + this_computer: Some(true), + recorded: shown_again_then_this_computer.clone(), + abandoned: Some(Step::Welcome), + }, + // Quit on "Checking your saved setup…", or behind a Windows blocker: no local view yet. + Case { + connected: true, + window: vec![viewed("connect_openbot")], + this_computer: Some(false), + recorded: shown_again_then_this_computer, + abandoned: Some(Step::Welcome), + }, + // A first setup. + Case { + connected: false, + window: vec![viewed("welcome")], + this_computer: None, + recorded: vec![step(Step::Welcome)], + abandoned: Some(Step::Welcome), + }, + Case { + connected: false, + window: vec![viewed("connect_openbot"), started, failed], + this_computer: None, + recorded: vec![ + step(Step::Welcome), + step(Step::ConnectOpenbot), + connect(ConnectOutcome::Started, None), + connect(ConnectOutcome::Failed, Some(9000)), + ], + abandoned: Some(Step::ConnectOpenbot), + }, + ]; + for case in cases { + for crash in [false, true] { + let data = temp_root("openbot-shown-again-telemetry"); + let shell = launched_with_usage_data(case.connected, &data); + for event in &case.window { + window_says(&shell, event); + } + if let Some(then_viewed) = case.this_computer { + assert_eq!(shell.ask(SETUP, "use_this_computer"), Ok(serde_json::Value::Null)); + if then_viewed { + window_says(&shell, &viewed("welcome")); + } + } + let what = format!( + "connected {}, window {:?}, this computer {:?}, crash {crash}", + case.connected, case.window, case.this_computer + ); + let abandoned: Vec = case + .abandoned + .map(|step| EventData::SetupAbandoned { step }) + .into_iter() + .collect(); + // As the quit or the crash leaves it. + let mut left = case.recorded.clone(); + if !crash { + desktop_telemetry::shutdown(shell.handle()); + left.extend(abandoned.clone()); + } + assert_eq!(queued(&shell), left, "{what}: on exit"); + // The next launch, of an app on the same files and the choice the last run kept + // (this computer once This computer was chosen): an abandonment the quit said is + // not said again, and a crash's is said once. + assert_eq!( + choice::read(&shell.config).mode == choice::Mode::Connected, + case.connected && case.this_computer.is_none(), + "{what}: the choice kept" + ); + let next = relaunched(&shell, &data); + let mut expected = case.recorded.clone(); + expected.extend(abandoned); + expected.push(step(Step::Welcome)); + assert_eq!(queued(&next), expected, "{what}: next launch"); + drop(shell); + drop(next); + let _ = std::fs::remove_dir_all(&data); + } + } + } + + /// A connected app whose last run left a setup session open (an earlier version, which started + /// one at every launch, then a crash): its first launch with the connection on record closes + /// that session as it opens its usage data, and queues no `setup_abandoned` for it. With no + /// connection on record the same run is a first setup the crash abandoned, and it is still + /// said, once. + #[test] + fn a_connected_launch_closes_the_session_an_earlier_crash_left() { + use openbot_desktop_lib::telemetry::{EventData, Step}; + for connected in [true, false] { + let data = temp_root("openbot-earlier-crash-telemetry"); + // The earlier version: its launch started a setup session, then the app crashed. + { + let earlier = desktop_telemetry::DesktopTelemetry::for_tests(data.clone(), true); + earlier.record_for_test(EventData::StepViewed { + step: Step::Welcome, + }); + } + let next = launched_with_usage_data(connected, &data); + let mut expected = vec![EventData::StepViewed { + step: Step::Welcome, + }]; + if !connected { + expected.push(EventData::SetupAbandoned { + step: Step::Welcome, + }); + } + expected.push(EventData::StepViewed { + step: Step::Welcome, + }); + assert_eq!(queued(&next), expected, "connected {connected}"); + desktop_telemetry::shutdown(next.handle()); + assert_eq!( + queued(&next).last(), + Some(&if connected { + EventData::StepViewed { + step: Step::Welcome, + } + } else { + EventData::SetupAbandoned { + step: Step::Welcome, + } + }), + "connected {connected}: quit" + ); + drop(next); + let _ = std::fs::remove_dir_all(&data); + } + } + + /// Move to Cloud from an OpenBot on this computer whose activation was never recorded (usage + /// data was off when it started): the connection it keeps ends the setup session this launch + /// opened, though the move says no `openbot_connect`, so neither the quit nor the next launch + /// says `setup_abandoned`. The move keeps it through `keep_moved_choice` once it is saved + /// (`ThisComputer::moved`), which is called here directly. + #[test] + fn a_connection_kept_by_move_to_cloud_ends_the_setup_session() { + use openbot_desktop_lib::telemetry::{EventData, Step}; + let data = temp_root("openbot-moved-telemetry"); + let shell = launched_with_usage_data(false, &data); + desktop_connected::keep_moved_choice(shell.handle(), ADDRESS, "org_moved").unwrap(); + let welcome = EventData::StepViewed { + step: Step::Welcome, + }; + quit_and_relaunch_without_abandonment(shell, &data, vec![welcome], "moved"); + } + + /// A first launch's Connect through the relay, from the first screen: the connection it keeps + /// ends the setup session the launch opened, whether or not the window named its screen (it + /// always does today, and only then is it counted `completed`; without it, keeping the + /// connection alone ends the session), so neither the quit nor the next launch says + /// `setup_abandoned`. + #[test] + fn a_first_launchs_connect_through_the_relay_ends_setup_so_its_quit_is_not_abandoned() { + use openbot_desktop_lib::telemetry::{EventData, Step}; + for named in [true, false] { + let data = temp_root("openbot-relay-connect-telemetry"); + let address = window_stand_in(WindowStand::new(false)); + let shell = launched_with_usage_data(false, &data); + let (_browser, _opened) = approving_browser(); + window_says( + &shell, + &serde_json::json!({ "kind": "step_viewed", "step": "connect_openbot" }), + ); + let connected = connect_from_the_first_screen(&shell, &address, named); + assert!(desktop_connected::relay_origin(shell.handle()).is_some()); + assert_eq!( + choice::read(&shell.config).connected_to(), + Some(address.as_str()), + "named {named}: the choice kept" + ); + let mut shown = vec![ + EventData::StepViewed { + step: Step::Welcome, + }, + EventData::StepViewed { + step: Step::ConnectOpenbot, + }, + ]; + shown.extend(connected); + quit_and_relaunch_without_abandonment(shell, &data, shown, &format!("named {named}")); + } + } + + /// What put the first screen up again, the choice on record still connected. + #[derive(Clone, Copy, Debug)] + enum ShownAgainBy { + /// A sign-in that ended while OpenBot showed (`session_ended`, which puts setup back). + EndedSignIn, + /// A saved OpenBot that cannot be reached (`show_connected`, asked by the window, failing). + Unreachable, + /// Sign out, from a menu or the setup window (`sign_out_of_openbot`): the sign-in is + /// forgotten and the address kept. + SignOut, + /// Settings' Change while connected (`change_connection_now`): signed out, and setup asked + /// to open at the choice of where OpenBot runs. + SettingsChange, + } + + /// The first screen shown again by the desktop itself (`by`), then said by the window. None of + /// these changes the choice on record, so the screen is counted and starts no setup session: + /// no `setup_abandoned` on quit, or at the next launch. + fn shown_again_by_the_desktop_is_not_abandoned(by: ShownAgainBy) { + use openbot_desktop_lib::telemetry::{EventData, Step}; + // An address where nothing answers: a loopback port just closed. + let unreachable = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + format!("http://{}", listener.local_addr().unwrap()) + }; + let address = match by { + ShownAgainBy::EndedSignIn => ADDRESS.to_owned(), + ShownAgainBy::Unreachable | ShownAgainBy::SignOut | ShownAgainBy::SettingsChange => { + unreachable + } + }; + let data = temp_root("openbot-shown-again-by-the-desktop"); + let shell = launched_connected_to(Some(&address), &data); + match by { + ShownAgainBy::EndedSignIn => { + desktop_connected::session_ended(shell.handle(), "openbot.example.com"); + } + ShownAgainBy::Unreachable => { + let refused = shell.ask(SETUP, "show_connected").unwrap_err(); + assert_eq!(refused["kind"], "unreachable", "{refused}"); + } + ShownAgainBy::SignOut | ShownAgainBy::SettingsChange => { + // Nothing answers there, so no browser is sent to end a session at it. + let opened = Arc::new(Mutex::new(Vec::::new())); + let noting = opened.clone(); + let _browser = desktop_connected::use_browser_for_test(move |to: &str| { + noting.lock().unwrap().push(to.to_owned()); + Ok(()) + }); + shell + .store + .set(&address, &format!("obr_saved{}", "s".repeat(32))) + .unwrap(); + if matches!(by, ShownAgainBy::SignOut) { + assert_eq!( + shell.ask(SETUP, "sign_out_of_openbot"), + Ok(serde_json::Value::Null) + ); + } else { + desktop_connected::change_connection_now(shell.handle()).unwrap(); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::json!({ "kind": "choose", "message": null })) + ); + } + assert_eq!(shell.store.get(&address).unwrap(), None, "signed out"); + assert_eq!(shell.window.url().unwrap().as_str(), SETUP); + assert_eq!(*opened.lock().unwrap(), Vec::::new()); + } + } + window_says( + &shell, + &serde_json::json!({ "kind": "step_viewed", "step": "connect_openbot" }), + ); + assert_eq!( + choice::read(&shell.config).connected_to(), + Some(address.as_str()), + "{by:?}: the choice kept" + ); + let shown = vec![ + EventData::StepViewed { + step: Step::Welcome, + }, + EventData::StepViewed { + step: Step::ConnectOpenbot, + }, + ]; + quit_and_relaunch_without_abandonment(shell, &data, shown, &format!("{by:?}")); + } + + /// A sign-in that ends while OpenBot shows keeps the connection: Sign in again, shown then, is + /// not abandoned on quit or at the next launch. + #[test] + fn a_first_screen_shown_again_by_an_ended_sign_in_is_not_abandoned() { + shown_again_by_the_desktop_is_not_abandoned(ShownAgainBy::EndedSignIn); + } + + /// A saved OpenBot that cannot be reached keeps the connection: the screen that says so is not + /// abandoned on quit or at the next launch. + #[test] + fn a_first_screen_shown_again_by_an_unreachable_openbot_is_not_abandoned() { + shown_again_by_the_desktop_is_not_abandoned(ShownAgainBy::Unreachable); + } + + /// Sign out keeps the address, so the choice stays connected: Sign in again, shown then, is not + /// abandoned on quit or at the next launch. + #[test] + fn a_first_screen_shown_again_by_a_sign_out_is_not_abandoned() { + shown_again_by_the_desktop_is_not_abandoned(ShownAgainBy::SignOut); + } + + /// Settings' Change while connected signs out and keeps the address, so the choice stays + /// connected: the first screen it opens is not abandoned on quit or at the next launch. + #[test] + fn a_first_screen_shown_again_by_settings_change_is_not_abandoned() { + shown_again_by_the_desktop_is_not_abandoned(ShownAgainBy::SettingsChange); + } + + /// A setup failure is said at the last screen shown, a screen shown once setup ended with a + /// connection included, though that screen starts no setup session, and also after an + /// organization switch, which keeps the connection with no setup session open. Which part + /// failed is arbitrary here: the test is about where the failure is placed. + #[test] + fn a_setup_failure_after_a_screen_shown_again_names_that_screen() { + use openbot_desktop_lib::telemetry::{EventData, FailingStep, SetupErrorClass, Step}; + let data = temp_root("openbot-shown-again-failure"); + let shell = launched_with_usage_data(true, &data); + window_says( + &shell, + &serde_json::json!({ "kind": "step_viewed", "step": "connect_openbot" }), + ); + desktop_connected::set_organization_now(shell.handle(), Some("org_switched".into())) + .unwrap(); + desktop_telemetry::setup_failed( + shell.handle(), + desktop_telemetry::SetupFailure::new( + FailingStep::LocalStart, + SetupErrorClass::NetworkUnavailable, + ), + ); + assert!( + matches!( + queued(&shell).last(), + Some(EventData::SetupFailed { + step: Step::ConnectOpenbot, + .. + }) + ), + "{:?}", + queued(&shell) + ); + drop(shell); + let _ = std::fs::remove_dir_all(&data); + } + /// OpenBot's page, served through the relay, may ask where it runs, sign out, change the /// connection and name the organisation. A page on another loopback port may not. #[test] diff --git a/desktop/src-tauri/src/desktop_connected.rs b/desktop/src-tauri/src/desktop_connected.rs index 65943c7fa3..6b2d4c2a7a 100644 --- a/desktop/src-tauri/src/desktop_connected.rs +++ b/desktop/src-tauri/src/desktop_connected.rs @@ -152,6 +152,14 @@ fn keep( let written = config_dir(app) .ok_or_else(|| "the app has no configuration folder".to_owned()) .and_then(|dir| choice::write(&dir, chosen).map_err(|error| error.to_string())); + // Connected is first kept once a connection worked, or once the window's own sign-in came + // back from the browser: setup on this computer ended with it, whether or not the connection + // was counted (`openbot_connect` `completed`, Move to Cloud). An organization switch + // (`set_organization_now`) and a window sign-in let go (`forget_window_sign_in`) keep a choice + // that was already connected, so setup had already ended, and ending it again changes nothing. + if written.is_ok() && chosen.mode == choice::Mode::Connected { + crate::desktop_telemetry::setup_ended(app); + } written.map_err(|detail| { Problem::with( "OpenBot couldn't save your choice on this computer. Try again.", @@ -189,6 +197,19 @@ pub fn shown_origin(app: &tauri::AppHandle) -> Option(app: &tauri::AppHandle) -> bool { + app.try_state::().is_some() && chosen(app).mode == choice::Mode::Connected +} + /// The relay's origin, `http://127.0.0.1:`, while the window shows OpenBot through it. pub fn relay_origin(app: &tauri::AppHandle) -> Option { #[cfg(test)] @@ -730,7 +751,8 @@ pub async fn sign_out_of_openbot( } /// Back to OpenBot on this computer: signed out, the choice switched, and the setup window, which -/// carries on as it does for an installation here. +/// carries on as it does for an installation here. A setup starts at its first screen, as at a +/// first launch (`desktop_telemetry::launched`), so a quit before `activated` is `setup_abandoned`. #[tauri::command] pub async fn use_this_computer(app: tauri::AppHandle) -> Result<(), Problem> { blocking(move || { @@ -740,6 +762,8 @@ pub async fn use_this_computer(app: tauri::AppHandle) -> R chosen.organization_id = None; keep(&app, &chosen)?; log::info!("[connect] the choice is OpenBot on this computer"); + // A setup starts here, from the first screen, as at a first launch. + crate::desktop_telemetry::launched(&app); crate::refresh_menus(&app); crate::show_setup(app).map_err(Problem::from) }) diff --git a/desktop/src-tauri/src/desktop_telemetry.rs b/desktop/src-tauri/src/desktop_telemetry.rs index f1b0b8749f..949294547a 100644 --- a/desktop/src-tauri/src/desktop_telemetry.rs +++ b/desktop/src-tauri/src/desktop_telemetry.rs @@ -85,6 +85,12 @@ impl DesktopTelemetry { .unwrap_or_default() } + /// `data` saved as an earlier run of the app saved it, with nothing sent. + #[cfg(test)] + pub(crate) fn record_for_test(&self, data: telemetry::EventData) { + self.emitter.record(data).unwrap(); + } + /// An emitter in `data_dir`, sharing or not, for tests that drive the app's commands. #[cfg(test)] pub(crate) fn for_tests(data_dir: std::path::PathBuf, sharing: bool) -> Self { @@ -130,24 +136,47 @@ pub fn initialize(app: &tauri::AppHandle) { .map(|directory| usage_data::saved(&directory)) .unwrap_or(true); usage_data::set_off(!shared); + open_then_launch( + app, + app.path() + .app_local_data_dir() + .ok() + .map(|directory| directory.join("telemetry")), + Some( + std::env::var("COPILOTKIT_TELEMETRY_URL") + .unwrap_or_else(|_| "https://telemetry.copilotkit.ai/ingest".into()), + ), + if shared { + telemetry::EnvOverride::Process + } else { + telemetry::EnvOverride::Disabled + }, + ); +} + +/// The emitter opened in `data_dir`, sending to `endpoint`, knowing whether setup already ended +/// with a connection, then this launch's first screen (`first_screen`, by the same reading). +fn open_then_launch( + app: &tauri::AppHandle, + data_dir: Option, + endpoint: Option, + env_override: telemetry::EnvOverride, +) { + // Read before the state is opened: a setup session the last run left open is then closed, or + // said abandoned, in the one write that opens it. + let setup_ended = crate::desktop_connected::setup_ended_with_connection(app); let initialized = (|| { let context = context(&app.package_info().version.to_string())?; - let emitter = telemetry::Telemetry::open_with_env( - app.path().app_local_data_dir().ok()?.join("telemetry"), + let emitter = telemetry::Telemetry::open_with_setup( + data_dir?, context, telemetry::Config { enabled: true, - endpoint: Some( - std::env::var("COPILOTKIT_TELEMETRY_URL") - .unwrap_or_else(|_| "https://telemetry.copilotkit.ai/ingest".into()), - ), + endpoint, max_queue: 256, }, - if shared { - telemetry::EnvOverride::Process - } else { - telemetry::EnvOverride::Disabled - }, + env_override, + setup_ended, ) .ok()?; app.manage(DesktopTelemetry::new(emitter)); @@ -157,14 +186,46 @@ pub fn initialize(app: &tauri::AppHandle) { log::warn!("[telemetry] local setup telemetry could not initialize"); return; } - record( + // The same reading of the choice that opened the state: one decision for the launch. + first_screen(app, setup_ended); +} + +/// `initialize` as the app runs it, sharing, in `data_dir` and sending nowhere: for tests of a +/// launch. +#[cfg(test)] +pub(crate) fn initialize_for_test( + app: &tauri::AppHandle, + data_dir: std::path::PathBuf, +) { + open_then_launch(app, Some(data_dir), None, telemetry::EnvOverride::Enabled); +} + +/** +The first screen viewed when OpenBot (Self-Contained) is chosen once connected +(`desktop_connected::use_this_computer`), before the window has shown anything, as a launch views +it (`open_then_launch`, through `first_screen`). Once setup ended with a connection to an OpenBot +that runs elsewhere (`desktop_connected::setup_ended_with_connection`), that view starts no setup +session, so a launch that opens that OpenBot, or shows the first screen to sign in again, and is +then quit is not `setup_abandoned`. `use_this_computer` calls it once the choice is this computer, +so there it starts a setup, and a quit before the window shows anything abandons it. +*/ +pub fn launched(app: &tauri::AppHandle) { + first_screen( app, - telemetry::EventData::StepViewed { - step: telemetry::Step::Welcome, - }, + crate::desktop_connected::setup_ended_with_connection(app), ); } +/// `launched`, with whether setup already ended as already read. +fn first_screen(app: &tauri::AppHandle, setup_ended: bool) { + let step = telemetry::Step::Welcome; + if setup_ended { + record_step_after_setup(app, step); + } else { + record(app, telemetry::EventData::StepViewed { step }); + } +} + fn context(version: &str) -> Option { use telemetry::{ AppVersion, Architecture, Distribution, Engine, NumericVersion, Platform, RuntimeEnv, @@ -517,10 +578,38 @@ fn link_account_unlocked( } pub fn record(app: &tauri::AppHandle, event: telemetry::EventData) { + saved_then_sent(app, |emitter| emitter.record(event)); +} + +/// Setup ended with a connection the app now keeps (`desktop_connected::keep`): the open setup +/// session closes without a `setup_abandoned` (`Telemetry::end_setup_session`). +pub fn setup_ended(app: &tauri::AppHandle) { + let Some(state) = app.try_state::() else { + return; + }; + if state.emitter.end_setup_session().is_err() { + log::warn!("[telemetry] the setup session could not be closed"); + } +} + +/// A setup step shown again once setup ended with a connection +/// (`Telemetry::record_step_after_setup`). +pub fn record_step_after_setup( + app: &tauri::AppHandle, + step: telemetry::Step, +) { + saved_then_sent(app, |emitter| emitter.record_step_after_setup(step)); +} + +/// An event saved by `save`, then sent in the background. +fn saved_then_sent( + app: &tauri::AppHandle, + save: impl FnOnce(&telemetry::Telemetry) -> telemetry::Result<()>, +) { let Some(state) = app.try_state::() else { return; }; - if state.emitter.record(event).is_err() { + if save(&state.emitter).is_err() { log::warn!("[telemetry] setup event could not be saved"); return; } @@ -613,9 +702,9 @@ pub fn setup_failed(app: &tauri::AppHandle, failure: Setup state.failures.fetch_add(1, Ordering::SeqCst); let step = state .emitter - .snapshot() + .last_step_shown() .ok() - .and_then(|state| state.last_step) + .flatten() .unwrap_or(telemetry::Step::Install); record(app, failure.event(step)); } diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 8c3130ac48..5f67f394b0 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -1961,7 +1961,16 @@ fn record_setup_event(app: tauri::AppHandle, event: serde_ }), ) = serde_json::from_value(event) { - desktop_telemetry::record(&app, event); + match event { + // Setup already ended with a connection: a step it shows is counted, and a quit there + // is not `setup_abandoned`. + telemetry::EventData::StepViewed { step } + if desktop_connected::setup_ended_with_connection(&app) => + { + desktop_telemetry::record_step_after_setup(&app, step); + } + event => desktop_telemetry::record(&app, event), + } } } diff --git a/desktop/src-tauri/src/telemetry.rs b/desktop/src-tauri/src/telemetry.rs index bf3349c8bf..b029755d5c 100644 --- a/desktop/src-tauri/src/telemetry.rs +++ b/desktop/src-tauri/src/telemetry.rs @@ -105,6 +105,9 @@ pub struct Telemetry { config: Config, state: Mutex>, session_last_step_viewed: Mutex>, + /// The last setup screen shown, whether or not it started a setup session: where a setup + /// failure happened (`last_step_shown` says when it is cleared). + last_step_shown: Mutex>, flush_lock: Mutex<()>, client: Client, /// What this launch found about the version that ran before it, for `observe_launch` once. @@ -198,6 +201,22 @@ impl Telemetry { context: Context, config: Config, env_override: EnvOverride, + ) -> Result> { + Self::open_with_setup(data_dir, context, config, env_override, false) + } + + /** + `open_with_env`, knowing whether setup already ended before this launch (a connection to an + OpenBot that runs elsewhere is kept). A setup session the last run left open (a crash, or an + earlier version, which started one at every launch) is then closed without a + `setup_abandoned`, in the same write that opens the state, so nothing false is ever queued. + */ + pub fn open_with_setup( + data_dir: impl AsRef, + context: Context, + config: Config, + env_override: EnvOverride, + setup_ended: bool, ) -> Result> { let state_path = state_path(data_dir.as_ref()); if telemetry_disabled(env_override) || !config.enabled { @@ -232,10 +251,12 @@ impl Telemetry { if !state.activated { if let Some(step) = state.last_step.take() { - state.push_bounded( - Event::new(EventData::SetupAbandoned { step }, context.clone()), - normalized_max_queue(config.max_queue), - ); + if !setup_ended { + state.push_bounded( + Event::new(EventData::SetupAbandoned { step }, context.clone()), + normalized_max_queue(config.max_queue), + ); + } } } // An update the last launch started ends here: this launch is the version it was moving to, @@ -257,6 +278,7 @@ impl Telemetry { config, state: Mutex::new(Some(state)), session_last_step_viewed: Mutex::new(None), + last_step_shown: Mutex::new(None), flush_lock: Mutex::new(()), client: client()?, launch: Mutex::new(Some(LaunchSeen { @@ -350,6 +372,7 @@ impl Telemetry { config, state: Mutex::new(None), session_last_step_viewed: Mutex::new(None), + last_step_shown: Mutex::new(None), flush_lock: Mutex::new(()), client: client()?, launch: Mutex::new(None), @@ -394,6 +417,14 @@ impl Telemetry { pub fn stop_sharing(&self) -> Result<()> { let mut guard = self.state.lock().map_err(|_| TelemetryError::Poisoned)?; *guard = None; + // Nothing from before the opt-out names a step for what is said after it. A poisoned lock + // never stops the state file being deleted. + if let Ok(mut shown) = self.last_step_shown.lock() { + *shown = None; + } + if let Ok(mut viewed) = self.session_last_step_viewed.lock() { + *viewed = None; + } match fs::remove_file(&self.state_path) { Ok(()) => Ok(()), Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), @@ -486,6 +517,22 @@ impl Telemetry { } pub fn record(&self, data: EventData) -> Result<()> { + self.record_in_setup(data, true) + } + + /** + A setup screen shown once setup has already ended on this computer, with a connection to an + OpenBot that runs elsewhere on record: each launch's first screen, a sign-in that ended (Sign in + again), or the choice of where OpenBot runs asked for again from Settings. `step_viewed` as any + other, but it starts no setup session, so a quit there is not `setup_abandoned`, on quit or at + the next launch. + */ + pub fn record_step_after_setup(&self, step: Step) -> Result<()> { + self.record_in_setup(EventData::StepViewed { step }, false) + } + + /// `starts_setup`: a `step_viewed` is the step a quit before activation abandons. + fn record_in_setup(&self, data: EventData, starts_setup: bool) -> Result<()> { let context = self .context .lock() @@ -524,15 +571,29 @@ impl Telemetry { match &data { EventData::StepViewed { step } => { + *self + .last_step_shown + .lock() + .map_err(|_| TelemetryError::Poisoned)? = Some(*step); + // A screen shown after setup ended, then the same screen starting a setup + // (defensive: no current window flow puts these two side by side): the setup + // starts even though the view is not said twice. + let starts = starts_setup && state.last_step != Some(*step); + if starts { + state.last_step = Some(*step); + } let mut last_step = self .session_last_step_viewed .lock() .map_err(|_| TelemetryError::Poisoned)?; if *last_step == Some(*step) { - return Ok(()); + return if starts { + write_state(&self.state_path, state) + } else { + Ok(()) + }; } *last_step = Some(*step); - state.last_step = Some(*step); } EventData::Activated => { if state.activated { @@ -540,6 +601,10 @@ impl Telemetry { } state.activated = true; state.last_step = None; + *self + .last_step_shown + .lock() + .map_err(|_| TelemetryError::Poisoned)? = None; *self .session_last_step_viewed .lock() @@ -552,6 +617,10 @@ impl Telemetry { return Ok(()); } state.last_step = None; + *self + .last_step_shown + .lock() + .map_err(|_| TelemetryError::Poisoned)? = None; *self .session_last_step_viewed .lock() @@ -564,6 +633,10 @@ impl Telemetry { .. } => { state.last_step = None; + *self + .last_step_shown + .lock() + .map_err(|_| TelemetryError::Poisoned)? = None; *self .session_last_step_viewed .lock() @@ -721,6 +794,41 @@ impl Telemetry { .and_then(|state| (!state.activated).then_some(state.last_step).flatten())) } + /** + Setup ended with a connection to an OpenBot that runs elsewhere, kept by the app, whether or not + that connection was counted (`openbot_connect` `completed`): the setup session open now closes + without a `setup_abandoned`, and nothing is sent for it. With none open it changes nothing, and + the last screen shown stays (`last_step_shown`). + */ + pub fn end_setup_session(&self) -> Result<()> { + let mut guard = self.state.lock().map_err(|_| TelemetryError::Poisoned)?; + let Some(state) = guard.as_mut() else { + return Ok(()); + }; + if state.activated || state.last_step.take().is_none() { + return Ok(()); + } + *self + .last_step_shown + .lock() + .map_err(|_| TelemetryError::Poisoned)? = None; + *self + .session_last_step_viewed + .lock() + .map_err(|_| TelemetryError::Poisoned)? = None; + write_state(&self.state_path, state) + } + + /// The last setup screen shown, whether or not it started a setup session: where a setup + /// failure is said to have happened. Setup ending clears it, and a kept connection only when + /// it closes an open setup session (`end_setup_session`). + pub fn last_step_shown(&self) -> Result> { + Ok(*self + .last_step_shown + .lock() + .map_err(|_| TelemetryError::Poisoned)?) + } + pub fn shutdown(&self) -> Result<()> { if let Some(step) = self.setup_step()? { self.record(EventData::SetupAbandoned { step })?; @@ -3528,6 +3636,434 @@ mod tests { } } + /// The first screen shown again once setup ended with a connection (`record_step_after_setup`): + /// a later launch's Sign in again, or the choice asked for again from Settings. It is counted + /// as `step_viewed`, and a quit there is not `setup_abandoned`, after a Sign in again that only + /// started and failed or was cancelled too, neither on quit nor at the next launch. The same + /// screens in a first setup still are. Never `activated`. + #[test] + fn a_step_shown_again_after_setup_is_counted_and_a_quit_there_is_not_abandonment() { + let connect = |outcome| EventData::OpenbotConnect { + screen: ConnectScreen::ConnectOpenbot, + outcome, + duration_ms: None, + }; + for (after_setup, step, then, abandoned) in [ + (true, Step::ConnectOpenbot, vec![], vec![]), + ( + true, + Step::ConnectOpenbot, + vec![connect(ConnectOutcome::Started)], + vec![], + ), + ( + true, + Step::ConnectOpenbot, + vec![ + connect(ConnectOutcome::Started), + connect(ConnectOutcome::Failed), + ], + vec![], + ), + ( + true, + Step::ConnectOpenbot, + vec![ + connect(ConnectOutcome::Started), + connect(ConnectOutcome::Cancelled), + ], + vec![], + ), + (true, Step::Welcome, vec![], vec![]), + (false, Step::Welcome, vec![], vec![Step::Welcome]), + ( + false, + Step::ConnectOpenbot, + vec![], + vec![Step::ConnectOpenbot], + ), + ( + false, + Step::ConnectOpenbot, + vec![ + connect(ConnectOutcome::Started), + connect(ConnectOutcome::Failed), + ], + vec![Step::ConnectOpenbot], + ), + ( + false, + Step::ConnectOpenbot, + vec![ + connect(ConnectOutcome::Started), + connect(ConnectOutcome::Cancelled), + ], + vec![Step::ConnectOpenbot], + ), + ] { + let dir = temp_dir("shown-again-then-quit"); + let open = || { + Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap() + }; + let telemetry = open(); + if after_setup { + telemetry.record_step_after_setup(step).unwrap(); + } else { + telemetry.record(EventData::StepViewed { step }).unwrap(); + } + for event in &then { + telemetry.record(event.clone()).unwrap(); + } + let case = format!("after setup {after_setup}, {step:?}, then {then:?}"); + assert_eq!( + telemetry.snapshot().unwrap().queue[0].data, + EventData::StepViewed { step }, + "{case}: counted" + ); + telemetry.shutdown().unwrap(); + drop(telemetry); + // The next launch reads what the quit left: it says nothing more. + let queue = open().snapshot().unwrap().queue; + let abandoned_at: Vec = queue + .iter() + .filter_map(|event| match event.data { + EventData::SetupAbandoned { step } => Some(step), + _ => None, + }) + .collect(); + assert_eq!(abandoned_at, abandoned, "{case}"); + assert!( + !queue + .iter() + .any(|event| matches!(event.data, EventData::Activated)), + "{case}" + ); + } + } + + /// A screen shown after setup ended, then the same screen starting a setup on this computer: + /// counted once, as any view said twice in a row, and the setup it starts is still abandoned by + /// a quit, or by the next launch after a crash. Where a setup failure happened is the last + /// screen shown either way, until setup ends. With usage data off, nothing is recorded or kept. + #[test] + fn a_step_shown_after_setup_then_starting_one_is_counted_once_and_abandoned() { + let dir = temp_dir("shown-after-then-starting"); + let telemetry = Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + telemetry.record_step_after_setup(Step::Welcome).unwrap(); + assert_eq!(telemetry.last_step_shown().unwrap(), Some(Step::Welcome)); + assert_eq!(telemetry.snapshot().unwrap().last_step, None); + telemetry + .record(EventData::StepViewed { + step: Step::Welcome, + }) + .unwrap(); + assert_eq!( + telemetry.snapshot().unwrap().last_step, + Some(Step::Welcome), + "the setup started" + ); + telemetry.shutdown().unwrap(); + let queue: Vec = telemetry + .snapshot() + .unwrap() + .queue + .into_iter() + .map(|event| event.data) + .collect(); + assert_eq!( + queue, + vec![ + EventData::StepViewed { + step: Step::Welcome + }, + EventData::SetupAbandoned { + step: Step::Welcome + }, + ] + ); + assert_eq!(telemetry.last_step_shown().unwrap(), None, "setup ended"); + + // The same two views, then a crash: the setup they started is saved, so the next launch + // says it abandoned. + let crash_dir = temp_dir("shown-after-then-starting-crash"); + let crashed = Telemetry::open_with_env( + &crash_dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + crashed.record_step_after_setup(Step::Welcome).unwrap(); + crashed + .record(EventData::StepViewed { + step: Step::Welcome, + }) + .unwrap(); + drop(crashed); + let next_launch = Telemetry::open_with_env( + &crash_dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + let queue: Vec = next_launch + .snapshot() + .unwrap() + .queue + .into_iter() + .map(|event| event.data) + .collect(); + assert_eq!( + queue, + vec![ + EventData::StepViewed { + step: Step::Welcome + }, + EventData::SetupAbandoned { + step: Step::Welcome + }, + ] + ); + + let shown = Telemetry::open_with_env( + temp_dir("shown-after-then-connected"), + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + shown.record_step_after_setup(Step::ConnectOpenbot).unwrap(); + assert_eq!(shown.last_step_shown().unwrap(), Some(Step::ConnectOpenbot)); + shown + .record(EventData::OpenbotConnect { + screen: ConnectScreen::ConnectOpenbot, + outcome: ConnectOutcome::Completed, + duration_ms: None, + }) + .unwrap(); + assert_eq!(shown.last_step_shown().unwrap(), None, "setup ended"); + + let off_dir = temp_dir("shown-after-off"); + let off = Telemetry::open_with_env( + &off_dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Disabled, + ) + .unwrap(); + off.record_step_after_setup(Step::ConnectOpenbot).unwrap(); + off.shutdown().unwrap(); + assert!(off.snapshot().is_err(), "nothing kept"); + assert!(!state_path(&off_dir).exists()); + } + + /// Usage data turned off then on in the same run: no step from before names a setup failure + /// after it, and the first view after it is said. + #[test] + fn a_step_shown_before_an_opt_out_names_nothing_after_it() { + let telemetry = Telemetry::open_with_env( + temp_dir("shown-then-opt-out"), + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + telemetry.record_step_after_setup(Step::Welcome).unwrap(); + telemetry.stop_sharing().unwrap(); + telemetry.resume_sharing().unwrap(); + assert_eq!(telemetry.last_step_shown().unwrap(), None); + telemetry.record_step_after_setup(Step::Welcome).unwrap(); + assert_eq!( + telemetry.snapshot().unwrap().queue[0].data, + EventData::StepViewed { + step: Step::Welcome + } + ); + } + + /// Usage data turned off deletes the saved state even when a panic poisoned the locks on the + /// last screen shown: the opt-out never leaves the file behind. + #[test] + fn an_opt_out_deletes_the_saved_state_even_with_the_step_locks_poisoned() { + let dir = temp_dir("opt-out-poisoned-steps"); + let telemetry = Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + telemetry.record_step_after_setup(Step::Welcome).unwrap(); + assert!(state_path(&dir).exists()); + let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _shown = telemetry.last_step_shown.lock().unwrap(); + let _viewed = telemetry.session_last_step_viewed.lock().unwrap(); + panic!("a panic while the step locks are held"); + })); + assert!(poisoned.is_err()); + assert!(telemetry.last_step_shown.is_poisoned()); + assert!(telemetry.session_last_step_viewed.is_poisoned()); + telemetry.stop_sharing().unwrap(); + assert!(!state_path(&dir).exists(), "the opt-out deleted the state"); + } + + /// A launch that knows setup already ended (a connection kept) closes the setup session the + /// last run left open (a crash) without a `setup_abandoned`, in the write that opens the state: + /// nothing is queued for it, so nothing is pushed out of a full queue, and what was queued + /// before, an abandonment an earlier quit said included, stays as it was. A launch that does + /// not know it still says the crash's abandonment, once. + #[test] + fn a_launch_after_setup_ended_closes_the_last_runs_session_without_abandoning_it() { + for setup_ended in [true, false] { + let dir = temp_dir("open-after-setup-ended"); + let config = Config { + enabled: true, + endpoint: None, + max_queue: 3, + }; + let open = |setup_ended| { + Telemetry::open_with_setup( + &dir, + context("1.2.3", Engine::None), + config.clone(), + EnvOverride::Enabled, + setup_ended, + ) + .unwrap() + }; + let earlier = open(false); + earlier + .record(EventData::StepViewed { + step: Step::Install, + }) + .unwrap(); + earlier.shutdown().unwrap(); + earlier + .record(EventData::StepViewed { + step: Step::Welcome, + }) + .unwrap(); + drop(earlier); + let kept: Vec = open(setup_ended) + .snapshot() + .unwrap() + .queue + .into_iter() + .map(|event| event.data) + .collect(); + let mut expected = vec![ + EventData::StepViewed { + step: Step::Install, + }, + EventData::SetupAbandoned { + step: Step::Install, + }, + EventData::StepViewed { + step: Step::Welcome, + }, + ]; + if !setup_ended { + expected.remove(0); + expected.push(EventData::SetupAbandoned { + step: Step::Welcome, + }); + } + assert_eq!(kept, expected, "setup ended {setup_ended}"); + } + } + + /// A connection kept ends the setup session open now, whether or not the connection was + /// counted: no `setup_abandoned` on quit or at the next launch, and nothing sent for it. With + /// no session open, or once activated, it changes nothing, the last screen shown included. + #[test] + fn a_connection_kept_ends_the_open_setup_session_and_sends_nothing() { + let dir = temp_dir("connection-kept-ends-setup"); + let telemetry = Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + telemetry + .record(EventData::StepViewed { + step: Step::ConnectOpenbot, + }) + .unwrap(); + telemetry.end_setup_session().unwrap(); + assert_eq!(telemetry.last_step_shown().unwrap(), None); + telemetry.end_setup_session().unwrap(); + telemetry.shutdown().unwrap(); + drop(telemetry); + let queue: Vec = Telemetry::open_with_env( + &dir, + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap() + .snapshot() + .unwrap() + .queue + .into_iter() + .map(|event| event.data) + .collect(); + assert_eq!( + queue, + vec![EventData::StepViewed { + step: Step::ConnectOpenbot + }] + ); + + // Once activated, the step it keeps stays as it was. + let activated = Telemetry::open_with_env( + temp_dir("connection-kept-after-activation"), + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + activated.record(EventData::Activated).unwrap(); + activated + .record(EventData::StepViewed { step: Step::Model }) + .unwrap(); + activated.end_setup_session().unwrap(); + assert_eq!(activated.snapshot().unwrap().last_step, Some(Step::Model)); + assert_eq!(activated.last_step_shown().unwrap(), Some(Step::Model)); + + // With no session open (a screen shown once setup ended, then an organization switch), + // the last screen shown stays, so a setup failure after it is placed there. + let after_setup = Telemetry::open_with_env( + temp_dir("connection-kept-with-no-session"), + context("1.2.3", Engine::None), + Config::disabled_for_tests(), + EnvOverride::Enabled, + ) + .unwrap(); + after_setup + .record_step_after_setup(Step::ConnectOpenbot) + .unwrap(); + after_setup.end_setup_session().unwrap(); + assert_eq!(after_setup.snapshot().unwrap().last_step, None); + assert_eq!( + after_setup.last_step_shown().unwrap(), + Some(Step::ConnectOpenbot) + ); + } + #[test] fn quit_abandonment_is_not_duplicated_on_next_launch() { let dir = temp_dir("quit-reopen"); diff --git a/desktop/src-tauri/src/window_ipc_tests.rs b/desktop/src-tauri/src/window_ipc_tests.rs index 84f567eaec..122b4d2895 100644 --- a/desktop/src-tauri/src/window_ipc_tests.rs +++ b/desktop/src-tauri/src/window_ipc_tests.rs @@ -36,9 +36,9 @@ impl WindowStand { } /// An OpenBot stand-in on 127.0.0.1: the two public questions (with or without the window's -/// sign-in), the window sign-in sending the browser back with a code, Better Auth's sign-out, the -/// token endpoint for a sign-in of the app's own, and the person's organizations and email to the -/// window's session cookie only. +/// sign-in), the window sign-in and the authorization of a sign-in of the app's own each sending +/// the browser back with a code, Better Auth's sign-out, the token endpoint for a sign-in of the +/// app's own, and the person's organizations and email to the window's session cookie only. fn window_stand_in(stand: Arc>) -> String { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let address = format!("http://{}", listener.local_addr().unwrap()); @@ -105,7 +105,7 @@ fn window_stand_in(stand: Arc>) -> String { } (200, None, metadata.to_string()) } - ("GET", "/api/auth/window/sign-in") => { + ("GET", "/api/auth/window/sign-in" | "/api/auth/oauth2/authorize") => { let asked: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); let mut back = reqwest::Url::parse(&asked["redirect_uri"]).unwrap(); @@ -739,3 +739,96 @@ fn an_older_openbot_and_a_sign_in_from_before_go_on_through_the_relay() { Some(address.as_str()) ); } + +/** +Setup ends with a connection through the window's own sign-in too (`connect_window_now` keeps the +choice), and a first screen the window's sign-in puts back (the page could not trade its code: +Sign in again, the choice still connected) starts no setup session: no `setup_abandoned` on quit, +or at the next launch. Connect is asked as the window asks it, with the screen named (then counted +`started` and `completed` before the trade) and, the defensive case, without +(`connect_from_the_first_screen`). +*/ +#[test] +fn a_window_sign_in_ends_setup_and_its_sign_in_again_is_not_abandoned() { + use openbot_desktop_lib::telemetry::{EventData, Step}; + for named in [true, false] { + let data = temp_root("openbot-window-sign-in-not-abandoned"); + let address = window_stand_in(WindowStand::new(true)); + let shell = window_shell(); + let (_browser, _opened) = approving_browser(); + desktop_telemetry::initialize_for_test(shell.handle(), data.to_path_buf()); + window_says( + &shell, + &serde_json::json!({ "kind": "step_viewed", "step": "connect_openbot" }), + ); + let connected = connect_from_the_first_screen(&shell, &address, named); + assert_eq!( + choice::read(&shell.config).window_origin(), + Some(address.as_str()) + ); + shell + .ask_with( + &format!("{address}/desktop/signed-in"), + "plugin:openbot-desktop|window_sign_in_failed", + serde_json::json!({ "reason": "invalid_code" }), + ) + .expect("put back"); + assert_eq!(shell.window.url().unwrap().as_str(), SETUP); + assert_eq!( + choice::read(&shell.config).connected_to(), + Some(address.as_str()), + "named {named}: the choice kept" + ); + window_says( + &shell, + &serde_json::json!({ "kind": "step_viewed", "step": "connect_openbot" }), + ); + let mut shown = vec![ + EventData::StepViewed { + step: Step::Welcome, + }, + EventData::StepViewed { + step: Step::ConnectOpenbot, + }, + ]; + shown.extend(connected); + shown.push(EventData::StepViewed { + step: Step::ConnectOpenbot, + }); + quit_and_relaunch_without_abandonment(shell, &data, shown, &format!("named {named}")); + } +} + +/** +A launch whose saved window sign-in that OpenBot no longer publishes (`show_window_saved`) lets +the window's sign-in go and puts Sign in again up, the choice still connected: that screen starts +no setup session, so no `setup_abandoned` on quit, or at the next launch. +*/ +#[test] +fn a_saved_window_sign_in_no_longer_published_is_not_abandoned() { + use openbot_desktop_lib::telemetry::{EventData, Step}; + let data = temp_root("openbot-window-no-longer-published"); + let stand = WindowStand::new(false); + let address = window_stand_in(stand); + let shell = window_shell(); + choice::write(&shell.config, &choice::window_signed_in_at(&address, &address)).unwrap(); + desktop_telemetry::initialize_for_test(shell.handle(), data.to_path_buf()); + let refused = shell.ask(SETUP, "show_connected").unwrap_err(); + assert_eq!(refused["kind"], "session-ended", "{refused}"); + let kept = choice::read(&shell.config); + assert_eq!(kept.window, None, "the window's sign-in let go"); + assert_eq!(kept.connected_to(), Some(address.as_str()), "the choice kept"); + window_says( + &shell, + &serde_json::json!({ "kind": "step_viewed", "step": "connect_openbot" }), + ); + let shown = vec![ + EventData::StepViewed { + step: Step::Welcome, + }, + EventData::StepViewed { + step: Step::ConnectOpenbot, + }, + ]; + quit_and_relaunch_without_abandonment(shell, &data, shown, "no longer published"); +} diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 9525ef50f1..c90d1b0fa6 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -2439,6 +2439,10 @@ test("asked from Settings to choose where OpenBot runs, the first screen opens o "connection", "take_connection_notice", ]); + // The first screen shown again is counted once, as a Sign in again is. + expect(setupEvents()).toEqual([ + { event: { kind: "step_viewed", step: "connect_openbot" } }, + ]); // Picking Self-Contained switches the saved choice, then setup carries on as it does today. await userEvent.click( view.getByRole("radio", { name: /^OpenBot \(Self-Contained\)/ }), @@ -2447,6 +2451,12 @@ test("asked from Settings to choose where OpenBot runs, the first screen opens o const commands = asked().map((call) => call.command); expect(commands.indexOf("use_this_computer")).toBe(2); expect(commands).toContain("already_configured"); + // The window then says the first screen of the setup this computer starts, as the shell's own + // IPC test of `use_this_computer` takes it to. + expect(setupEvents()).toEqual([ + { event: { kind: "step_viewed", step: "connect_openbot" } }, + { event: { kind: "step_viewed", step: "welcome" } }, + ]); }); /* @@ -2593,6 +2603,10 @@ test("Stop reconnecting shows the connect screen with why, and Try again opens i "show_connected", "show_connected", ]); + // The connect screen it said why on is counted once, as a Sign in again is. + expect(setupEvents()).toEqual([ + { event: { kind: "step_viewed", step: "connect_openbot" } }, + ]); // Opened with the sign-in this computer had: not a go at connecting, so nothing is counted. expect(connectEvents()).toEqual([]); expect(strays).toEqual([]);