Files
Kigi-CLI/crates/codegen/kigi-pager-render/src/host/mod.rs
T
ZacharyZhang-NY d6c20fc13f M0: compilable skeleton — Kigi 0.1.0 fork surgery
Hard fork of xai-org/grok-build (Apache-2.0) re-targeted as Kigi, an
unofficial Kimi Code CLI community build.

Rename & identity
- 72 xai-*/xai-grok-* crates -> kigi-* (explicit: xai-grok-pager-bin ->
  kigi-bin [binary `kigi`], xai-grok-pager -> kigi-tui; rest mechanical);
  ptyctl, ptyctl-cli, third_party/ unchanged; proto package
  xai.grok.tools.v1 -> kigi.tools.v1
- Config home ~/.kigi (KIGI_SHARE_DIR override), env prefix GROK_* ->
  KIGI_*, `kigi --version` carries the unofficial-community-build notice
- clap identity, help text, startup banner, prompt templates rebranded
  (templates re-encrypted)

Deletions (PRD removal list #5/#6/#7/#9/#10)
- voice input (xai-grok-voice) and all TUI wiring
- telemetry: Mixpanel client, external OTel stream, Sentry, OTLP layers,
  trace/GCS/S3 upload queues (kigi-file-utils halved), workspace upload
  module & dc_log, heap-profile uploader, auth-diagnostics uploader,
  session-analytics halves of feedback; local zero-egress observability
  preserved in new kigi-log crate (unified log, --debug firehose,
  subsystem file logs, opt-in instrumentation)
- announcements (crate, remote-settings fields, TUI surfaces)
- plugin marketplace (crate, sources/browse/CTA/extensions-modal tab);
  direct plugin install/uninstall/update via kigi-agent git_install kept
- relay/gateway/assets endpoints and features (agent relay, headless
  relay transport, gateway bridge, LeaderEnvUrls); leader IPC socket now
  ~/.kigi/leader.sock + KIGI_LEADER_SOCKET, no ws-url derivation
- functional types rehomed instead of deleted: PermissionMode ->
  kigi-config-types, McpInitStrategy -> kigi-mcp, PrCreationSource ->
  session signals, TerminalDiagnostics -> kigi-pager-render, agent_id ->
  shell util

Endpoints
- kigi-env rewritten: single production KigiEndpoints {coding_api_base_url
  https://api.kimi.com/coding/v1 (KIGI_CODE_BASE_URL), oauth_host
  https://auth.kimi.com (KIGI_OAUTH_HOST), update_base_url (GitHub
  Releases API), upgrade_page_url}; GrokBuildEnvironment enum deleted

Toolchain & workspace hygiene
- Rust 1.97.0 pinned; edition 2024; full cargo update; git2 hoisted to
  workspace at 0.21 (Option->Result API migration), quick-xml 0.41
- Root Cargo.toml hand-maintained (PRD §8.1): version 0.1.0 inherited by
  all members, members sorted, unused deps pruned
- cargo-deny advisories gate (deny.toml with documented transitive
  exceptions); CI workflow (check/clippy/fmt/deny/test, macOS+Linux)
- cross-crate test seams re-gated behind `test-support` cargo feature;
  insta snapshot baselines renamed to the kigi_tui prefix
- clippy --workspace --all-targets: zero warnings; fmt clean

Fixes surfaced by the port
- updater probe/installer divergence (bin/kigi vs bin/grok symlink set)
- idle model-metadata refresh dead under KIGI_CODE_BASE_URL override
  (new is_effective_coding_endpoint_url, loopback+override aware)
- macOS symlinked-TMPDIR fixture canonicalization (foreign_sessions,
  fast-worktree); RSS measurement tests serialized via serial_test

Docs & legal (Apache §4)
- NOTICE added (upstream attribution + change statement); THIRD-PARTY
  notices sustained; kigi-tools ported-code notices extended; README,
  CONTRIBUTING, SECURITY, AGENTS.md rewritten

Out of scope for M0 (tracked): Kimi auth/inference (M1), search/fetch,
command parity, config import (M2), Computer Hub excision & final
brand-token sweep (M2), distribution & self-update rewrite (M3).
2026-07-17 05:31:01 -04:00

186 lines
5.3 KiB
Rust

//! Host platform and display server classification.
use std::collections::HashMap;
use std::ffi::OsString;
use std::sync::OnceLock;
mod display_refresh;
pub use display_refresh::{DisplayRefreshProbeResult, DisplayRefreshSource, probe_display_refresh};
/// Process env as UTF-8. Skips non-Unicode entries (`vars()` panics on those).
pub fn collect_unicode_env() -> HashMap<String, String> {
unicode_env_from_os(std::env::vars_os())
}
/// Pure helper: drop OsString pairs that are not valid Unicode.
pub fn unicode_env_from_os(
iter: impl IntoIterator<Item = (OsString, OsString)>,
) -> HashMap<String, String> {
iter.into_iter()
.filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
.collect()
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, strum::Display)]
#[strum(serialize_all = "snake_case")]
#[non_exhaustive]
pub enum HostOs {
Macos,
Linux,
Windows,
#[default]
Other,
}
impl HostOs {
/// Call on demand since cfg is compile-time constant.
pub fn current() -> Self {
if cfg!(target_os = "macos") {
Self::Macos
} else if cfg!(target_os = "linux") {
Self::Linux
} else if cfg!(target_os = "windows") {
Self::Windows
} else {
Self::Other
}
}
}
/// WSL detection. The implementation lives in `kigi-tty-utils` (the shared
/// low-level crate) so crates that must not depend on this UI crate can reuse
/// it; re-exported here so existing `host::is_wsl()` callers are unchanged.
pub use kigi_tty_utils::is_wsl;
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, strum::Display)]
#[strum(serialize_all = "snake_case")]
#[non_exhaustive]
pub enum DisplayServer {
Quartz,
Wayland,
X11,
Win32,
#[default]
Unknown,
}
impl DisplayServer {
/// Detect the display server. Cached for process lifetime on Linux
/// (env vars don't change); compile-time constant on macOS/Windows.
pub fn current() -> Self {
static CACHE: OnceLock<DisplayServer> = OnceLock::new();
*CACHE.get_or_init(|| {
let env = collect_unicode_env();
Self::detect_from_env(&env)
})
}
/// Pure helper so tests can drive env directly.
fn detect_from_env(env: &HashMap<String, String>) -> Self {
match HostOs::current() {
HostOs::Macos => Self::Quartz,
HostOs::Windows => Self::Win32,
HostOs::Linux => {
if env.get("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty()) {
Self::Wayland
} else if env.get("DISPLAY").is_some_and(|v| !v.is_empty()) {
Self::X11
} else {
Self::Unknown
}
}
HostOs::Other => Self::Unknown,
}
}
}
#[cfg(test)]
mod unicode_env_tests {
use super::*;
use std::ffi::OsString;
#[test]
fn unicode_env_from_os_skips_non_unicode_key_or_value() {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
let bad = OsString::from_vec(vec![0xff, 0xfe]);
let map = unicode_env_from_os([
(bad.clone(), OsString::from("ok")),
(OsString::from("OK_KEY"), bad),
(OsString::from("GOOD"), OsString::from("yes")),
]);
assert_eq!(map, HashMap::from([("GOOD".into(), "yes".into())]));
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
let bad = OsString::from_wide(&[0xD800]); // lone surrogate
let map = unicode_env_from_os([
(bad.clone(), OsString::from("ok")),
(OsString::from("OK_KEY"), bad),
(OsString::from("GOOD"), OsString::from("yes")),
]);
assert_eq!(map, HashMap::from([("GOOD".into(), "yes".into())]));
}
}
}
// All remaining tests here are Linux-only DisplayServer tests; WSL detection
// tests live with the implementation in `kigi-tty-utils`.
#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::*;
fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect()
}
#[test]
fn display_server_wayland() {
assert_eq!(
DisplayServer::detect_from_env(&env(&[("WAYLAND_DISPLAY", "wayland-0")])),
DisplayServer::Wayland,
);
}
#[test]
fn display_server_x11() {
assert_eq!(
DisplayServer::detect_from_env(&env(&[("DISPLAY", ":0")])),
DisplayServer::X11,
);
}
#[test]
fn display_server_wayland_wins_over_x11() {
assert_eq!(
DisplayServer::detect_from_env(&env(&[
("WAYLAND_DISPLAY", "wayland-0"),
("DISPLAY", ":0"),
])),
DisplayServer::Wayland,
);
}
#[test]
fn display_server_unknown_when_no_display() {
assert_eq!(
DisplayServer::detect_from_env(&env(&[])),
DisplayServer::Unknown,
);
}
#[test]
fn display_server_empty_wayland_display_ignored() {
assert_eq!(
DisplayServer::detect_from_env(&env(&[("WAYLAND_DISPLAY", ""), ("DISPLAY", ":1")])),
DisplayServer::X11,
);
}
}