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).
This commit is contained in:
2026-07-17 05:31:01 -04:00
commit d6c20fc13f
2612 changed files with 1353757 additions and 0 deletions
@@ -0,0 +1,127 @@
//! Empty-composer Enter sends the top mid-turn queued follow-up now.
//!
//! Regression for send-now discoverability: plain Enter with text still
//! *queues*; a second bare Enter on the empty prompt is cancel-and-send — the
//! running turn is cancelled (silently: no "Turn cancelled by user" marker)
//! and the queued row runs as the next turn, arriving on the wire as a
//! standard `<user_query>` prompt with no interjection preamble.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use super::wait_for_welcome;
use crate::{ContentController, PtyHarness, pager_binary};
const DEFAULT_ROWS: u16 = 50;
const DEFAULT_COLS: u16 = 120;
/// The interjection-merge preamble: send-now must never produce it.
const INTERJECTION_WIRE_PREFIX: &str = "The user sent a message while you were working";
fn slow_turn_text(sentinel: &str) -> String {
let mut s = String::from(sentinel);
for i in 0..30 {
s.push_str(&format!(" streaming{i}"));
}
s
}
fn all_user_message_blobs(content: &ContentController) -> Vec<String> {
content
.request_bodies()
.iter()
.flat_map(|b| {
let items = b["messages"].as_array().or_else(|| b["input"].as_array());
items
.into_iter()
.flatten()
.filter(|m| m["role"] == "user")
.map(|m| match m["content"].as_str() {
Some(s) => s.to_owned(),
None => m["content"].to_string(),
})
.collect::<Vec<_>>()
})
.collect()
}
/// Mid-turn queue via Enter, then empty Enter cancels the running turn and
/// runs that row as the next turn (cancel-and-send).
pub async fn assert_empty_enter_force_sends_top_queued() -> Result<()> {
let content = ContentController::start()
.await
.context("start ContentController")?;
// Gate turn 1's terminal event so the queue + empty-Enter provably land
// mid-turn — a paced-chunk window races turn end on slow (remote) workers.
content.hold_agent_completions();
content.set_turns([
slow_turn_text("TURNONE"),
"TURNTWO reply to the promoted follow-up.".to_owned(),
]);
let binary = pager_binary().context("resolve pager binary")?;
let mut harness =
PtyHarness::spawn_with_content(&binary, DEFAULT_ROWS, DEFAULT_COLS, &content, &[])
.context("spawn pager")?;
wait_for_welcome(&mut harness).await?;
harness.inject_keys(b"go\r").context("submit prompt")?;
harness
.wait_for_text("TURNONE", Duration::from_secs(30))
.context("turn 1 streaming")?;
harness
.inject_keys(b"please also check the logs\r")
.context("queue follow-up")?;
harness
.wait_for_text("please also check the logs", Duration::from_secs(10))
.context("queued text visible")?;
harness.inject_keys(b"\r").context("empty Enter send-now")?;
// Cancel-and-send: the shell cancels turn 1 (its held completion is
// irrelevant — the abort wins) and promotes the row to run as turn 2.
// Release the gate so any completion race resolves rather than hangs.
content.release_agent_completions();
// The promoted row renders as a standard user prompt block (" " prefix
// distinguishes the committed block from the prefix-less queue row) with
// the new turn's reply below it.
harness
.wait_for_text(
"\u{276F} please also check the logs",
Duration::from_secs(15),
)
.context("promoted prompt scrollback chrome")?;
harness
.wait_for_text("TURNTWO", Duration::from_secs(40))
.context("promoted turn reply")?;
// A send-now cancel is silent: no "Turn cancelled by user" marker may
// appear between the partial turn-1 output and the promoted prompt.
if harness.contains_text("Turn cancelled by user") {
bail!(
"send-now cancel must not render a cancelled marker\n{}",
harness.screen_contents()
);
}
let users = all_user_message_blobs(&content);
let Some(promoted) = users
.iter()
.find(|u| u.contains("please also check the logs"))
else {
bail!("queued follow-up never reached the wire: {users:#?}");
};
if promoted.contains(INTERJECTION_WIRE_PREFIX) {
bail!("send-now must not use the interjection preamble: {promoted}");
}
if !promoted.contains("<user_query>") {
bail!("send-now must arrive as a standard user_query prompt: {promoted}");
}
if harness.contains_text("panicked") {
bail!("pager panicked\n{}", harness.screen_contents());
}
harness.quit().context("clean quit")?;
Ok(())
}
@@ -0,0 +1,30 @@
//! `idle_cost` — after content settles, measure frames for N seconds of
//! true idle. Catches the `needs_animation()` always-true bug: frames > 0
//! here means the pager is ticking when it shouldn't.
use std::time::{Duration, Instant};
use anyhow::Result;
use super::{BenchResults, ContentController, PtyHarness, wait_for_welcome};
const IDLE_WINDOW: Duration = Duration::from_secs(3);
pub async fn run(harness: &mut PtyHarness, _content: &ContentController) -> Result<BenchResults> {
wait_for_welcome(harness).await?;
// Let the splash screen animation settle (some of the pager's intro
// screens do a brief fade/animation).
harness.update(Duration::from_secs(1));
harness.reset_timing();
let start = Instant::now();
while start.elapsed() < IDLE_WINDOW {
harness.update(Duration::from_millis(100));
if !harness.is_running() {
break;
}
}
let wall_time = start.elapsed();
Ok(harness.bench_results("idle_cost", wall_time))
}
@@ -0,0 +1,52 @@
//! `large_codeblock` — render a large syntax-highlighted Rust code block
//! and scroll through it.
//!
//! What it stresses: `syntect` highlighting cache, wrapping of long source
//! lines, ScratchBuffer copy for a single oversized entry.
use std::time::{Duration, Instant};
use anyhow::Result;
use super::{BenchResults, ContentController, PtyHarness, wait_for_welcome};
use crate::keys;
const LINES: usize = 400;
const SCROLL_KEYS: usize = 120;
const KEY_INTERVAL: Duration = Duration::from_millis(20);
pub async fn run(harness: &mut PtyHarness, content: &ContentController) -> Result<BenchResults> {
content.set_response(build_rust_codeblock(LINES));
wait_for_welcome(harness).await?;
harness.inject_keys(b"code\r")?;
harness.wait_for_text("fn code_sample", Duration::from_secs(30))?;
harness.update(Duration::from_millis(500));
harness.reset_timing();
let start = Instant::now();
for _ in 0..SCROLL_KEYS {
harness.inject_keys(keys::J)?;
harness.update(KEY_INTERVAL);
if !harness.is_running() {
break;
}
}
harness.update(Duration::from_millis(250));
let wall_time = start.elapsed();
Ok(harness.bench_results("large_codeblock", wall_time))
}
fn build_rust_codeblock(lines: usize) -> String {
let mut s = String::with_capacity(lines * 60);
s.push_str("```rust\n");
for i in 0..lines {
s.push_str(&format!(
"fn code_sample_{i}(x: i32) -> i32 {{ x.wrapping_mul({i}).wrapping_add({}) }}\n",
i + 1
));
}
s.push_str("```\n");
s
}
@@ -0,0 +1,46 @@
//! `mixed_interaction` — scroll while streaming. The real-world worst case.
//!
//! What it stresses: simultaneous cache invalidation (from streaming) and
//! full viewport re-render (from scrolling). Surfaces `dirty_heights` /
//! scroll-offset interactions.
use std::time::{Duration, Instant};
use anyhow::Result;
use super::{BenchResults, ContentController, PtyHarness, wait_for_welcome};
use crate::keys;
const TARGET_WORDS: usize = 400;
const SCROLL_KEYS: usize = 80;
const KEY_INTERVAL: Duration = Duration::from_millis(40);
pub async fn run(harness: &mut PtyHarness, content: &ContentController) -> Result<BenchResults> {
// Same payload shape as streaming_render, but we scroll through it
// while it's still arriving.
let mut body = String::from("mixed-bench ");
for i in 0..TARGET_WORDS {
body.push_str("tok");
body.push_str(&i.to_string());
body.push(' ');
}
content.set_response(body);
wait_for_welcome(harness).await?;
harness.inject_keys(b"go\r")?;
harness.wait_for_text("mixed-bench", Duration::from_secs(20))?;
harness.reset_timing();
let start = Instant::now();
for _ in 0..SCROLL_KEYS {
harness.inject_keys(keys::J)?;
harness.update(KEY_INTERVAL);
if !harness.is_running() {
break;
}
}
harness.update(Duration::from_millis(250));
let wall_time = start.elapsed();
Ok(harness.bench_results("mixed_interaction", wall_time))
}
@@ -0,0 +1,90 @@
//! Named scenarios that drive content into the pager and measure frame timing.
//!
//! Each scenario is a function `async fn run(&mut PtyHarness, &ContentController)`
//! returning a [`BenchResults`]. Scenarios are dispatched by name via the
//! [`Scenario`] enum for the `pty-bench` CLI and for ad-hoc test usage.
use std::time::Duration;
use anyhow::Result;
use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use super::{BenchResults, ContentController, PtyHarness};
pub mod empty_enter_send_now;
pub mod idle_cost;
pub mod large_codeblock;
pub mod mixed_interaction;
pub mod plan_approval_resume;
pub mod resize_storm;
pub mod scroll_stress;
pub mod streaming_render;
/// Enumerates every benchmark scenario that can be dispatched by name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Scenario {
/// Inject rapid `j` keys against a large pre-rendered response.
ScrollStress,
/// Stream a 2000-token response at a controlled rate.
StreamingRender,
/// Resize the PTY many times in quick succession; assert no crash.
ResizeStorm,
/// Render a large syntax-highlighted code block and scroll through it.
LargeCodeblock,
/// After content settles, measure CPU cost while idle.
IdleCost,
/// Scroll while streaming — the real-world worst case.
MixedInteraction,
}
impl Scenario {
/// Every scenario, in dispatch order.
pub const ALL: &'static [Scenario] = &[
Scenario::ScrollStress,
Scenario::StreamingRender,
Scenario::ResizeStorm,
Scenario::LargeCodeblock,
Scenario::IdleCost,
Scenario::MixedInteraction,
];
/// Stable slug used in JSON output and baseline files.
pub fn as_str(self) -> &'static str {
match self {
Scenario::ScrollStress => "scroll_stress",
Scenario::StreamingRender => "streaming_render",
Scenario::ResizeStorm => "resize_storm",
Scenario::LargeCodeblock => "large_codeblock",
Scenario::IdleCost => "idle_cost",
Scenario::MixedInteraction => "mixed_interaction",
}
}
/// Dispatch to the scenario implementation.
pub async fn run(
self,
harness: &mut PtyHarness,
content: &ContentController,
) -> Result<BenchResults> {
match self {
Scenario::ScrollStress => scroll_stress::run(harness, content).await,
Scenario::StreamingRender => streaming_render::run(harness, content).await,
Scenario::ResizeStorm => resize_storm::run(harness, content).await,
Scenario::LargeCodeblock => large_codeblock::run(harness, content).await,
Scenario::IdleCost => idle_cost::run(harness, content).await,
Scenario::MixedInteraction => mixed_interaction::run(harness, content).await,
}
}
}
/// Wait for the pager to render the initial welcome screen. All scenarios
/// that prompt / stream content rely on the pager being past startup.
pub(crate) async fn wait_for_welcome(harness: &mut PtyHarness) -> Result<()> {
// Menu label on the normal welcome (and gate menus): capital Q — see
// `kigi-tui` `views/welcome/mod.rs` (`"Quit"` in `render_menu`).
harness
.wait_for_text("Quit", Duration::from_secs(15))
.map_err(|e| anyhow::anyhow!("pager failed to reach welcome screen: {e}"))
}
@@ -0,0 +1,195 @@
//! Plan-approval chrome restored by the shell after quit + resume.
//!
//! When `exit_plan_mode` is parked and the user quits, the shell persists
//! `awaiting_plan_approval = true` in `plan_mode.json`. On `--continue` the
//! shell re-issues the `x.ai/exit_plan_mode` reverse-request — a real live ACP
//! waiter — so the pager re-shows approval chrome through its normal path with
//! no pager-side disk logic. Approving then leaves plan mode and starts the
//! implement turn.
//!
//! This FAILS without the shell re-park (PR2 product change): no reverse-request
//! reaches the resumed pager, so no approval chrome appears.
use std::path::Path;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use super::wait_for_welcome;
use crate::{ContentController, PtyHarness, pager_binary};
const DEFAULT_ROWS: u16 = 50;
const DEFAULT_COLS: u16 = 120;
const WELCOME_TIMEOUT: Duration = Duration::from_secs(20);
/// Distinct per-turn sentinels: turn 1 seeds the session before quit; turn 2 is
/// the implement turn the shell injects after the resumed approval is approved.
const SETUP_SENTINEL: &str = "GBT3703SETUP";
const IMPLEMENT_SENTINEL: &str = "GBT3703IMPLEMENTED";
const PLAN_BODY: &str = "\
# Plan GBT3703Repro
## Steps
1. Seed plan file on disk
2. Quit pager with the approval parked
3. Resume and expect restored approval chrome
";
/// Regression: the shell re-parks `exit_plan_mode` on resume; pressing
/// approve leaves plan mode and starts the implement turn.
pub async fn assert_plan_approval_restored_after_resume() -> Result<()> {
let content = ContentController::start()
.await
.context("start ContentController")?;
// One response per agent turn (FIFO, 2+-tool requests only — aux requests
// never steal one). Turn 1 is consumed by the first pager; turn 2 by the
// implement turn the shell starts after approval.
content.set_turns([
format!("{SETUP_SENTINEL}: drafted a plan for the user to review."),
format!("{IMPLEMENT_SENTINEL}: implementing the approved plan."),
]);
let project = tempfile::tempdir().context("project dir")?;
std::fs::create_dir_all(project.path().join(".git")).context("create .git")?;
let binary = pager_binary().context("resolve pager binary")?;
let mut first = PtyHarness::spawn_with_content_in_dir(
&binary,
DEFAULT_ROWS,
DEFAULT_COLS,
&content,
&[],
Some(project.path()),
)
.context("spawn first pager")?;
wait_for_welcome(&mut first).await?;
first.inject_keys(b"go\r").context("submit setup turn")?;
first
.wait_for_text(SETUP_SENTINEL, Duration::from_secs(30))
.context("setup turn rendered")?;
// Quit and reap BEFORE seeding so the still-live shell cannot re-persist
// and clobber the seeded state.
first.inject_keys(b"\x11").context("ctrl-q once")?;
first.update(Duration::from_millis(200));
first.inject_keys(b"\x11").context("ctrl-q confirm")?;
first.quit().context("reap first pager")?;
let seeded = seed_parked_approval(content.home()).context("seed parked approval")?;
assert!(seeded > 0, "no session dir seeded");
let mut resumed = PtyHarness::spawn_with_content_in_dir(
&binary,
DEFAULT_ROWS,
DEFAULT_COLS,
&content,
&["--continue"],
Some(project.path()),
)
.context("spawn resumed pager")?;
// The shell re-parks `exit_plan_mode` on resume, so approval chrome can open
// immediately and cover chat history. Prefer the chrome markers (product
// signal) over SETUP_SENTINEL, which may not be visible under the plan viewer.
// Without the shell re-park this times out.
resumed
.wait_for_text("request changes", WELCOME_TIMEOUT)
.context("restored approval 'request changes' after --continue")?;
resumed
.wait_for_text("quit plan", Duration::from_secs(5))
.context("restored approval 'quit plan' after resume")?;
let screen = resumed.screen_contents();
if !screen.contains("approve") {
bail!("expected approval primary action after resume\n{screen}");
}
// History was seeded before quit; plan body from disk is a stronger signal
// that the session was restored when chrome already covers the transcript.
if !screen.contains("GBT3703Repro")
&& !screen.contains(SETUP_SENTINEL)
&& !screen.contains("Seed plan file on disk")
{
bail!("expected resumed session content (plan body or setup sentinel)\n{screen}");
}
if resumed.contains_text("panicked") {
bail!("pager panicked\n{screen}");
}
// Approve: the shell leaves plan mode and injects the implement turn.
resumed.inject_keys(b"a").context("press 'a' to approve")?;
resumed
.wait_for_text(IMPLEMENT_SENTINEL, Duration::from_secs(30))
.context("approve must leave plan mode and start the implement turn")?;
resumed.quit().context("quit resumed pager")?;
Ok(())
}
/// Mark the persisted session as having a parked plan approval: write `plan.md`
/// and flip `awaiting_plan_approval` to `true` in `plan_mode.json` for every
/// session dir under the sandbox home.
fn seed_parked_approval(home: &Path) -> Result<usize> {
let sessions_root = home.join(".kigi").join("sessions");
if !sessions_root.is_dir() {
bail!(
"expected sessions under {} after first turn",
sessions_root.display()
);
}
let mut seeded = 0usize;
for cwd_ent in std::fs::read_dir(&sessions_root).context("read sessions root")? {
let cwd_ent = cwd_ent.context("cwd entry")?;
if !cwd_ent.file_type().context("ft")?.is_dir() {
continue;
}
for sess_ent in std::fs::read_dir(cwd_ent.path()).context("read cwd sessions")? {
let sess_ent = sess_ent.context("session entry")?;
if !sess_ent.file_type().context("ft")?.is_dir() {
continue;
}
let dir = sess_ent.path();
std::fs::write(dir.join("plan.md"), PLAN_BODY).context("write plan.md")?;
write_awaiting_plan_mode(&dir.join("plan_mode.json"))?;
seeded += 1;
}
}
if seeded == 0 {
bail!(
"expected at least one session dir under {}",
sessions_root.display()
);
}
Ok(seeded)
}
/// Round-trip the shell-written `plan_mode.json` and flip `awaiting_plan_approval`
/// to `true`, preserving every other field. Falls back to a fresh Active
/// snapshot if the shell wrote nothing. The shape mirrors
/// `kigi_shell::session::plan_mode::PlanModeSnapshot`; we only touch the one
/// field (robust to schema growth) rather than depend on the heavy shell crate
/// from this test-only harness.
fn write_awaiting_plan_mode(path: &Path) -> Result<()> {
let mut value: serde_json::Value = std::fs::read_to_string(path)
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or_else(|| {
serde_json::json!({
"state": "Active",
"was_previously_active": true,
"reminder_count": 0,
"pending_exit_reminder": false,
})
});
let obj = value
.as_object_mut()
.context("plan_mode.json must be a JSON object")?;
// Must be Active for the re-park; awaiting flag is the trigger.
obj.insert("state".into(), serde_json::Value::String("Active".into()));
obj.insert(
"awaiting_plan_approval".into(),
serde_json::Value::Bool(true),
);
std::fs::write(path, serde_json::to_vec_pretty(&value)?).context("write plan_mode.json")?;
Ok(())
}
@@ -0,0 +1,42 @@
//! `resize_storm` — resize the PTY many times in quick succession; assert
//! no crash and measure recovery.
//!
//! What it stresses: `prepare_layout` Case 1 (full width-change rebuild),
//! wrap-cache misses across every entry, resize-debounce in `event_loop.rs`.
use std::time::{Duration, Instant};
use anyhow::{Result, anyhow};
use super::{BenchResults, ContentController, PtyHarness, wait_for_welcome};
const RESIZES: usize = 25;
const RESIZE_INTERVAL: Duration = Duration::from_millis(40);
pub async fn run(harness: &mut PtyHarness, _content: &ContentController) -> Result<BenchResults> {
wait_for_welcome(harness).await?;
harness.reset_timing();
let start = Instant::now();
// Oscillate between a narrow and a wide layout.
for i in 0..RESIZES {
let (rows, cols) = if i % 2 == 0 { (35, 100) } else { (55, 160) };
harness.resize(rows, cols)?;
harness.update(RESIZE_INTERVAL);
if !harness.is_running() {
return Err(anyhow!("pager exited during resize_storm at iter {i}"));
}
}
// Let the pager settle.
harness.update(Duration::from_millis(500));
let wall_time = start.elapsed();
if harness.contains_text("panicked") {
return Err(anyhow!(
"pager rendered 'panicked' during resize_storm\nscreen:\n{}",
harness.screen_contents()
));
}
Ok(harness.bench_results("resize_storm", wall_time))
}
@@ -0,0 +1,65 @@
//! `scroll_stress` — inject rapid `j` keys against a large pre-rendered
//! response, measure frame timing.
//!
//! What it stresses: `render_scrolled_entries_with_scratch`, partial-entry
//! clipping (ScratchBuffer cell copy), `Buffer::diff()`.
use std::time::{Duration, Instant};
use anyhow::Result;
use super::{BenchResults, ContentController, PtyHarness, wait_for_welcome};
use crate::keys;
const LINES: usize = 500;
const SCROLL_KEYS: usize = 200;
const KEY_INTERVAL: Duration = Duration::from_millis(16);
pub async fn run(harness: &mut PtyHarness, content: &ContentController) -> Result<BenchResults> {
// 1. Prime the mock server with a large markdown response.
content.set_response(long_markdown_response(LINES));
// 2. Wait for the pager's splash screen.
wait_for_welcome(harness).await?;
// 3. Submit a prompt so the mock inference server returns the big response.
// The pager is interactive: type a short prompt then hit Enter.
harness.inject_keys(b"go\r")?;
// 4. Wait until the streamed response is on screen.
// The response is `Lorem ipsum dolor ...` — look for a word we know
// will appear after streaming starts.
harness.wait_for_text("Lorem", Duration::from_secs(30))?;
// 5. Let the full response settle, then reset timing to start clean.
harness.update(Duration::from_millis(500));
harness.reset_timing();
// 6. Inject scroll-down keys at a fixed interval while collecting frames.
let wall_start = Instant::now();
for _ in 0..SCROLL_KEYS {
harness.inject_keys(keys::J)?;
harness.update(KEY_INTERVAL);
if !harness.is_running() {
break;
}
}
// Drain any straggler frames.
harness.update(Duration::from_millis(250));
let wall_time = wall_start.elapsed();
Ok(harness.bench_results("scroll_stress", wall_time))
}
/// Generate `n` lines of predictable markdown. Used both as scenario
/// payload and as a basic smoke test of the wrapping pipeline.
fn long_markdown_response(n: usize) -> String {
let mut out = String::with_capacity(n * 80);
out.push_str("# Scroll stress response\n\n");
for i in 0..n {
out.push_str(&format!(
"Line {i}: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n"
));
}
out
}
@@ -0,0 +1,53 @@
//! `streaming_render` — stream a response and measure frame timing during
//! active streaming.
//!
//! What it stresses: streaming-chunk cache invalidation, `ensure_wrapped()`
//! cache misses every generation, wave animation during running turn.
use std::time::{Duration, Instant};
use anyhow::Result;
use super::{BenchResults, ContentController, PtyHarness, wait_for_welcome};
const TARGET_WORDS: usize = 400;
const STREAM_WINDOW: Duration = Duration::from_secs(4);
pub async fn run(harness: &mut PtyHarness, content: &ContentController) -> Result<BenchResults> {
content.set_response(build_response(TARGET_WORDS));
wait_for_welcome(harness).await?;
// Kick off the streamed response.
harness.inject_keys(b"stream\r")?;
// Wait for first delta to hit the screen so we're measuring the
// steady-state streaming path, not startup latency.
harness.wait_for_text("stream-bench", Duration::from_secs(20))?;
harness.reset_timing();
// Collect frames during the streaming window — the mock server paces
// itself naturally via HTTP/SSE; we just let the pipe drain.
let start = Instant::now();
while start.elapsed() < STREAM_WINDOW {
harness.update(Duration::from_millis(100));
if !harness.is_running() {
break;
}
}
let wall_time = start.elapsed();
Ok(harness.bench_results("streaming_render", wall_time))
}
fn build_response(words: usize) -> String {
let mut s = String::with_capacity(words * 10);
// Sentinel token that wait_for_text keys on — guaranteed to appear
// near the very start of the stream.
s.push_str("stream-bench ");
for i in 0..words {
s.push_str("word");
s.push_str(&i.to_string());
s.push(' ');
}
s
}