Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 17 additions & 27 deletions crates/jcode-setup-hints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// platform. In a non-macOS *test* build their only production callers (the
// `#[cfg(target_os = "macos")]` notice/install paths) are compiled out, so the
// helpers the tests don't call directly look dead. They are real macOS code, so
// silence dead_code only for that specific build shape instead of deleting them.
// silence dead_code for that build shape rather than deleting them.
#![cfg_attr(all(test, not(target_os = "macos")), allow(dead_code))]

#[cfg(any(target_os = "macos", target_os = "linux"))]
Expand Down Expand Up @@ -55,10 +55,9 @@ use macos_terminal::load_preferred_macos_terminal;
use macos_terminal::paused_jcode_shell_command;
#[cfg(target_os = "macos")]
use macos_terminal::save_preferred_macos_terminal;
// `MacTerminalKind` is reachable from the `#[cfg(any(test, target_os = "macos"))]`
// notice helper and its tests, but every `effective_macos_terminal()` caller sits
// behind `#[cfg(target_os = "macos")]`. Keeping the two names on one gate left
// this import unused in a non-macOS `--all-targets` test build.
// `MacTerminalKind` is used by the notice helper and its tests, but every
// `effective_macos_terminal()` caller is macOS-only, so the gates must differ:
// one import was otherwise unused in a non-macOS test build.
#[cfg(target_os = "macos")]
use macos_terminal::effective_macos_terminal;
#[cfg(windows)]
Expand Down Expand Up @@ -328,8 +327,8 @@ fn load_launch_hotkeys_config() -> jcode_config_types::LaunchHotkeysConfig {
};
let path = dir.join("config.toml");
// Startup calls this several times (hotkey notice, resolve, install
// checks), each a full TOML parse of config.toml. Memoize on the file's
// path, mtime and length so edits are still picked up immediately.
// checks), each a full TOML parse. Memoize on path, mtime and length so
// edits are still picked up immediately.
type Key = (
std::path::PathBuf,
Option<std::time::SystemTime>,
Expand Down Expand Up @@ -616,15 +615,10 @@ fn install_macos_hotkey_listener(

fn startup_hints_for_launch(_state: &SetupHintsState) -> Option<StartupHints> {
// The startup spawn notice was retired: nothing in the crate ever writes
// `startup_spawn_hint_dismissed = false`, so the prior `if !hotkey_configured
// || dismissed { None } else { Some(notice) }` gate always evaluated to None
// in practice. The function remains so callers (lib.rs:1353) and tests in
// setup_hints_tests.rs continue to compile against the same signature; it
// `startup_spawn_hint_dismissed = false`, so the prior gate always
// evaluated to None. The function remains so callers (lib.rs:1353) and
// tests in setup_hints_tests.rs compile against the same signature; it
// simply no longer constructs the notice.
//
// Note: `SetupHintsState::startup_spawn_hint_dismissed` is intentionally kept
// on the struct for state-file compatibility — existing users may have
// `false` persisted, and the serde Deserialize path still reads it.
let _ = _state;
None
}
Expand Down Expand Up @@ -698,10 +692,9 @@ pub fn run_setup_hotkey(
}
#[cfg(target_os = "macos")]
{
// The background listener (`--listen-macos-hotkey`) is intercepted earlier,
// in `main()`, so it runs on the real main thread with a Core Foundation
// run loop. If we somehow reach here with that flag (e.g. invoked directly),
// honor it rather than running the interactive installer.
// The background listener (`--listen-macos-hotkey`) is intercepted earlier, in
// `main()`, and runs on the real main thread with a Core Foundation run loop.
// Reaching here with that flag anyway means honor it, not the installer.
if _listen_macos_hotkey {
return run_macos_hotkey_listener();
}
Expand Down Expand Up @@ -935,10 +928,8 @@ pub fn run_macos_hotkey_listener_main_thread() -> Result<()> {
mod macos_run_loop {
// Minimal Carbon/ApplicationServices bindings to (a) make this faceless
// launchd process eligible to receive global hotkeys and (b) run the Carbon
// application event loop that dispatches `RegisterEventHotKey` events.
//
// We deliberately avoid pulling in a heavier `core-foundation`/`cocoa`
// dependency just for these few calls.
// event loop that dispatches `RegisterEventHotKey` events. A heavier
// `core-foundation`/`cocoa` dependency is deliberately avoided for these calls.

#[repr(C)]
struct ProcessSerialNumber {
Expand All @@ -948,10 +939,9 @@ mod macos_run_loop {

// `kCurrentProcess` from MacTypes / Process Manager.
const K_CURRENT_PROCESS: u32 = 2;
// `kProcessTransformToUIElementApplication` from ApplicationServices.
// Promotes a background (faceless) process to a UIElement app so it has a
// connection to the window server and can receive Carbon hotkey events,
// without showing a Dock icon or menu bar.
// `kProcessTransformToUIElementApplication` promotes a background (faceless)
// process to a UIElement app so it can reach the window server and receive
// Carbon hotkey events, without showing a Dock icon or menu bar.
const K_PROCESS_TRANSFORM_TO_UI_ELEMENT_APPLICATION: u32 = 4;

#[link(name = "ApplicationServices", kind = "framework")]
Expand Down
52 changes: 16 additions & 36 deletions crates/jcode-telemetry-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ mod concurrency;
mod delivery;
mod lifecycle;
pub use concurrency::{ConcurrencySession, begin_concurrency_session};
// The live HTTP delivery path is inert under `cfg(test)`: payloads are captured
// into `TEST_EMITTED_PAYLOADS` instead of being queued or posted. Re-exporting
// these three unconditionally left the import unused in the `--all-targets`
// test build. Non-test builds are unaffected.
// The live HTTP delivery path is inert under `cfg(test)`: payloads go to
// `TEST_EMITTED_PAYLOADS` instead of being queued or posted.
#[cfg(not(test))]
pub(crate) use delivery::{background_sender, post_payload, transcript_background_sender};
// Only the test module reaches for these two; re-exporting them unconditionally
Expand Down Expand Up @@ -36,8 +34,7 @@ use std::collections::HashSet;
use std::sync::Mutex;
#[cfg(not(test))]
use std::sync::OnceLock;
// Only the `#[cfg(not(test))]` delivery paths read the atomic flags and the
// non-blocking send errors; the test build asserts on fully-qualified paths.
// Only the `#[cfg(not(test))]` delivery paths read these flags.
#[cfg(not(test))]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(test))]
Expand Down Expand Up @@ -179,11 +176,9 @@ impl TodoSessionTelemetry {
}
}

// Error/switch counters live inside `SessionTelemetry` (guarded by
// `SESSION_STATE`) so increments, snapshots, and resets all happen under a
// single critical section and are naturally scoped to the owning session.
// Keeping them in a separate lock-free atomic domain previously let trailing
// `record_*` calls drift across session boundaries (see issue #394).
// Error/switch counters live in `SessionTelemetry` under `SESSION_STATE`, so
// a separate lock-free domain cannot let trailing `record_*` calls drift

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Comment may overstate cross-session drift protection

The comment claims "a separate lock-free domain cannot let trailing record_* calls drift across session boundaries" (issue #394). However, late record_error or switch calls after a new begin_session may update the new slot under the same SESSION_STATE mutex, potentially undermining the claimed protection. Verify this claim or soften the wording.

// across session boundaries (issue #394).
static SESSION_STATE: Mutex<Option<SessionTelemetry>> = Mutex::new(None);

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -537,8 +532,7 @@ pub fn set_usage_telemetry_enabled(enabled: bool) -> bool {
}
} else {
// Record the explicit in-app choice once, while telemetry is still
// enabled. Failure never prevents or delays the opt-out itself, and
// environment-forced opt-outs remain completely silent.
// unmutated by the background worker.
if !path.exists() && !opt_out_forced_by_env() {
emit_telemetry_opt_out();
}
Expand Down Expand Up @@ -1322,8 +1316,7 @@ fn send_transcript_payload(payload: Value) -> bool {
if let Ok(mut emitted) = TEST_EMITTED_PAYLOADS.lock() {
emitted.push(payload);
}
// Tail expression rather than `return true;`: this block is the function
// body in a test build, where `return` would be a needless return.
// Tail expression, not `return true;`: this is the whole body in a test build.
true
}
#[cfg(not(test))]
Expand Down Expand Up @@ -1694,12 +1687,8 @@ pub fn record_install_if_first_run() {
clear_install_conversion_id();
return;
}
// Skip install/onboarding emission under CI. Ephemeral runners start with a
// fresh ~/.kcode (so a new telemetry_id) on every job, which would otherwise
// look like a brand-new install and user, inflating install/active counts,
// the onboarding funnel, and depressing retention. Session/turn/lifecycle
// events are still emitted (tagged is_ci) so CI crash/error signal stays
// queryable; product dashboards filter is_ci out of the headline metrics.
// Skip install/onboarding emission under CI: ephemeral runners start with
// a fresh ~/.kcode each job, which would inflate install/active counts.
if is_ci() {
logging::debug("skipping telemetry install/onboarding under CI");
clear_install_conversion_id();
Expand All @@ -1713,9 +1702,7 @@ pub fn record_install_if_first_run() {
};
let install_conversion_id = read_install_conversion_id();
// A website-attributed install is a fresh post-install launch even when
// this telemetry identity previously recorded an install. This also lets
// the first conversion-aware release consume tokens written by the
// installer before that release existed.
// this identity previously recorded an install.
if !should_record_install_for_id(&id, install_conversion_id.as_deref()) {
return;
}
Expand Down Expand Up @@ -2019,11 +2006,7 @@ fn begin_session_with_mode(
todo: TodoSessionTelemetry::default(),
};
// A live session in the slot means the process is switching sessions
// without anyone calling end_session (agent create/attach both call
// begin_session unconditionally). Overwriting it silently orphaned the
// previous session_start, which is why only ~25% of release
// session_starts ever saw a matching session_end. Close it out first so
// every start has a terminal event.
// without end_session, orphaning the previous session_start.
let superseded = match SESSION_STATE.lock() {
Ok(guard) => guard.as_ref().map(|prior| {
(
Expand Down Expand Up @@ -2103,9 +2086,8 @@ pub fn record_turn() {
}
if let Some(payload) = prompt_event {
let mode = if first_prompt {
// Short `jcode run` invocations can exit before the background
// worker starts. Bound the first prompt's delivery so every active
// installation has an immediate durable activity anchor.
// Short `jcode run` invocations can exit before the background worker
// has flushed, so the shutdown path drains it explicitly.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Comment may overstate shutdown drain behavior

The comment claims "the shutdown path drains it explicitly" to justify DeliveryMode::Blocking for the first prompt. However, the shutdown path may not actually drain a queued background worker copy. Verify this claim or adjust the wording to match actual behavior.

DeliveryMode::Blocking(BLOCKING_FIRST_PROMPT_TIMEOUT)
} else {
DeliveryMode::Background
Expand Down Expand Up @@ -2607,10 +2589,8 @@ pub fn current_provider_model() -> Option<(String, String)> {

fn show_first_run_notice() {
// This can print before any terminal setup enables VT processing. Legacy
// Windows consoles (conhost without ENABLE_VIRTUAL_TERMINAL_PROCESSING,
// exactly the double-click-the-exe path) render raw escapes as `←[90m`
// garbage (issue #498), so only colorize when the console accepts ANSI
// (the helper also opportunistically enables VT mode on Windows).
// consoles render raw escapes as garbage (issue #498), so only colorize
// when the console accepts ANSI.
let (dim, reset) = if jcode_core::console::stderr_supports_ansi() {
("\x1b[90m", "\x1b[0m")
} else {
Expand Down
Loading