diff --git a/Cargo.lock b/Cargo.lock index 7f338367a..4d3ae0f14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13347,7 +13347,7 @@ dependencies = [ [[package]] name = "zatex" -version = "0.3.3" +version = "0.3.7" dependencies = [ "tiny-skia", "ttf-parser", @@ -13598,7 +13598,7 @@ dependencies = [ [[package]] name = "zeron" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -13623,7 +13623,7 @@ dependencies = [ [[package]] name = "zeron-audio" -version = "0.3.3" +version = "0.3.7" dependencies = [ "base64 0.22.1", "cpal 0.18.2", @@ -13635,7 +13635,7 @@ dependencies = [ [[package]] name = "zeron-cli" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -13651,7 +13651,7 @@ dependencies = [ [[package]] name = "zeron-client" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13682,7 +13682,7 @@ dependencies = [ [[package]] name = "zeron-doc" -version = "0.3.3" +version = "0.3.7" dependencies = [ "chrono", "loro", @@ -13697,7 +13697,7 @@ dependencies = [ [[package]] name = "zeron-engine" -version = "0.3.3" +version = "0.3.7" dependencies = [ "alacritty_terminal", "anyhow", @@ -13757,7 +13757,7 @@ dependencies = [ [[package]] name = "zeron-harness" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13791,7 +13791,7 @@ dependencies = [ [[package]] name = "zeron-launch" -version = "0.3.3" +version = "0.3.7" dependencies = [ "libc", "tempfile", @@ -13800,14 +13800,14 @@ dependencies = [ [[package]] name = "zeron-markdown" -version = "0.3.3" +version = "0.3.7" dependencies = [ "pulldown-cmark", ] [[package]] name = "zeron-mcp" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13829,7 +13829,7 @@ dependencies = [ [[package]] name = "zeron-mobile" -version = "0.3.3" +version = "0.3.7" dependencies = [ "async-trait", "serde", @@ -13856,14 +13856,14 @@ dependencies = [ [[package]] name = "zeron-mobile-bindgen" -version = "0.3.3" +version = "0.3.7" dependencies = [ "uniffi", ] [[package]] name = "zeron-notify" -version = "0.3.3" +version = "0.3.7" dependencies = [ "objc", "sha2", @@ -13872,11 +13872,11 @@ dependencies = [ [[package]] name = "zeron-orb" -version = "0.3.3" +version = "0.3.7" [[package]] name = "zeron-plugin-guard" -version = "0.3.3" +version = "0.3.7" dependencies = [ "serde_json", "tempfile", @@ -13884,7 +13884,7 @@ dependencies = [ [[package]] name = "zeron-preview" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13914,11 +13914,11 @@ dependencies = [ [[package]] name = "zeron-preview-label" -version = "0.3.3" +version = "0.3.7" [[package]] name = "zeron-proto" -version = "0.3.3" +version = "0.3.7" dependencies = [ "chrono", "pulldown-cmark", @@ -13929,7 +13929,7 @@ dependencies = [ [[package]] name = "zeron-rpc" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13950,7 +13950,7 @@ dependencies = [ [[package]] name = "zeron-sync" -version = "0.3.3" +version = "0.3.7" dependencies = [ "base64 0.22.1", "block2 0.6.2", @@ -13976,7 +13976,7 @@ dependencies = [ [[package]] name = "zeron-syntax" -version = "0.3.3" +version = "0.3.7" dependencies = [ "thiserror 2.0.20", "tree-sitter", @@ -14011,14 +14011,14 @@ dependencies = [ [[package]] name = "zeron-term" -version = "0.3.3" +version = "0.3.7" dependencies = [ "alacritty_terminal", ] [[package]] name = "zeron-term-link" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -14035,7 +14035,7 @@ dependencies = [ [[package]] name = "zeron-text" -version = "0.3.3" +version = "0.3.7" dependencies = [ "core-foundation 0.10.1", "core-graphics 0.24.0", @@ -14052,7 +14052,7 @@ dependencies = [ [[package]] name = "zeron-theme" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -14067,7 +14067,7 @@ dependencies = [ [[package]] name = "zeron-ui" -version = "0.3.3" +version = "0.3.7" dependencies = [ "alacritty_terminal", "anyhow", @@ -14150,7 +14150,7 @@ dependencies = [ [[package]] name = "zeron-update" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "futures", @@ -14167,11 +14167,11 @@ dependencies = [ [[package]] name = "zeron-veil" -version = "0.3.3" +version = "0.3.7" [[package]] name = "zeron-visual" -version = "0.3.3" +version = "0.3.7" dependencies = [ "base64 0.22.1", "gltf", @@ -14183,7 +14183,7 @@ dependencies = [ [[package]] name = "zeron-visual-gpu" -version = "0.3.3" +version = "0.3.7" dependencies = [ "image", "pollster 0.4.0", @@ -14194,7 +14194,7 @@ dependencies = [ [[package]] name = "zeron-voice" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "cpal 0.17.3", @@ -14213,7 +14213,7 @@ dependencies = [ [[package]] name = "zeron-voice-media" -version = "0.3.3" +version = "0.3.7" dependencies = [ "async-trait", "semver", @@ -14228,7 +14228,7 @@ dependencies = [ [[package]] name = "zeron-voice-session" -version = "0.3.3" +version = "0.3.7" dependencies = [ "async-trait", "futures", diff --git a/Cargo.toml b/Cargo.toml index 998f6d040..7865ac29a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ members = [ ] [workspace.package] -version = "0.3.3" +version = "0.3.7" edition = "2024" license = "MIT" publish = false diff --git a/apps/zgx/Cargo.lock b/apps/zgx/Cargo.lock index b685ad7cc..d096e16e9 100644 --- a/apps/zgx/Cargo.lock +++ b/apps/zgx/Cargo.lock @@ -30,7 +30,7 @@ dependencies = [ [[package]] name = "accesskit_atspi_common" version = "0.19.1" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "accesskit", "accesskit_consumer", @@ -43,7 +43,7 @@ dependencies = [ [[package]] name = "accesskit_consumer" version = "0.38.0" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "accesskit", "hashbrown 0.16.1", @@ -66,7 +66,7 @@ dependencies = [ [[package]] name = "accesskit_macos" version = "0.26.3" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "accesskit", "accesskit_consumer", @@ -79,7 +79,7 @@ dependencies = [ [[package]] name = "accesskit_unix" version = "0.22.1" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "accesskit", "accesskit_atspi_common", @@ -96,7 +96,7 @@ dependencies = [ [[package]] name = "accesskit_windows" version = "0.34.0" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "accesskit", "accesskit_consumer", @@ -6450,7 +6450,7 @@ dependencies = [ [[package]] name = "wgpu-hal" version = "29.0.4" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "android_system_properties", "arrayvec", @@ -6888,7 +6888,7 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "ahash", "android-activity", @@ -7067,7 +7067,7 @@ dependencies = [ [[package]] name = "zatex" -version = "0.3.3" +version = "0.3.7" dependencies = [ "ttf-parser", ] @@ -7233,7 +7233,7 @@ checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zeron-cli" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -7248,7 +7248,7 @@ dependencies = [ [[package]] name = "zeron-launch" -version = "0.3.3" +version = "0.3.7" dependencies = [ "libc", "windows-sys 0.61.2", @@ -7256,7 +7256,7 @@ dependencies = [ [[package]] name = "zeron-notify" -version = "0.3.3" +version = "0.3.7" dependencies = [ "objc", "sha2", @@ -7265,18 +7265,18 @@ dependencies = [ [[package]] name = "zeron-plugin-guard" -version = "0.3.3" +version = "0.3.7" dependencies = [ "serde_json", ] [[package]] name = "zeron-preview-label" -version = "0.3.3" +version = "0.3.7" [[package]] name = "zeron-proto" -version = "0.3.3" +version = "0.3.7" dependencies = [ "chrono", "pulldown-cmark 0.12.2", @@ -7287,7 +7287,7 @@ dependencies = [ [[package]] name = "zeron-theme" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -7301,7 +7301,7 @@ dependencies = [ [[package]] name = "zeron-update" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "futures", @@ -7318,7 +7318,7 @@ dependencies = [ [[package]] name = "zeron-visual" -version = "0.3.3" +version = "0.3.7" dependencies = [ "base64 0.22.1", "gltf", @@ -7330,7 +7330,7 @@ dependencies = [ [[package]] name = "zeron-visual-gpu" -version = "0.3.3" +version = "0.3.7" dependencies = [ "pollster", "tracing", @@ -7340,7 +7340,7 @@ dependencies = [ [[package]] name = "zeron-voice" -version = "0.3.3" +version = "0.3.7" dependencies = [ "anyhow", "cpal", @@ -7456,7 +7456,7 @@ dependencies = [ [[package]] name = "zgx" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "fixed_decimal", "foldhash 0.2.0", @@ -7476,6 +7476,7 @@ dependencies = [ "unicode-linebreak", "unicode-normalization", "unicode-segmentation", + "web-time", "zerotrie", "zerovec", "zgx-taffy", @@ -7484,7 +7485,7 @@ dependencies = [ [[package]] name = "zgx-3d" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "bytemuck", "zgx", @@ -7493,8 +7494,8 @@ dependencies = [ [[package]] name = "zgx-alacritty-terminal" -version = "0.26.4" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +version = "0.26.8" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "base64 0.22.1", "bitflags 2.13.2", @@ -7519,7 +7520,7 @@ dependencies = [ [[package]] name = "zgx-components" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "zgx", ] @@ -7527,7 +7528,7 @@ dependencies = [ [[package]] name = "zgx-cosmic-text" version = "0.19.14" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "bitflags 2.13.2", "fontdb", @@ -7551,7 +7552,7 @@ dependencies = [ [[package]] name = "zgx-desktop" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "accesskit", "accesskit_consumer", @@ -7602,16 +7603,17 @@ dependencies = [ [[package]] name = "zgx-ghostty-sys" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" [[package]] name = "zgx-gpu" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "ash", "block2 0.6.2", "bytemuck", + "dispatch2", "fontconfig-parser", "gif", "image", @@ -7645,8 +7647,8 @@ dependencies = [ [[package]] name = "zgx-harfrust" -version = "0.5.3" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +version = "0.5.4" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "bitflags 2.13.2", "bytemuck", @@ -7657,8 +7659,8 @@ dependencies = [ [[package]] name = "zgx-mlua" -version = "0.12.8" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +version = "0.12.9" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "bstr", "either", @@ -7673,7 +7675,7 @@ dependencies = [ [[package]] name = "zgx-run" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "serde_json", "ureq 3.5.0", @@ -7685,7 +7687,7 @@ dependencies = [ [[package]] name = "zgx-script" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "icu_locale_core", "icu_plurals", @@ -7698,6 +7700,7 @@ dependencies = [ "serde_json", "smallvec", "unicase", + "web-time", "windows", "zgx", "zgx-3d", @@ -7709,7 +7712,7 @@ dependencies = [ [[package]] name = "zgx-swash" version = "0.2.11" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "skrifa", "yazi", @@ -7719,7 +7722,7 @@ dependencies = [ [[package]] name = "zgx-taffy" version = "0.9.2" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "arrayvec", "grid", @@ -7730,7 +7733,7 @@ dependencies = [ [[package]] name = "zgx-terminal" version = "0.1.10" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "base64 0.22.1", "flate2", @@ -7745,8 +7748,8 @@ dependencies = [ [[package]] name = "zgx-vte" -version = "0.15.0" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +version = "0.15.4" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "arrayvec", "bitflags 2.13.2", @@ -7758,7 +7761,7 @@ dependencies = [ [[package]] name = "zgx-zune-jpeg" version = "0.5.15" -source = "git+https://github.com/zeronsh/zgx?rev=ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b#ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" +source = "git+https://github.com/zeronsh/zgx?rev=d391ea7276f0de5cb3d65c191bfd66c02a4c358d#d391ea7276f0de5cb3d65c191bfd66c02a4c358d" dependencies = [ "zune-core", ] diff --git a/apps/zgx/Cargo.toml b/apps/zgx/Cargo.toml index 175eef720..9a30cbf91 100644 --- a/apps/zgx/Cargo.toml +++ b/apps/zgx/Cargo.toml @@ -4,6 +4,7 @@ # patched crates (its `[patch.crates-io]`, mirrored below), and a patch here # must not reach gpui's wgpu renderer in the shipping app. It tracks zgx's # `main` branch, pinned by commit when Zeron needs one ahead of main. +# Natural editor metrics use the pinned framework API; see docs/composer.md. [workspace] @@ -31,7 +32,7 @@ layout_probe = [] [dependencies] lz4_flex = { version = "0.11", default-features = false, features = ["safe-encode", "safe-decode"] } -zgx = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } +zgx = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } # `mimalloc`: the program's allocator, in place of the system's. It hands # freed memory back to the system (the system's keeps the most it ever # held), and zgx measures 1-10% less CPU for script, text and layout work. @@ -42,7 +43,7 @@ zgx = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12 # none of it, and without it pages are placeholders ("Web view · "). # zgx-run turns it on by default, but this app takes zgx-run without its # defaults (below). Nothing on macOS or Windows. -zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b", features = ["mimalloc", "terminal", "webkitgtk"] } +zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d", features = ["mimalloc", "terminal", "webkitgtk"] } # `inspect`: devtools for `zgx inspect` (and its MCP server), asked for # with `--inspect`. `i18n`: `ui.t`'s plurals and numbers by each locale's # own rules (ICU4X's data, about 90 KB), for ui/locales' translations. @@ -50,18 +51,18 @@ zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5 # wgpu this app already links), for plugins that show 3D: the CAD plugin # hands it its own triangles (`geometry = { positions, indices, … }`). It # asks no grant; a scene draws a frame only when something in it changes. -zgx-script = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b", features = ["inspect", "i18n", "scene3d"] } +zgx-script = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d", features = ["inspect", "i18n", "scene3d"] } # A picture's pixels for the clipboard (src/images.rs): zgx's own decoder, # the formats `ui.image` shows (no features of its own: the ones zgx-desktop # turns on). -zgx-gpu = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b", default-features = false } +zgx-gpu = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d", default-features = false } # Each plugin's own database (`zeron.db`, src/plugins/db.rs): SQLite, # built in; `limits` to keep one from attaching any other file. rusqlite = { version = "0.32", features = ["bundled", "limits", "hooks"] } # `fetch`: zgx's own transport for `ui.fetch` and remote images (HTTP and # HTTPS, rustls), given to every window (src/main.rs): the app's scripts, # and plugins granted "network". Nothing else of the runner. -zgx-run = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b", default-features = false, features = ["fetch"] } +zgx-run = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d", default-features = false, features = ["fetch"] } # `webp`: `ui.image` decodes through this crate, by what its features # allow, so turning WebP on here is all it takes (the member cards' art). # `ico`: sites' favicons (the browser tab's: src/favicons.rs), most of @@ -161,7 +162,7 @@ foreign-types = "0.5" # elements, box drawing and Powerline glyphs to the cell; zgx's own renderer # draws them from the font at its text line height, gapped. Builds Ghostty # with Zig 0.16 (cached in ~/Library/Caches/zgx-ghostty). -zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b", features = ["ghostty"] } +zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d", features = ["ghostty"] } # Windows' Transparency effects (src/transparency.rs), read and watched in # the registry, until zgx reports them (zgx-asks/windows-transparency); a @@ -171,8 +172,8 @@ zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5 # DirectComposition tree of the window's own. The runtime ships with Windows # 11 (and with Edge on Windows 10); without it, pages are placeholders. [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Media_Audio", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_WindowsAndMessaging"] } -zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b", features = ["webview2"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Media_Audio", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Console", "Win32_System_Registry", "Win32_System_Threading", "Win32_System_Time", "Win32_UI_WindowsAndMessaging"] } +zgx-desktop = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d", features = ["webview2"] } # zgx's D-Bus (menus, portals) linked in rather than loaded: `zeron` is also # what a headless Linux server and every Cloud machine runs (`zeron @@ -184,13 +185,13 @@ libdbus-sys = { version = "0.2.7", features = ["vendored"] } # zgx's own patches (its root Cargo.toml): a git dependency does not bring # them, so every consumer repeats them. [patch.crates-io] -wgpu-hal = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } -winit = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } -accesskit_macos = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } -accesskit_consumer = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } -accesskit_atspi_common = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } -accesskit_unix = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } -accesskit_windows = { git = "https://github.com/zeronsh/zgx", rev = "ac935c6f888a4d2c5c8a6ac12bf47771b1a44e9b" } +wgpu-hal = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } +winit = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } +accesskit_macos = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } +accesskit_consumer = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } +accesskit_atspi_common = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } +accesskit_unix = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } +accesskit_windows = { git = "https://github.com/zeronsh/zgx", rev = "d391ea7276f0de5cb3d65c191bfd66c02a4c358d" } # zgx is slow unoptimized (its own setting): optimize dependencies, keep # this crate quick to build. diff --git a/apps/zgx/README.md b/apps/zgx/README.md index eb9f40aa3..48a11299f 100644 --- a/apps/zgx/README.md +++ b/apps/zgx/README.md @@ -7,6 +7,9 @@ keeping its state, so most work never rebuilds Rust. The Rust host actions, and speaks to a Zeron engine (`src/engine/`), which owns the account, this Mac's agents and GitHub for Cloud. +The composer's current behavior, layout and sizing contracts are documented +in [Composer](docs/composer.md). + ## Running it **Dev builds talk to Zeron's staging servers, not production.** Signing in diff --git a/apps/zgx/docs/composer.md b/apps/zgx/docs/composer.md new file mode 100644 index 000000000..bf267dfdc --- /dev/null +++ b/apps/zgx/docs/composer.md @@ -0,0 +1,236 @@ +# Composer + +The compact and expanded composers use the same `ds.Composer` component and +retain the same textarea while changing mode. The component owns text sizing +and internal geometry; the chat screen owns placement on the page. Main-chat, +side-chat and v2 consumers share the sizing contract. + +## Structure and ownership + +| Module | Responsibility | +| --- | --- | +| [`ds/composer.luau`](../ui/ds/composer.luau) | Assemble the editor, header, controls, footer and trays; resolve theme inputs; publish sizes. | +| [`ds/composer_metrics.luau`](../ui/ds/composer_metrics.luau) | Adapt the editor's natural text metrics into coherent, revisioned samples. | +| [`ds/composer_layout.luau`](../ui/ds/composer_layout.luau) | Calculate the complete target geometry and explicit text-expansion history. | +| [`ds/composer_motion.luau`](../ui/ds/composer_motion.luau) | Present one geometry snapshot per animation frame and handle interruption/snap. | +| [`screens/chat/composer.luau`](../ui/screens/chat/composer.luau) | Bind session state and place the main composer; retain the model-picker anchor and animate new-chat sends. | +| [`screens/chat/composer_place.luau`](../ui/screens/chat/composer_place.luau) | Calculate page-placement offsets from published sizes. | +| [`screens/chat/dock.luau`](../ui/screens/chat/dock.luau) | Dock at the page's foot and calculate transcript clearance. | +| [`screens/chat/lane_tab.luau`](../ui/screens/chat/lane_tab.luau) | Bind a side chat and publish its presented composer height. | + +The data flow is editor metrics → target geometry → presented geometry → +view and published sizes → page placement/transcript clearance. Footer folding +and deck/tray layout keep their own responsibilities; their measurements feed +the size contract without supplying text-layout rules. + +## Modes and visible layout + +In compact mode, one line of text sits between the leading attachment control +and trailing controls. Text exceeding the available compact width expands the +composer; an explicit newline also expands it when width is known. New-chat +placement forces the expanded form. Attachments, an active question and +dictation also force expansion. + +Expanded text occupies the width above the controls, with 16-point left/right +insets. Attachments and questions contribute a measured header above the text. +The text viewport grows with its natural wrapped content up to its limit; +additional content scrolls inside the editor. The editor manages caret reveal +and scrolling. Its native placeholder follows IME composition; a press on blank +composer space focuses the draft without a second focus change from the press +layer. Footer chips sit below the surface, and trays/deck content keep +their existing layout and interaction behavior. + +The pure `Layout.calculate(input, previous_text_expanded)` receives available +width, the last text sample, measured controls/header, resolved theme geometry +and mode flags. It returns mode, natural/limited surface height, text rectangle, +control anchors, tray inset and the next text-expansion decision. It reads no +UI state or time and does not mutate its inputs or hidden history. + +The current geometry constants are local logical points: + +| Constraint | Value | +| --- | ---: | +| Surface border | 1 per side | +| Compact inner height / total surface height | 47 / 49 | +| Compact text viewport / fallback line height | 22 | +| Expanded text side insets | 16 per side | +| Expanded text top/bottom reservation without a header | 16 / 4 | +| Expanded text box, including that top/bottom reservation | 76–260 | +| Expanded text viewport | 56–240 | +| Leading / trailing control height | 28 / 32 | +| Text-contraction hysteresis | 32 | + +Expanded total height adds the controls' reserved area, borders and any header +adjustment to the limited text box. The controls reserve at least 42 points; +the resolved control corner can increase that reservation. Header gap, corner, +typography and decoration still use the theme's tokens. `natural_height` is +computed before the text-box clamp; it is not a displayed height or transcript +reservation. + +Text expansion uses hysteresis: compact text expands above its capacity and +an expanded draft contracts only at or below capacity minus 32 points. The +previous decision is an explicit input. Forced expansion does not overwrite +text history. Unknown width preserves that history; with known width but no +sample, the previous text decision supplies the fallback. The view commits the +next decision and target geometry together in a batch. + +## Text metrics + +`Metrics.use { value, width, editor, keep?, estimate? }` returns a computed +`result` and a read-only `sample` state (the size alone: unwrapped width, +wrapped height, line height), and creates no measurement nodes. Geometry follows +the sample without subscribing to request/readiness-only changes: a new +revision of an equal size wakes no layout. The visible +textarea supplies +`Element:text_metrics(content_width)` (Rust: `EditorHandle::text_metrics`). +It uses the editor's plain/rich shaping, spans, fonts and fallback, includes a +final empty line and displayed IME composition, and excludes placeholder, +padding, border and gutter. + +The requested expanded content width is the pill width minus both borders +and both 16-point insets. It does not follow the animated textarea's insets, +height or scroll, avoiding feedback from an intermediate viewport into the +next target geometry. + +| Result field | Meaning | +| --- | --- | +| `revision`, `width` | Current request generation and expanded content width. | +| `status` | `pending` before any sample, `stale` while retaining an older sample, `ready` for the current request. | +| `sample.unwrapped_width` | Natural width used for the compact-mode decision. | +| `sample.wrapped_height`, `sample.line_height` | Natural wrapped height at the requested width and base line height. | +| `sample.width`, `sample.revision` | Width and request generation represented by the complete sample. | + +Requests follow draft, theme and settled editor metrics, including +uncommitted IME. They follow width only while the widest line doesn't fit the +requested width: a draft that fits measures the same at any width it fits, so +a pane resized asks nothing of it. A width-only query publishes immediately when the mounted +editor, draft, theme and native metric revision match the last acknowledged +request. Mount generations distinguish editor replacement from fresh userdata +wrappers. Other requests retain deferred publication, checking request and +editor revisions; replacement or unmount cancels obsolete callbacks. Width and height publish +together. Zero width of measured text is valid for an empty draft, not an +initialization sentinel; an unknown/non-positive available width cannot +publish a fresh sample. + +With `keep`, the last complete sample survives reload but starts stale until +revalidated against the mounted editor. Layout retains the last sample while +waiting; before the first sample it uses its explicit geometry fallback. +The persistence namespaces are `editor_text_metrics` and `editor_text_size`. + +`estimate(text, line_height)` stands in for the exact query where the caller +knows the answer can't change its layout. The composer passes +`Layout.estimate`: a draft with enough hard lines to fill the text box to its +cap at the last measured line height has a newline (forced open, its unwrapped +width unused) and is capped whatever it wraps to, so it is not measured again. +Finding that out looks for at most a dozen newlines. An estimate is used only +for the editor, theme and composer line-height token of the last exact +measure; a repeated equal estimate is the same request and publishes nothing. + +Framework metrics are exact. The first query per revision/width visits all +hard lines twice, past the editor's 4,096-line span cache; unchanged queries +are constant-time. A full-document query after each edit cost a 5,000-line +draft about 10,000 script calls (its highlighting) and 47 ms a keystroke, +which is why long drafts are estimated. Focus, +selection, scroll, caret blink and viewport size alone do not change the +metric revision. The API is supplied by the immutable ZGX revision pinned in +[`Cargo.toml`](../Cargo.toml), from `zeronsh/zgx` main (zgx#2148). + +## Geometry transitions and context changes + +One controller keeps origin, destination and progress, with a 220 ms `out(3)` +animation. Every view binding derives from the same presented snapshot. A changed +destination cancels the previous animation and starts from the geometry +currently presented. An unchanged visual destination retains progress, even +if natural height above the cap or other metadata changes. The view publishes +a new target only when a field it binds or the motion reads changes +(`Layout.same_target`): the pill's and text's widths, which layout applies +itself, and the natural height past the cap don't, so resizing a pane runs no +motion, frame or binding. +View bindings share a projection of the complete presented snapshot, so changes +to width or measurement metadata alone do not wake unchanged controls/insets. + +The vertical envelope and controls move together. During expansion, the editor +keeps compact width until a complete line fits above both control groups, then +switches once to the expanded width. During contraction, it takes compact width +immediately. The text top and height continue on the same vertical trajectory; +width is not continuously interpolated during a mode change. + +The viewport derives from that frame's surface, top and bottom reservations. +A separate animated clip surrounds the naturally measured header; the clip's +height never feeds back into the header measurement. These transitions retain +the textarea, draft, focus and selection, and do not write editor scroll. + +Reduced motion cancels animation and snaps to the destination. A context change +also snaps, holding that policy until the current metrics are ready and the pill +has been laid out at its target height. A deferred acknowledgement verifies +context, revision and destination before ending settlement. Page placement uses +the same context acknowledgement. Cleanup cancels animation/acknowledgement; +obsolete generations cannot update a replacement controller. + +## Published sizes and page placement + +`Composer.on_sizes` reports: + +| Field | Meaning | +| --- | --- | +| `rest` | Surface height calculated with no draft/cargo/question/dictation, retaining the forced expanded flag, plus the currently measured footer and deck. | +| `target` | Target surface height plus measured footer and deck. | +| `presented` | Actual laid-out root height, including footer/deck. | +| `active` | Whether the internal geometry transition is running. | +| `ready` | Current metrics are valid and the pill is laid out at target height. | +| `settling`, `context` | Context snap status and the generation the snapshot belongs to. | + +A new chat stands near the page's middle, under the title bar. Its top is based +on `rest`, so typing grows the composer downward without moving that top. If +the presented box would overflow the page's foot, placement lifts it by the +required amount. A session anchors at the bottom with the dock's 8-point gap. +The main chat publishes presented height through `shared.dock_h`; side chats' +`Dock.Dock` publishes their laid-out height for their transcript clearance (they +take no `on_sizes`). `on_sizes` is called only when one of its fields changes. + +While a new chat's model picker is open, a height compensation keeps its chip +and picker anchored. Closing the picker releases that compensation with a +260 ms `out(3)` animation. Sending from a new chat deliberately glides to the +session dock with the same duration, and the composer eases from its new-chat +form to its docked one on the way (no snap). The send records the session it +opens, so both effects that see the move (the page mode's and the routed +chat's) know it for a send whichever runs first. Other route/split-context changes snap; +reduced motion snaps these page movements too. Sidebar/page resizing follows +layout. The rest height and context settlement use no fixed waiting window. + +## Verification and visual diagnostics + +Run from the repository root: + +```sh +cargo test --locked --manifest-path apps/zgx/Cargo.toml --bin zeron-zgx composer +cargo test --locked --manifest-path apps/zgx/Cargo.toml --bin zeron-zgx zeron_v2 +``` + +The tests cover mode boundaries, headers, metrics/IME, interruption, context +revisions, cleanup, editor identity/focus/selection, max-height scrolling, +dictation layout, theme/transparency and logical resize/zoom reflow. Route-motion +checks compare against a second, reduced-motion shell. Set +`ZERON_ZGX_COMPOSER_TRACE=1` and use `-- --nocapture` to retain per-frame traces. + +For a local visual check, build the development binary (beta omits the fixture +CLI) and run the isolated composer preview: + +```sh +cargo build --locked --manifest-path apps/zgx/Cargo.toml --bin zeron-zgx +python3 apps/zgx/scripts/composer_frames.py --binary apps/zgx/target/debug/zeron-zgx --output .personal/composer/normal +python3 apps/zgx/scripts/composer_frames.py --binary apps/zgx/target/debug/zeron-zgx --output .personal/composer/damage --damage-check +``` + +The Linux runner needs Python, Xvfb, xdotool and ffmpeg. It records real frames, +input timing, text-region ink counts and partial/full repaint diagnostics. +The region check can detect whole-region disappearance but can miss local +clipping or missing glyphs. Diagnostic repaints alter timing, so always retain +a separate normal run. On macOS, compare native caret behavior separately with +`ZGX_NATIVE_CARET=0`; record build/platform, window size, zoom, theme, +transparency, display scale/refresh rate and the exact input sequence. + +The reported intermittent glitch has not been established as reproduced or +fixed. Headless geometry and Linux captures do not verify macOS/Windows +presentation, native IME or device-scale rendering. Existing broader-suite +failures should be assessed separately from these composer checks. diff --git a/apps/zgx/docs/plugins.md b/apps/zgx/docs/plugins.md index 6ad2dd6bd..5ac07018a 100644 --- a/apps/zgx/docs/plugins.md +++ b/apps/zgx/docs/plugins.md @@ -52,7 +52,8 @@ Your own plugins are signed as yours, and re-signed and reloaded each time you s | `navigate` | open chats and pages (`zeron.open`) | | `links.open` | open http(s) links (`zeron.open_url`), where you open links (Settings → Links) | | `notifications` | send you notifications (`zeron.notify`), as Zeron's own: Settings → Notifications decides whether they show, a few a minute at most | -| `compose` | put text in the message box (`zeron.compose`), or a review comment on it (`zeron.compose_comment`); you still send it | +| `compose` | put text in the message box, after what's there or in place of its words (`zeron.compose`), or a review comment on it (`zeron.compose_comment`); you still send it | +| `draft` | read the message box's draft as you type it (`zeron.draft`), or any chat's (`zeron.draft_of`), and take it whole, put it back, swap it or let it go (`zeron.take_draft`, `put_draft`, `swap_draft`, `drop_draft`). See [The composer's draft](#the-composers-draft) | | `github`, `github.write` | read (and write) GitHub through Zeron's engine (older calls; prefer `commands` with `gh`) | | `network` | the internet: `ui.fetch`, and remote images (`ui.image { src = "https://…" }`). See [Reaching the network](#reaching-the-network) | | `clipboard`, `files`, `web`, `windows` | zgx's clipboard, file dialogs, web views, windows | @@ -213,9 +214,13 @@ Zeron draws that row on your settings page: "Use as wallpaper", and while it's o | call | what | needs | |---|---|---| | `zeron.open("home" \| { session = id } \| { settings = page })` | open a page | `navigate` | -| `zeron.compose(text)` | text into the message box | `compose` | +| `zeron.compose(text, { replace?, session? })` | text into a chat's draft: after what's there (on a line of its own), or in place of its words (`replace = true`, its chips kept); the chat shown's draft, or `session`'s ([below](#the-composers-draft)) | `compose` | | `zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? }` | a review comment on a file or a diff, as a chip on a chat's draft (below) | `compose` | | `zeron.composed()` | in a build: your comments still on a draft, by `key`: `{ session, hovered }` | `compose` | +| `zeron.draft()` | in a build: the message box's draft, `{ session?, text, attachments = { { kind, name } } }` (below) | `draft` | +| `zeron.take_draft(key)`, `zeron.put_draft(key)`, `zeron.swap_draft(key)`, `zeron.drop_draft(key)` | the draft taken whole and kept by Zeron under your key; put back; traded with what the key keeps; let go (below) | `draft` | +| `zeron.drafts()` | in a build: what Zeron keeps for you, by key: `{ session?, text, attachments, at }` | `draft` | +| `zeron.draft_of(session)` | a promise of chat `session`'s draft as it is now, as `zeron.draft()` says it (`""`: a new chat's) | `draft` | | `zeron.toast(text)` | a short note at the window's foot | (always) | | `zeron.need("panel").open_tab { kind, title, icon?, data? }` | a tab of yours in the chat's panel; asked again, the one there is brought forward (found by `data.key` when you give one, else by its title) | `panel.tabs` | | `zeron.tab(kind, function(tab) return node end)` | how a kind of your tabs draws (`tab` = `{ kind, title, data }`) | `panel.tabs` | @@ -274,6 +279,48 @@ Comments on the diff (each cites the file and line it belongs to; L = line numbe Give each a `key` of your own: `zeron.composed()` lists yours still on a draft by it (taken off or sent, gone), and says which one's chip is under the pointer (`hovered`), so the lines it was left on can keep a mark and light up as its chip is pointed at. Zeron's Git plugin does all of this in its Changes (`plugins-builtin/git/changes.luau`): the diff's + (or a drag from it over lines) opens `ds/comment`'s composer under them, using `ds/git_changes`'s `on_comment`, `ranges` and `marks`. +### The composer's draft + +With `draft`, a plugin reads what you're typing and can set it aside and bring it back: a stash for a prompt written in the wrong chat, a counter of its length, a bar that says what it carries. + +- **`zeron.draft()`**, read in a build or an effect, is the draft shown as it changes: `session` (the chat it's for; nil on a new chat), `text` (the words as typed) and `attachments`, each chip's `kind` (`"file"`, `"image"`, `"chat"`, `"comment"`, …) and `name`. A file's path is never in it. +- **`zeron.take_draft(key)`** takes the draft shown whole (its words, its chips, the passages quoted in it) and clears the composer. Zeron keeps it, under your `key` (1 to 64 characters), so your plugin never holds a file's path. An empty draft isn't taken; taking under a key that's kept replaces what it kept. Up to 16 at once. +- **`zeron.put_draft(key)`** puts what `key` kept back on the draft shown, in whichever chat is open, and lets it go. Onto an empty composer it's as it was taken; onto words already there, its words follow after a blank line and its chips after theirs. +- **`zeron.swap_draft(key)`** trades the draft shown with what `key` keeps. Either may be empty, so one call sets the draft aside (nothing kept), brings it back (an empty composer), or swaps the two. +- **`zeron.drop_draft(key)`** lets what `key` kept go. +- **`zeron.drafts()`**, read in a build, is what Zeron keeps for you, by key: `{ session?, text, attachments, at }` (`at` as `os.time()`). Drafts are kept while Zeron runs, as chats' own drafts are. +- **`zeron.draft_of(session)`** reads another chat's draft once, shown or not: a promise of `{ session?, text, attachments }`, as `zeron.draft()` says it (`""` for a new chat's, with no session). + +With `compose` too, a plugin can change the words in place: **`zeron.compose(text, { replace = true })`** puts `text` in place of the draft's words, leaving its chips where they are, and `session` names another chat's draft. A rewrite or a snippet that expands is a read and a replace: + +```lua +-- ("ui.add", "draft", "compose"): /bug alone in the box becomes the template. +ui.effect(function() + local d = zeron.draft() + if d and d.text == "/bug" then + zeron.compose("## What happened\n\n## What I expected\n\n## Steps\n", { replace = true, session = d.session }) + end +end) +``` + +Nothing is sent: the person sees the new words in the composer, and sends or edits them. `zeron.compose` takes 20,000 characters at most. + +Each is done in the order you ask. A prompt stash is one shortcut and one chip: + +```lua +-- ⌘⇧S (Ctrl+Shift+S): set the draft aside, bring it back, or swap the two. +ui.command { id = "stash", title = "Stash prompt", key = "cmd+shift+s", run = function() + zeron.swap_draft("stash") +end } + +-- While one is kept, a chip over the composer: click to bring it back. +zeron.place { at = "#chat-composer", before = function(): Node + return ui.show(function(): boolean + return zeron.drafts().stash ~= nil + end, ui.button { "Stashed", on_click = function() zeron.swap_draft("stash") end }) +end } +``` + ## Programs and a database A plugin can do real work of its own: run the command-line tools you already use, and keep what it learns. diff --git a/apps/zgx/plugins-builtin/git/zeron.luau b/apps/zgx/plugins-builtin/git/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-builtin/git/zeron.luau +++ b/apps/zgx/plugins-builtin/git/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-builtin/github/zeron.luau b/apps/zgx/plugins-builtin/github/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-builtin/github/zeron.luau +++ b/apps/zgx/plugins-builtin/github/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-builtin/parallax-scenes/zeron.luau b/apps/zgx/plugins-builtin/parallax-scenes/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-builtin/parallax-scenes/zeron.luau +++ b/apps/zgx/plugins-builtin/parallax-scenes/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/account-pin/zeron.luau b/apps/zgx/plugins-dev/account-pin/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/account-pin/zeron.luau +++ b/apps/zgx/plugins-dev/account-pin/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/account-rotate/zeron.luau b/apps/zgx/plugins-dev/account-rotate/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/account-rotate/zeron.luau +++ b/apps/zgx/plugins-dev/account-rotate/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/checkout-status/zeron.luau b/apps/zgx/plugins-dev/checkout-status/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/checkout-status/zeron.luau +++ b/apps/zgx/plugins-dev/checkout-status/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/compact-sidebar/zeron.luau b/apps/zgx/plugins-dev/compact-sidebar/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/compact-sidebar/zeron.luau +++ b/apps/zgx/plugins-dev/compact-sidebar/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/composer-cat/zeron.luau b/apps/zgx/plugins-dev/composer-cat/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/composer-cat/zeron.luau +++ b/apps/zgx/plugins-dev/composer-cat/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/focus/zeron.luau b/apps/zgx/plugins-dev/focus/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/focus/zeron.luau +++ b/apps/zgx/plugins-dev/focus/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/keep-going/zeron.luau b/apps/zgx/plugins-dev/keep-going/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/keep-going/zeron.luau +++ b/apps/zgx/plugins-dev/keep-going/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/md-hello/zeron.luau b/apps/zgx/plugins-dev/md-hello/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/md-hello/zeron.luau +++ b/apps/zgx/plugins-dev/md-hello/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/notes-tool/zeron.luau b/apps/zgx/plugins-dev/notes-tool/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/notes-tool/zeron.luau +++ b/apps/zgx/plugins-dev/notes-tool/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/ping/zeron.luau b/apps/zgx/plugins-dev/ping/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/ping/zeron.luau +++ b/apps/zgx/plugins-dev/ping/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/session-status/zeron.luau b/apps/zgx/plugins-dev/session-status/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/session-status/zeron.luau +++ b/apps/zgx/plugins-dev/session-status/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/session-words/zeron.luau b/apps/zgx/plugins-dev/session-words/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/session-words/zeron.luau +++ b/apps/zgx/plugins-dev/session-words/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-dev/settings-demo/zeron.luau b/apps/zgx/plugins-dev/settings-demo/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-dev/settings-demo/zeron.luau +++ b/apps/zgx/plugins-dev/settings-demo/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/plugins-sdk/zeron.luau b/apps/zgx/plugins-sdk/zeron.luau index c5f896393..553b6cc16 100644 --- a/apps/zgx/plugins-sdk/zeron.luau +++ b/apps/zgx/plugins-sdk/zeron.luau @@ -69,13 +69,31 @@ -- zeron.on_message(function(message) end) -- what arrives: { from = { id, name }, data, at } ("devices") -- zeron.open(route) "home", { session = id }, { settings = page } ("navigate") --- zeron.compose(text) text into the message box, for you to send ("compose") +-- zeron.compose(text, { replace?, session? }) +-- text into the message box, for you to send: after +-- what's there, or in place of its words (`replace = +-- true`, its chips kept); the chat shown's draft, or +-- `session`'s ("compose") -- zeron.compose_comment { file, line, note, to?, side?, snippet?, key?, session? } -- a review comment chip on a session's draft, sent as -- Zeron's review comments block (file:line, the note, -- the code under it) ("compose") -- zeron.composed() in a build: your comments still on a draft, by key -- ({ [key] = { session, hovered } }), reactive ("compose") +-- zeron.draft() the composer's draft as you type it: { session?, +-- text, attachments = { { kind, name } } }, reactive +-- ("draft") +-- zeron.take_draft(key), zeron.put_draft(key), zeron.swap_draft(key), +-- zeron.drop_draft(key) +-- the draft taken whole (words, chips, quotes) and +-- kept by Zeron under your key, the composer +-- cleared; put back on the draft shown; the two +-- traded; let go ("draft") +-- zeron.drafts() what Zeron keeps for you, by key: { session?, text, +-- attachments, at }, reactive ("draft") +-- zeron.draft_of(session) +-- a promise of another chat's draft, as `draft()` +-- says it, read once ("" a new chat's) ("draft") -- zeron.toast(text) a short note at the window's foot (always) -- zeron.notify { title, body?, session? } a notification, as Zeron's -- own (Settings → Notifications) ("notifications") @@ -1343,8 +1361,16 @@ return function(id: string): any ui.invoke(`{prefix}.open_url`, url) end - function M.compose(text: string) - ui.invoke("zeron.compose.insert", text) + -- `text` into a chat's draft, for the person to send ("compose"): after + -- what's there, on a line of its own; with `replace = true`, in place of + -- its words (what it carries stays). The chat shown's draft, or + -- `session`'s ("" a new chat's). + function M.compose(text: string, opts: { replace: boolean?, session: string? }?) + if opts and (opts.replace or opts.session) then + ui.invoke("zeron.compose.insert", { text = text, replace = opts.replace == true, session = opts.session or ui.null }) + else + ui.invoke("zeron.compose.insert", text) + end end -- A review comment on a file or a diff, as a chip on a session's draft @@ -1374,6 +1400,57 @@ return function(id: string): any return composed:get() or {} end + -- The composer's draft as you type it: the chat it's for (nil, a new + -- chat), its words, and what it carries, each chip's kind ("file", + -- "image", "chat", …) and name, never a file's path. Read in a build or + -- an effect: it changes as the draft does. Nil until Zeron says. + -- (Reached on first read: only a plugin allowed "draft" may.) + local draft: any = nil + function M.draft(): { session: string?, text: string, attachments: { { kind: string, name: string } } }? + draft = draft or ui.shared("zeron.draft", nil :: any) + return draft:get() + end + + -- The draft shown, taken whole (its words, its chips, the passages + -- quoted in it) and kept by Zeron under `key`, yours, the composer + -- cleared; what that key kept before is replaced. An empty draft isn't + -- taken. Up to 16 kept at once. + function M.take_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "take", key = key }) + end + + -- What `key` kept, put back on the draft shown as it was taken (after + -- what's there, if the composer isn't empty), and no longer kept. + function M.put_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "put", key = key }) + end + + -- The draft shown and what `key` keeps, traded: either may be empty, so + -- one call sets the draft aside, brings it back, or swaps the two. + function M.swap_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "swap", key = key }) + end + + -- What `key` kept, let go of. + function M.drop_draft(key: string) + ui.invoke(`{prefix}.draft`, { op = "drop", key = key }) + end + + -- What Zeron keeps for you, by key: the chat each was taken from, its + -- words, what it carries (as `draft()` says it) and when (os.time). + -- Read in a build: it changes as you take and put back. + local drafts = ui.shared(`{prefix}.drafts`, {} :: { [string]: any }) + function M.drafts(): { [string]: { session: string?, text: string, attachments: { { kind: string, name: string } }, at: number } } + return drafts:get() or {} + end + + -- Chat `session`'s draft as it is now, unsent: shown or not (`draft()` + -- follows the one shown). A promise of { session?, text, attachments } + -- as `draft()` says it ("" a new chat's draft, with no session). + function M.draft_of(session: string): any + return ui.call(`{prefix}.draft_of`, session) + end + function M.toast(text: string) ui.invoke(`{prefix}.toast`, text) end diff --git a/apps/zgx/scripts/composer_frames.py b/apps/zgx/scripts/composer_frames.py new file mode 100644 index 000000000..570934656 --- /dev/null +++ b/apps/zgx/scripts/composer_frames.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Record the isolated composer fixture on Linux X11 and check its text region. + +Needs Xvfb, xdotool and ffmpeg. Run normal and --damage-check separately: the +comparison repaint changes rendering behavior. Output is local diagnostic data. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import time + + +def run(binary, output, damage_check): + for tool in ("Xvfb", "xdotool", "ffmpeg"): + if not shutil.which(tool): + raise SystemExit(f"required executable missing: {tool}") + output.mkdir(parents=True, exist_ok=True) + events = [] + processes = [] + logs = [] + + def launch(args, name, **kwargs): + log = (output / name).open("w") + logs.append(log) + process = subprocess.Popen(args, stdout=log, stderr=subprocess.STDOUT, **kwargs) + processes.append(process) + return process + + try: + read, write = os.pipe() + launch(["Xvfb", "-displayfd", str(write), "-screen", "0", "1280x900x24", + "-nolisten", "tcp"], "xvfb.log", pass_fds=(write,)) + os.close(write) + display = ":" + os.read(read, 64).decode().strip() + os.close(read) + env = os.environ.copy() + env.pop("WAYLAND_DISPLAY", None) + env.pop("ZGX_DAMAGE_CHECK", None) + env.update(DISPLAY=display, XDG_CONFIG_HOME=str(output / "config"), + XDG_DATA_HOME=str(output / "data"), ZERON_ZGX_ENGINE_SPAWN="0", + ZERON_ZGX_ENGINE_PORT="27963", ZERON_ZGX_ENGINE_DATA=str(output / "engine")) + if damage_check: + env["ZGX_DAMAGE_CHECK"] = "1" + app = launch([str(binary), "fixture=composer_transition_preview.luau", "--inspect"], + "app.log", env=env) + + def x(*args, check=True): + return subprocess.run(["xdotool", *map(str, args)], env=env, + capture_output=True, text=True, check=check) + + window = None + for _ in range(100): + if app.poll() is not None: + raise RuntimeError("app exited before its window appeared; see app.log") + found = x("search", "--onlyvisible", "--pid", app.pid, check=False) + if found.returncode == 0 and found.stdout.strip(): + window = found.stdout.splitlines()[-1] + break + time.sleep(.1) + if window is None: + raise RuntimeError("window did not appear within 10 seconds") + x("windowsize", window, 1200, 800) + x("windowfocus", "--sync", window) + # Allow first presentation/font setup; all timings below are native + # input pacing for a recording, never product readiness deadlines. + time.sleep(1) + video = output / "frames.mkv" + recording = launch(["ffmpeg", "-y", "-loglevel", "error", "-f", "x11grab", + "-framerate", "60", "-video_size", "1280x900", "-i", display, + "-t", "12", "-c:v", "ffv1", "-threads", "2", str(video)], + "capture.log", env=env) + start = time.monotonic() + + def click(name, at, delay): + events.append({"seconds": round(time.monotonic() - start, 3), "action": name}) + x("mousemove", at, 32, "click", 1) + time.sleep(delay) + + time.sleep(.5) + click("ten lines", 115, .08) + click("interrupt with eighty", 195, .06) + click("reverse to short", 43, .08) + click("eighty lines", 195, .5) + click("attachment header", 279, .4) + click("short with header", 43, .4) + click("remove header", 279, .4) + click("long draft for scroll/edit", 195, .4) + x("mousemove", 150, 640, "click", 1) + x("key", "ctrl+End") + x("click", "--repeat", 5, "--delay", 30, 4) + x("type", "--delay", 20, " typed after scrolling") + events.append({"seconds": round(time.monotonic() - start, 3), "action": "scroll and character typing"}) + click("short", 43, .25) + click("wrap", 470, .4) + click("reverse wrap", 43, .08) + click("interrupt wrap", 470, .3) + click("reduce motion", 380, .1) + click("short snap", 43, .05) + click("long snap", 195, .2) + # Move the pointer away before sampling CPU; caret blink and + # engine reconnects remain valid background work in this fixture. + x("mousemove", 900, 400, "click", 1) + time.sleep(.5) + + def cpu_ticks(): + fields = Path(f"/proc/{app.pid}/stat").read_text().rsplit(")", 1)[1].split() + return int(fields[11]) + int(fields[12]) + + idle = [] + for _ in range(3): + before, at = cpu_ticks(), time.monotonic() + time.sleep(.6) + idle.append(100 * (cpu_ticks() - before) / os.sysconf("SC_CLK_TCK") / (time.monotonic() - at)) + recording.wait(timeout=20) + if recording.returncode: + raise RuntimeError("capture failed; see capture.log") + # This fixed fixture region excludes toolbar/footer/buttons. A + # minimum > 50 cannot be satisfied by a caret alone. It detects whole + # text-region disappearance, not every local glyph/clip defect. + decode = subprocess.Popen(["ffmpeg", "-loglevel", "error", "-i", str(video), + "-vf", "crop=540:360:50:390,format=gray", "-f", "rawvideo", "-"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + threshold = bytes(int(i > 120) for i in range(256)) + counts = [] + frame_size = 540 * 360 + while True: + frame = decode.stdout.read(frame_size) + if not frame: + break + if len(frame) != frame_size: + raise RuntimeError("incomplete decoded frame") + counts.append(frame.translate(threshold).count(b"\1")) + if decode.wait(): + raise RuntimeError(decode.stderr.read().decode()) + app_log = (output / "app.log").read_text() + stale = re.findall(r"ZGX_DAMAGE_CHECK frame .*", app_log) + report = {"platform": platform.platform(), "content_size": [1200, 800], + "capture_size": [1280, 900], "fps": 60, "frames": len(counts), + "theme": "zeron-dark", "zoom": "100%", "transparency": "default frosted", + "damage_check": damage_check, "minimum_text_pixels": min(counts, default=0), + "suspicious_frames": [i for i, count in enumerate(counts) if count <= 50], + "damage_mismatches": stale, "idle_cpu_percent": idle, + "events": events, "text_pixels_by_frame": counts, + "limitations": "Whole-region check; native macOS/Windows and original glitch reproduction unverified."} + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({k: v for k, v in report.items() if k not in ("events", "text_pixels_by_frame")}, indent=2)) + if len(counts) < 600 or report["suspicious_frames"] or stale: + raise SystemExit("frame validation failed; inspect report.json and frames.mkv") + finally: + for process in reversed(processes): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + for log in logs: + log.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True, + help="development zeron-zgx build; beta omits the fixture CLI") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--damage-check", action="store_true") + args = parser.parse_args() + run(args.binary.resolve(), args.output.resolve(), args.damage_check) diff --git a/apps/zgx/src/agents.rs b/apps/zgx/src/agents.rs index 590cc042c..00506865c 100644 --- a/apps/zgx/src/agents.rs +++ b/apps/zgx/src/agents.rs @@ -12,7 +12,19 @@ //! login_methods = { { id, name, description?, kind, var?, //! link? } } //! (an agent from the ACP registry, as it says it is), -//! accounts = { { id, email, plan, session, week, active } } } } } +//! accounts = { { id, email, plan, session, week, active, +//! switchable, provider? } }, +//! groups?, login_for? } } } +//! An agent that keeps a login per model provider (Pi, OpenCode, Hermes) +//! also carries `groups`, its accounts by provider (`provider_groups`): +//! `{ { id, name, accounts, login?, key?, hint?, read_only } }`, each with +//! its own one in use and its own ways to add one (`login`, who Zeron signs +//! you in to; `key`, who issues the API key it adds; neither: `hint` says +//! how the agent does), and +//! `login_for`, the provider its sign-in under way is for. `agents.logins` +//! says each such agent's providers, `{ [harness] = { [provider] = { name, +//! login?, key? } } }`, for a composer's Account row; `agents.on_device` rows carry +//! their `provider` and its `group` name. //! Each agent carries all it shows, so a page keys its rows by `id` and an //! account by its `id`, and they update in place. (`session` and `week` are //! the plan's two windows, 0 to 1; `mark` is the design system's name for @@ -25,6 +37,14 @@ //! agents.cancel(id) (an action) gives up that sign-in //! agents.sign_in({ id, method }) the same, by the method an agent from the //! ACP registry offers (`login_methods`) +//! agents.sign_in({ id, provider }) the same, to one model provider of an +//! agent that keeps a login per provider +//! agents.rename({ id, account, name }) an API key's name; rejects with +//! the engine's words +//! agents.add_key({ id, provider, key, name? }) an API key for one such provider, +//! on this Mac's agent only (`remote` with +//! another device shown), checked with the +//! provider; rejects with the engine's words //! agents.set_key({ id, var, value }) a key such an agent reads from its //! environment (a `login_methods` kind //! "env_var"), kept there; failed @@ -115,6 +135,9 @@ struct Login { page: Option, /// A device code it showed, to check against that page. pairing: Option, + /// The model provider it signs in to, for an agent that keeps a login + /// per provider (its group's add row shows it); none: the agent's own. + provider: Option, } /// An agent from the ACP registry's sign-in, as it says it is @@ -196,6 +219,8 @@ thread_local! { /// (`{ ["acp."] = svg }`): ds/agent_mark finds an agent's icon there /// by its harness, so no caller has to carry it. static ICONS_SHARED: RefCell> = RefCell::default(); + /// `agents.logins`, held for every window's scripts. + static LOGINS_SHARED: RefCell> = RefCell::default(); } /// Keeps the icons a harness list carries (agents from the ACP registry). @@ -273,6 +298,8 @@ pub fn install(host: &ScriptHost) { let agents = AGENTS.with(Rc::clone); agents.shared.borrow_mut().push(host.shared("agents", agents.value())); agents.device_shared.borrow_mut().push(host.shared("agents.on_device", agents.device_value())); + // (What never changes: each per-provider agent's sign-ins.) + LOGINS_SHARED.with(|shared| shared.borrow_mut().push(host.shared("agents.logins", logins_value()))); ICONS_SHARED.with(|shared| shared.borrow_mut().push(host.shared("agent_icons", icons_value()))); if agents.shared.borrow().len() == 1 { // Usage moves as turns run: looked at again while the app is open. @@ -355,12 +382,64 @@ pub fn install(host: &ScriptHost) { let a = agents.clone(); host.async_action("agents.sign_in", move |args| { let a = a.clone(); - // `id`, or `{ id, method }` (a registry agent's method of its choosing). - let (id, method) = match args.field("id") { - Some(id) => (text(&id), args.field("method").map(text).filter(|m| !m.is_empty())), - None => (text(&args), None), + // `id`, or `{ id, method }` (a registry agent's method of its + // choosing), or `{ id, provider }` (one model provider's login of an + // agent that keeps one per provider). + let field = |key: &str| args.field(key).map(text).filter(|m| !m.is_empty()); + let (id, method, provider) = match args.field("id") { + Some(id) => (text(&id), field("method"), field("provider")), + None => (text(&args), None, None), }; - async move { crate::plugins::preview::refuse("agents.sign_in")?; a.sign_in(id, method).await.map_err(String::from) } + async move { + crate::plugins::preview::refuse("agents.sign_in")?; + a.sign_in(id, method, provider).await.map_err(String::from) + } + }); + // An API key for one provider of an agent that keeps a login per + // provider: this Mac's agents only (a key never goes to another + // device), rejecting with why not in the engine's words — which never + // hold the key. + let a = agents.clone(); + host.async_action("agents.add_key", move |args| { + let a = a.clone(); + let id = args.field("id").map(text).unwrap_or_default(); + let provider = args.field("provider").map(text).unwrap_or_default(); + let key = args.field("key").map(text).unwrap_or_default(); + let name = args.field("name").map(text).filter(|n| !n.trim().is_empty()); + async move { + crate::plugins::preview::refuse("agents.add_key")?; + a.add_key(id, provider, key, name).await + } + }); + // An API key for Cloud's agents (Settings → Providers with Cloud + // shown): kept by the vault, authorized for the account's Cloud device + // (`device`), the key every Cloud machine uses from its next turn. + // Rejects with the engine's words, which never hold the key. + let a = agents.clone(); + host.async_action("agents.cloud_key", move |args| { + let a = a.clone(); + let provider = args.field("provider").map(text).unwrap_or_default(); + let key = args.field("key").map(text).unwrap_or_default().trim().to_string(); + let device = args.field("device").map(text).unwrap_or_default(); + async move { + crate::plugins::preview::refuse("agents.cloud_key")?; + let params = cloud_key_params(&provider, &key, &device)?; + engine::get().call("VaultPutApiKey", params).await.map_err(|error| engine::outcome(&error).to_string())?; + a.load_accounts(true).await; + Ok(Value::Nil) + } + }); + // An API key's name (no secret: on whichever device shows it), rejecting + // with the engine's words. + let a = agents.clone(); + host.async_action("agents.rename", move |args| { + let a = a.clone(); + let (id, account) = harness_and_account(&args); + let name = args.field("name").map(text).unwrap_or_default(); + async move { + crate::plugins::preview::refuse("agents.rename")?; + a.rename(id, account, name).await + } }); let a = agents.clone(); host.async_action("agents.set_key", move |args| { @@ -501,6 +580,90 @@ pub(crate) fn glyph(id: &str) -> Option { } } +/// `id` as the engine's harness (an agent from the ACP registry's too). +fn harness_id(id: &str) -> Option { + serde_json::from_value(json!(id)).ok() +} + +/// One provider's accounts of an agent that keeps a login per model provider. +#[derive(Debug, PartialEq)] +struct Group { + /// Its provider's id (`openai-codex`, `anthropic`): its accounts' + /// `provider`, a sign-in's and a key's. + provider: String, + /// The provider ("ChatGPT", "Anthropic", "OpenRouter"). + name: String, + /// Its accounts: indices into the agent's list, in its order. + rows: Vec, + /// Who Zeron signs you in to for it ("ChatGPT", "Claude"): none where it + /// can't. + login: Option, + /// Who issues the API key Zeron adds for it ("OpenRouter"): none where + /// it adds none. + key: Option, +} + +/// An agent's accounts by provider: first every provider Zeron signs in to, +/// in its order, then those it adds API keys for, then any other its +/// accounts are on, in the order they come. A provider with none yet is +/// one to add (its sign-in or key). An account naming no provider (an +/// older engine's) is in the first group. +fn provider_groups(harness: zeron_proto::HarnessId, accounts: &[Json]) -> Vec { + use zeron_proto::providers::{account_group_label, api_key_option, api_key_options, login_option, login_options}; + let mut order: Vec = login_options(harness).into_iter().filter_map(|o| o.provider.map(String::from)).collect(); + for option in api_key_options(harness) { + if !order.iter().any(|p| p == option.provider) { + order.push(option.provider.to_owned()); + } + } + let first = order.first().cloned().unwrap_or_default(); + let providers: Vec = + accounts.iter().map(|a| a["provider"].as_str().map(String::from).unwrap_or_else(|| first.clone())).collect(); + for provider in &providers { + if !order.contains(provider) { + order.push(provider.clone()); + } + } + order + .into_iter() + .map(|provider| { + let rows: Vec = (0..accounts.len()).filter(|&i| providers[i] == provider).collect(); + Group { + name: account_group_label(harness, &provider), + login: login_option(harness, &provider).map(|o| o.label.to_owned()), + key: api_key_option(harness, &provider).map(|o| o.label.to_owned()), + rows, + provider, + } + }) + .filter(|g| !g.rows.is_empty() || g.login.is_some() || g.key.is_some()) + .collect() +} + +/// Each per-provider agent's providers Zeron adds to, for a composer's +/// Account row to offer (`agents.logins`): `{ [harness] = { [provider] = { +/// name, login?, key? } } }` — who it signs you in to, who issues the key. +fn logins_value() -> Value { + use zeron_proto::providers::{groups_by_provider, PROVIDERS}; + let by = PROVIDERS.iter().filter(|(h, _, _)| groups_by_provider(*h)).filter_map(|(harness, _, _)| { + let id = serde_json::to_value(harness).ok()?.as_str()?.to_owned(); + let groups: Vec<(String, Value)> = provider_groups(*harness, &[]) + .into_iter() + .map(|g| { + let value = Value::record([ + ("name", Value::from(g.name.as_str())), + ("login", g.login.as_deref().map_or(Value::Nil, Value::from)), + ("key", g.key.as_deref().map_or(Value::Nil, Value::from)), + ]); + (g.provider, value) + }) + .collect(); + Some((id, Value::record(groups.iter().map(|(k, v)| (k.as_str(), v.clone()))))) + }); + let by: Vec<(String, Value)> = by.collect(); + Value::record(by.iter().map(|(k, v)| (k.as_str(), v.clone()))) +} + /// The sign-in an agent's Add account starts: an agent signing into several /// providers starts its first (crates/proto/src/providers.rs /// `login_options`), the one the shipping app lists first. @@ -589,9 +752,41 @@ impl Agents { Some(login) if login.failed => "failed", _ => "idle", }; + // An agent that keeps a login per model provider: its + // accounts by provider, each group with its own in use and + // its own way to add one (nil: one group, as ever). + let groups = harness_id(id).filter(|h| zeron_proto::providers::groups_by_provider(*h)).map(|harness| { + let list = accounts.get(id).map(Vec::as_slice).unwrap_or_default(); + let read_only = !zeron_proto::providers::switches_accounts(harness); + let groups: Vec = provider_groups(harness, list) + .into_iter() + .map(|g| { + let rows: Vec = g.rows.iter().map(|&i| account_value(&list[i])).collect(); + Value::record([ + ("id", Value::from(g.provider.as_str())), + ("name", Value::from(g.name.as_str())), + ("login", g.login.as_deref().map_or(Value::Nil, Value::from)), + ("key", g.key.as_deref().map_or(Value::Nil, Value::from)), + ("read_only", Value::Bool(read_only)), + ("accounts", Value::List(rows.into())), + ]) + }) + .collect(); + Value::List(groups.into()) + }); Value::record([ ("id", Value::from(id)), ("name", Value::from(h["name"].as_str().unwrap_or(id))), + ("groups", groups.unwrap_or(Value::Nil)), + // Which provider's group the sign-in under way is for. + ( + "login_for", + logins + .get(id) + .and_then(|l| l.provider.as_deref()) + .filter(|_| login != "idle") + .map_or(Value::Nil, Value::from), + ), ("mark", mark(id).map_or(Value::Nil, Value::from)), // An agent added from the ACP registry: its one-ink icon // (it has no mark), and no accounts of Zeron's to show. @@ -920,8 +1115,22 @@ impl Agents { fn keep_device(&self, key: String, snapshot: &Json) { let Some(accounts) = snapshot["accounts"].as_array() else { return }; - self.device_accounts.borrow_mut().entry(key).or_default().accounts = accounts.clone(); + let changed = { + let mut devices = self.device_accounts.borrow_mut(); + let device = devices.entry(key.clone()).or_default(); + // (The first sight of a device's accounts changes nothing: its + // models were looked up with them.) + let changed = if device.seen { changed_logins(&device.accounts, accounts) } else { Vec::new() }; + device.seen = true; + device.accounts = accounts.clone(); + changed + }; self.publish_devices(); + // An agent signed in, switched, given a key or signed out lists other + // models (Pi signed in to Claude lists Claude's): its models again. + for harness in changed { + crate::chat::accounts_changed(&key, &harness); + } } /// A composer on `key`'s device: its accounts, on first sight of it. @@ -977,6 +1186,11 @@ impl Agents { let params = addressed_to(target, json!({ "harness": id, "accountId": account })); match engine::get().call("ActivateAgentAccount", params).await { Ok(snapshot) => { + // (Told against the list from before the row moved, so the + // switch counts as a change: the model list follows it.) + if let (Some(before), Some(device)) = (before, self.device_accounts.borrow_mut().get_mut(&key)) { + device.accounts = before; + } self.keep_device(key.clone(), &snapshot); if self.target.borrow().as_deref().unwrap_or_default() == key { self.take_accounts(&snapshot); @@ -1056,7 +1270,10 @@ impl Agents { /// A new account: the engine's sign-in (`StartAgentLogin`), its page /// opened, then asked after (`PollAgentLogin`) until it lands or fails. - async fn sign_in(self: Rc, id: String, method: Option) -> Result { + async fn sign_in(self: Rc, id: String, method: Option, provider: Option) -> Result { + // The provider asked for (one the engine can't sign in to says why), + // else the agent's first. + let provider = provider.or_else(|| login_provider(&id).map(String::from)); // The device it's on, for all of it (the page may show another). let device = self.target.borrow().clone(); let device = device.as_deref(); @@ -1072,11 +1289,12 @@ impl Agents { login.page = None; login.pairing = None; login.target = device.map(Into::into); + login.provider = provider.clone(); login.generation }; self.publish(); let mut params = json!({ "harness": id }); - if let Some(provider) = login_provider(&id) { + if let Some(provider) = &provider { params["provider"] = json!(provider); } // (A registry agent's method of its choosing, in the same field.) @@ -1270,7 +1488,41 @@ impl Agents { } } - async fn account_call(&self, method: &'static str, id: String, account: String) -> Result { + /// `AddAgentApiKey` on this Mac's engine — never addressed elsewhere: + /// with another device shown, refused here, the key sent nowhere. + async fn add_key(&self, id: String, provider: String, key: String, name: Option) -> Result { + if self.target.borrow().is_some() { + return Err("remote".into()); + } + let params = json!({ "harness": id, "provider": provider, "key": key, "name": name }); + match engine::get().call("AddAgentApiKey", params).await { + Ok(snapshot) => { + self.take_accounts(&snapshot); + Ok(Value::Nil) + } + // (The engine's words never hold the key; they aren't printed.) + Err(error) if engine::outcome(&error) == "offline" => Err("offline".into()), + Err(error) => Err(error), + } + } + + /// `RenameAgentAccount`, on the device shown. + async fn rename(&self, id: String, account: String, name: String) -> Result { + let params = self.addressed(json!({ "harness": id, "accountId": account, "name": name })); + match engine::get().call("RenameAgentAccount", params).await { + Ok(snapshot) => { + self.take_accounts(&snapshot); + Ok(Value::Nil) + } + Err(error) if engine::outcome(&error) == "offline" => Err("offline".into()), + Err(error) => Err(error), + } + } + + /// A switch or a removal on the device shown, rejecting with why not in + /// the engine's words (`offline` when it can't be reached), for the + /// page to say: a refusal is never silent. + async fn account_call(&self, method: &'static str, id: String, account: String) -> Result { match engine::get() .call(method, self.addressed(json!({ "harness": id, "accountId": account }))) .await @@ -1281,7 +1533,7 @@ impl Agents { } Err(error) => { eprintln!("zeron-zgx: agents: {method} failed: {error}"); - Err(fail(&error)) + Err(if fail(&error) == "offline" { "offline".into() } else { error }) } } } @@ -1527,6 +1779,15 @@ fn account_value(account: &Json, reset: Option<&Reset>) -> Value { ("session", Value::from(session)), ("week", Value::from(week_used)), ("active", Value::Bool(account["active"].as_bool().unwrap_or(false))), + ("switchable", Value::Bool(can_switch(account))), + ("provider", account["provider"].as_str().map_or(Value::Nil, Value::from)), + // An API key: no plan, so no windows to show; named by someone, or + // going by its last four. + ("key", Value::Bool(account["authKind"].as_str() == Some("api-key"))), + ( + "named", + Value::Bool(account["authKind"].as_str() == Some("api-key") && account["displayName"].as_str().is_some()), + ), ]; if account["codexResetCredits"].is_object() { let (count, list) = banked(&account["codexResetCredits"], spent); @@ -1554,11 +1815,39 @@ fn account_value(account: &Json, reset: Option<&Reset>) -> Value { #[derive(Default)] struct DeviceAccounts { accounts: Vec, + /// Its accounts have come at least once. + seen: bool, /// A composer has asked for them. asked: bool, last_forced: Option, } +/// The agents whose logins differ between two account lists: an account +/// come or gone, or another in use. (Usage alone changes nothing.) +fn changed_logins(before: &[Json], after: &[Json]) -> Vec { + fn logins(accounts: &[Json]) -> BTreeMap> { + let mut by: BTreeMap> = BTreeMap::new(); + for a in accounts { + if let (Some(harness), Some(id)) = (a["harness"].as_str(), a["id"].as_str()) { + by.entry(harness.into()).or_default().push((id.into(), a["active"].as_bool() == Some(true))); + } + } + for list in by.values_mut() { + list.sort(); + } + by + } + let (before, after) = (logins(before), logins(after)); + // (Each agent once, however many of its rows moved.) + let changed: std::collections::BTreeSet = before + .keys() + .chain(after.keys()) + .filter(|h| before.get(*h) != after.get(*h)) + .cloned() + .collect(); + changed.into_iter().collect() +} + /// Forced usage asks the provider: not more often than this. const DEVICE_USAGE_MIN: Duration = Duration::from_secs(30); /// How often usage is looked at again while the app is open. @@ -1608,12 +1897,16 @@ fn device_accounts_value(accounts: &[Json]) -> Value { ("email", Value::from(account_name(account))), ("plan", Value::from(account["planLabel"].as_str().unwrap_or(""))), ("active", Value::Bool(account["active"].as_bool().unwrap_or(false))), - ( - "can_switch", - Value::Bool(account["switchable"].as_bool().unwrap_or(false) && zeron_proto::providers::switches_accounts(id)), - ), + ("can_switch", Value::Bool(can_switch(account))), ("windows", Value::List(windows.into())), ]; + // Its model provider, where its agent keeps a login per provider + // (the Account row shows only the model's provider's), and what + // that provider's group is called. + if let Some(provider) = account["provider"].as_str().filter(|_| zeron_proto::providers::groups_by_provider(id)) { + fields.push(("provider", Value::from(provider))); + fields.push(("group", Value::from(zeron_proto::providers::account_group_label(id, provider).as_str()))); + } if let Some(error) = account["usageError"].as_str() { fields.push(("error", Value::from(error))); } @@ -1622,6 +1915,13 @@ fn device_accounts_value(accounts: &[Json]) -> Value { Value::record(by.into_iter().map(|(harness, rows)| (harness, Value::List(rows.into())))) } +/// Whether an account can be put in use: one the engine can swap to, of an +/// agent whose logins Zeron switches (never Hermes' own pool). +fn can_switch(account: &Json) -> bool { + account["switchable"].as_bool().unwrap_or(false) + && account["harness"].as_str().and_then(harness_id).is_some_and(zeron_proto::providers::switches_accounts) +} + /// What an account goes by. fn account_name(account: &Json) -> &str { account["email"].as_str().or_else(|| account["displayName"].as_str()).unwrap_or("Signed in") @@ -1666,6 +1966,59 @@ fn epoch_secs(s: &str) -> Option { mod tests { use super::*; + /// A Cloud API key goes to the vault for the account's Cloud device: + /// Anthropic's or OpenAI's only, a real key, Cloud on. + #[test] + fn a_cloud_key_is_one_cloud_runs_for_its_device() { + let ok = cloud_key_params("anthropic-key", "sk-ant-123", "cloud-acct").unwrap(); + assert_eq!(ok, json!({ "provider": "anthropic-key", "key": "sk-ant-123", "authorizedDevices": ["cloud-acct"] })); + assert!(cloud_key_params("openai-key", "sk-1", "d").is_ok()); + assert!(cloud_key_params("claude", "sk", "d").is_err(), "a login isn't a key"); + assert!(cloud_key_params("anthropic-key", "", "d").is_err()); + assert!(cloud_key_params("anthropic-key", "a\nb", "d").is_err()); + assert!(cloud_key_params("anthropic-key", &"k".repeat(5000), "d").is_err()); + assert!(cloud_key_params("anthropic-key", "sk", "").is_err(), "Cloud off"); + } + + /// Pi signed in to Claude, or another login put in use: Pi's models are + /// looked up again. Usage moving, or another agent's, isn't Pi's change. + #[test] + fn only_an_agent_whose_logins_changed_has_its_models_looked_up_again() { + let row = |harness: &str, id: &str, active: bool, used: f64| { + json!({ "id": id, "harness": harness, "active": active, "usageWindows": [{ "used": used }] }) + }; + let before = vec![row("pi", "chatgpt-a", true, 0.1), row("codex", "c1", true, 0.2)]; + // Usage alone: nothing. + let after = vec![row("pi", "chatgpt-a", true, 0.5), row("codex", "c1", true, 0.9)]; + assert!(changed_logins(&before, &after).is_empty()); + // A new Claude login for Pi: Pi. + let signed_in = vec![ + row("pi", "chatgpt-a", true, 0.1), + row("pi", "claude-b", true, 0.0), + row("codex", "c1", true, 0.2), + ]; + assert_eq!(changed_logins(&before, &signed_in), ["pi"]); + // Another in use: that agent. + let switched = vec![ + row("pi", "chatgpt-a", true, 0.1), + row("codex", "c1", false, 0.2), + row("codex", "c2", true, 0.0), + ]; + assert_eq!(changed_logins(&before, &switched), ["codex"]); + // Signed out of everything: that agent too. + assert_eq!(changed_logins(&before, &[row("codex", "c1", true, 0.2)]), ["pi"]); + // Two agents changed at once: each named once, whatever the order. + let both = vec![row("pi", "chatgpt-b", true, 0.1), row("codex", "c2", true, 0.2)]; + assert_eq!(changed_logins(&before, &both), ["codex", "pi"]); + // A switch from the composer, told against the list before its row + // moved (as switch_on does): a change, so the models follow. + let mut optimistic = before.clone(); + optimistic.push(row("pi", "chatgpt-c", false, 0.0)); + let mut engine_said = optimistic.clone(); + mark_switched(&mut engine_said, "pi", "chatgpt-c"); + assert_eq!(changed_logins(&optimistic, &engine_said), ["pi"]); + } + #[test] fn a_switch_moves_only_its_own_login_group() { let mut accounts = vec![ @@ -1710,6 +2063,63 @@ mod tests { assert_eq!(hermes[0].field("error").map(text).as_deref(), Some("no")); } + #[test] + fn a_per_provider_agents_accounts_group_by_provider() { + let pi = harness_id("pi").unwrap(); + let accounts = [ + json!({ "id": "c1", "harness": "pi", "provider": "anthropic", "active": true }), + json!({ "id": "o1", "harness": "pi", "provider": "openai-codex", "active": false }), + json!({ "id": "o2", "harness": "pi", "provider": "openai-codex", "active": true }), + json!({ "id": "k1", "harness": "pi", "provider": "kimi-coding", "active": true }), + ]; + let groups = provider_groups(pi, &accounts); + let shape: Vec<(&str, &str, Vec, Option<&str>, Option<&str>)> = groups + .iter() + .map(|g| (g.provider.as_str(), g.name.as_str(), g.rows.clone(), g.login.as_deref(), g.key.as_deref())) + .collect(); + assert_eq!(&shape[..3], &[ + // Zeron's own sign-ins first, in their order (Anthropic takes + // a Claude sign-in and an API key alike)… + ("openai-codex", "ChatGPT", vec![1, 2], Some("ChatGPT"), None), + ("anthropic", "Anthropic", vec![0], Some("Claude"), Some("Anthropic")), + // …one without accounts yet is one to add… + ("github-copilot", "GitHub Copilot", vec![], Some("GitHub Copilot"), None), + ]); + // …then the providers it adds keys for… + assert!(shape.iter().any(|g| g.0 == "openrouter" && g.4 == Some("OpenRouter") && g.2.is_empty())); + // …then one it adds neither to, its accounts still listed. + let kimi = shape.last().unwrap(); + assert_eq!((kimi.0, kimi.2.clone(), kimi.3, kimi.4), ("kimi-coding", vec![3], None, None)); + // An older engine's row, naming no provider: the first group's. + let old = provider_groups(pi, &[json!({ "id": "x", "harness": "pi" })]); + assert_eq!(old[0].rows, [0]); + } + + #[test] + fn a_device_says_each_accounts_provider_where_its_agent_keeps_one_per_provider() { + let value = device_accounts_value(&[ + json!({ "id": "o1", "harness": "pi", "provider": "openai-codex", "active": true, "switchable": true }), + json!({ "id": "g1", "harness": "pi", "provider": "github-copilot", "active": true, "switchable": true }), + json!({ "id": "x1", "harness": "grok", "provider": "issuer", "active": true, "switchable": true }), + ]); + let pi = value.field("pi").expect("pi").list().to_vec(); + assert_eq!(pi[0].field("provider").map(text).as_deref(), Some("openai-codex")); + assert_eq!(pi[0].field("group").map(text).as_deref(), Some("ChatGPT")); + assert_eq!(pi[1].field("group").map(text).as_deref(), Some("GitHub Copilot")); + // (Grok's issuer is no model provider: one group.) + let grok = value.field("grok").expect("grok").list().to_vec(); + assert!(grok[0].field("provider").is_none()); + // Each per-provider agent's providers, for the Account row to offer. + let logins = logins_value(); + let pi_logins = logins.field("pi").expect("pi"); + let copilot = pi_logins.field("github-copilot").expect("copilot"); + assert_eq!(copilot.field("login").map(text).as_deref(), Some("GitHub Copilot")); + let openrouter = pi_logins.field("openrouter").expect("openrouter"); + assert_eq!(openrouter.field("key").map(text).as_deref(), Some("OpenRouter")); + assert!(!openrouter.field("login").is_some_and(|v| v.truthy())); + assert!(logins.field("claude-code").is_none()); + } + #[test] fn accounts_read_their_two_windows() { let account = json!({ @@ -1850,6 +2260,22 @@ pub(crate) fn shown_target() -> Option { } /// `params` addressed to the device Providers shows. +/// `VaultPutApiKey`'s params for a Cloud API key: Anthropic's or OpenAI's +/// alone, a key that's there and no longer than any key is, for the +/// account's Cloud device. Else why not. +pub(crate) fn cloud_key_params(provider: &str, key: &str, device: &str) -> Result { + if !matches!(provider, "anthropic-key" | "openai-key") { + return Err("Cloud takes Anthropic and OpenAI keys".into()); + } + if key.is_empty() || key.len() > 4096 || key.chars().any(char::is_control) { + return Err("That isn't an API key".into()); + } + if device.is_empty() { + return Err("Turn Cloud on in Settings → Cloud first".into()); + } + Ok(json!({ "provider": provider, "key": key, "authorizedDevices": [device] })) +} + pub(crate) fn addressed_to_shown(params: Json) -> Json { addressed_to(shown_target().as_deref(), params) } diff --git a/apps/zgx/src/chat.rs b/apps/zgx/src/chat.rs index 83a4b933f..b8e5734fe 100644 --- a/apps/zgx/src/chat.rs +++ b/apps/zgx/src/chat.rs @@ -625,6 +625,19 @@ impl Pending { } } +/// The transcript's rows with each id once, the first kept: its list is keyed +/// by `id`, and a key shown twice is one it can't place (zgx's virtual list +/// panics, and the transcript stops updating until the chat is opened +/// again). A prompt pending here comes after the transcript's own rows, so +/// the engine's copy of it is the one kept. +fn one_row_per_id(list: &mut Vec) { + let mut ids: std::collections::HashSet> = std::collections::HashSet::with_capacity(list.len()); + list.retain(|row| match row.field("id") { + Some(Value::Str(id)) => ids.insert(id.clone()), + _ => true, + }); +} + /// An edit lease on a queued message (the engine's `BeginQueuedMessageEdit`). #[derive(Clone)] struct Lease { @@ -1351,6 +1364,36 @@ impl Chats { self.publish_views(); } + /// `harness`'s logins on `device` ("" or this one: here) changed: its + /// models looked up again, as the agent now lists them (Pi signed in to + /// Claude lists Claude's models). Here, that agent's alone; another + /// device's, only while the composer runs on it. + fn accounts_changed(self: &Rc, device: &str, harness: &str) { + let here = self.here.borrow().clone(); + if device.is_empty() || here.as_deref() == Some(device) { + if !self.models.borrow().contains_key(harness) { + return; + } + let (me, id) = (self.clone(), harness.to_owned()); + engine::get().spawn(async move { + match engine::get() + .call("ListModels", json!({ "harness": id, "force": true })) + .await + { + Ok(list) => { + me.models + .borrow_mut() + .insert(id, list.as_array().cloned().unwrap_or_default()); + me.publish_catalog(); + } + Err(error) => eprintln!("zeron-zgx: chat: {id}'s models didn't list again: {error}"), + } + }); + } else if self.remote.borrow().as_ref().is_some_and(|r| r.device == device) { + self.reload_remote(); + } + } + /// The composer now runs on `device` ("" or this one: here). fn catalog_on(self: &Rc, device: &str) { let here = self.here.borrow().clone(); @@ -1622,6 +1665,11 @@ impl Chats { /// A chat just made here (`sessions.create`), as the engine's list will /// have it: `params` is its `createChat` (`chatId`, `deviceId`, `spaceId`, /// `config`, `cwd`, `branch`, `parentChatId`). +/// An agent's logins on a device changed (src/agents.rs): its models again. +pub(crate) fn accounts_changed(device: &str, harness: &str) { + CHATS.with(|c| c.clone().accounts_changed(device, harness)); +} + pub(crate) fn made(params: &Json) { let Some(id) = params["chatId"].as_str() else { return }; let mut row = json!({ "id": id }); @@ -1749,6 +1797,15 @@ fn model_value(harness: &str, m: &Json) -> Value { if m["default"].as_bool() == Some(true) { fields.push(("default", Value::Bool(true))); } + // Where it's served from, for an agent reaching models through several + // providers (Pi signed in to Codex and OpenCode): its id and its name. + let provider = &m["provider"]; + if let (Some(pid), Some(name)) = (provider["id"].as_str(), provider["name"].as_str()) + && !pid.is_empty() + && !name.is_empty() + { + fields.push(("provider", Value::record([("id", Value::from(pid)), ("name", Value::from(name))]))); + } Value::record(fields) } @@ -2033,6 +2090,9 @@ impl View { } } open.heard = true; + // (A prompt sent from here that the tail brought: the + // engine's copy now shows, so this one goes.) + self.drop_arrived_prompts(open); break 'applied Ok(Change::Rows); } else { open.has_whole = false; @@ -2081,14 +2141,7 @@ impl View { } if result.is_ok() { open.heard = true; - let ids: Vec<&str> = open.entries.iter().map(|e| &*e.id).collect(); - let mut pending = self.pending.borrow_mut(); - if let Some(prompts) = pending.get_mut(&open.id) { - prompts.retain(|p| !ids.contains(&p.id.as_str())); - if prompts.is_empty() { - pending.remove(&open.id); - } - } + self.drop_arrived_prompts(open); } result }; @@ -2107,6 +2160,20 @@ impl View { } } + /// Prompts sent from here that the transcript now has: the engine's copy + /// shows from now on, so this device's own goes (both would be two rows + /// with one id, which the transcript's list can't show). + fn drop_arrived_prompts(&self, open: &Open) { + let ids: std::collections::HashSet<&str> = open.entries.iter().map(|e| &*e.id).collect(); + let mut pending = self.pending.borrow_mut(); + if let Some(prompts) = pending.get_mut(&open.id) { + prompts.retain(|p| !ids.contains(p.id.as_str())); + if prompts.is_empty() { + pending.remove(&open.id); + } + } + } + /// What another view of this chat has built, for the entries here that /// are the same there: a chat in a split is watched by its pane and, when /// focused, by the window too. @@ -2340,6 +2407,7 @@ impl View { if let Some(pending) = self.pending.borrow().get(&open.id) { list.extend(pending.iter().map(Pending::value)); } + one_row_per_id(&mut list); list }; // The list first: a reply that ended takes its words into its row @@ -4466,6 +4534,56 @@ fn entry_text(entry: &Json) -> String { out } +/// Whether a user entry is only Claude Code's note on a picture a tool read +/// (`[Image: original WxH, displayed at WxH. …]`, `[Image: source: …]`), as +/// zeron-harness's `is_synthetic_user_text` reads it: nothing else in it. +fn image_note_only(entry: &Json) -> bool { + let mut notes = 0; + for p in entry["parts"].as_array().into_iter().flatten() { + match p["kind"].as_str() { + Some("text") => { + let text = p["text"].as_str().unwrap_or_default().trim(); + if text.is_empty() { + continue; + } + if !is_image_note(text) { + return false; + } + notes += 1; + } + _ => return false, + } + } + notes > 0 +} + +/// The CLI's image note exactly (zeron-harness's `is_image_note`): one +/// line, `[Image: source: ]` (the path may be followed by `, original +/// WxH, displayed at WxH. …`), or `[Image: original WxH, displayed at WxH. +/// …]`. Something a person typed that only starts and ends like one +/// (`[Image: source: shot.png] why is button [x]`) is not it. +fn is_image_note(text: &str) -> bool { + if text.contains('\n') { + return false; + } + let Some(rest) = text.strip_prefix("[Image: ").and_then(|rest| rest.strip_suffix(']')) else { + return false; + }; + if let Some(path) = rest.strip_prefix("source: ") { + return !path.trim().is_empty() && !path.contains(['[', ']']); + } + fn dimensions(text: &str) -> Option<&str> { + let (width, rest) = text.split_once('x')?; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + (!width.is_empty() && width.bytes().all(|b| b.is_ascii_digit()) && digits > 0).then(|| &rest[digits..]) + } + rest.strip_prefix("original ") + .and_then(dimensions) + .and_then(|rest| rest.strip_prefix(", displayed at ")) + .and_then(dimensions) + .is_some_and(|rest| !rest.contains(['[', ']'])) +} + /// A transcript's subagents: each spawn that names its doc, once, in the order they /// were spawned, with when their turn began (a message's `tools` hold all of its). fn subagents_in(message: &Value) -> Option> { @@ -4516,6 +4634,13 @@ pub(crate) fn message(entry: &Json, model: Option<&str>) -> Option { .filter_map(|p| p["text"].as_str()) .collect::>() .join("\n\n"); + // Claude Code's note on a picture a tool read (its size as the + // model saw it), which a subagent's transcript kept as a message + // before the engine learned it isn't one: not something anyone + // said, so no bubble. + if image_note_only(entry) { + return None; + } // A message from another chat: its routing header is the agent's to // read; the transcript shows who sent it, over its words. let sender = zeron_proto::agent_messages::agent_message_sender(&text); @@ -5687,6 +5812,10 @@ fn session_value(chats: &Chats, open: &Open, offline: bool) -> Value { // Its folder on that device (a reply's pictures resolve by it). ("cwd", s(&chat["cwd"])), ("harness", Value::from(harness)), + // The agent the chat records (nil until its config is known, where + // `harness` stands in as Claude Code): whose `/` commands and skills + // its composer lists when its model isn't in the catalog shown. + ("agent", s(&config["harness"])), ("model", model), ("model_label", model_label), ("effort", s(&config["reasoning"])), @@ -5994,8 +6123,19 @@ fn seen_would_change(chat: &Json, session: &Json, now: chrono::DateTime String { + const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + let month = MONTHS.get(month0 as usize).copied().unwrap_or("Jan"); + let twelve = match hour % 12 { + 0 => 12, + h => h, + }; + format!("{month} {day}, {twelve}:{minute:02} {}", if hour < 12 { "AM" } else { "PM" }) +} + +/// [`clock`] for `at` (seconds since 1970) in this machine's time zone. #[cfg(unix)] fn stamp(at: i64) -> Option { #[repr(C)] @@ -6028,21 +6168,47 @@ fn stamp(at: i64) -> Option { } tm.assume_init() }; - let hour = match tm.hour % 12 { - 0 => 12, - h => h, + Some(clock(tm.mon as u32, tm.mday as u32, tm.hour as u32, tm.min as u32)) +} + +/// [`clock`] for `at` (seconds since 1970) in this machine's time zone: on +/// Windows through its own conversion (it has no `localtime_r`). Without +/// it every message's time was missing there, and with it the hover strip +/// that holds Copy. +#[cfg(windows)] +fn stamp(at: i64) -> Option { + use windows_sys::Win32::Foundation::{FILETIME, SYSTEMTIME}; + use windows_sys::Win32::System::Time::{FileTimeToSystemTime, SystemTimeToTzSpecificLocalTime}; + if at <= 0 { + return None; + } + // FILETIME counts 100 ns from 1601-01-01 (11,644,473,600 s before 1970). + let ticks = (at as u64).checked_add(11_644_473_600)?.checked_mul(10_000_000)?; + let file = FILETIME { + dwLowDateTime: ticks as u32, + dwHighDateTime: (ticks >> 32) as u32, }; - const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - let month = MONTHS.get(tm.mon as usize).copied().unwrap_or("Jan"); - Some(format!( - "{month} {}, {hour}:{:02} {}", - tm.mday, - tm.min, - if tm.hour < 12 { "AM" } else { "PM" } + // SAFETY: both calls read only the structs passed in and write only the + // caller's SYSTEMTIMEs; a null zone means the machine's current one. + let local = unsafe { + let mut utc: SYSTEMTIME = std::mem::zeroed(); + let mut local: SYSTEMTIME = std::mem::zeroed(); + if FileTimeToSystemTime(&file, &mut utc) == 0 + || SystemTimeToTzSpecificLocalTime(std::ptr::null(), &utc, &mut local) == 0 + { + return None; + } + local + }; + Some(clock( + u32::from(local.wMonth).checked_sub(1)?, + u32::from(local.wDay), + u32::from(local.wHour), + u32::from(local.wMinute), )) } -#[cfg(not(unix))] +#[cfg(not(any(unix, windows)))] fn stamp(_at: i64) -> Option { None } @@ -6106,6 +6272,21 @@ mod stream_tests; #[cfg(test)] mod tests { + /// A message's time reads as the shipping app's, on every platform: the + /// formatting, and a real local time from `stamp` (Windows included, + /// where it once was always missing and hid the message's hover strip). + #[test] + fn a_messages_time_reads_like_the_shipping_apps_on_every_platform() { + assert_eq!(super::clock(6, 1, 16, 12), "Jul 1, 4:12 PM"); + assert_eq!(super::clock(0, 9, 0, 5), "Jan 9, 12:05 AM"); + assert_eq!(super::clock(11, 31, 12, 0), "Dec 31, 12:00 PM"); + let at = super::stamp(1_794_600_000).expect("a time for a real moment"); + let (month, rest) = at.split_once(' ').unwrap(); + assert!(["Nov", "Dec"].contains(&month), "{at}"); + assert!(rest.ends_with(" AM") || rest.ends_with(" PM"), "{at}"); + assert_eq!(super::stamp(0), None); + } + /// Opening a chat marks it seen only while that changes something any /// viewport reads (its last message, its terminal's report, the end of /// its sleep): a chat looked at already writes nothing, so its devices' @@ -6629,6 +6810,23 @@ mod tests { assert_eq!(model.as_deref(), Some("pi/kimi-k3")); } + /// The composer asks a chat's own agent for its `/` list: the harness its + /// config records, also without a model or before its device's catalog; + /// none until the config is known (not `harness`'s Claude Code stand-in). + #[test] + fn a_sessions_agent_is_its_recorded_harness() { + let chats = Chats::default(); + let open = Open { id: "c".into(), ..Open::default() }; + let agent = |chats: &Chats| session_value(chats, &open, false).field("agent").map(text).filter(|a| !a.is_empty()); + assert_eq!(agent(&chats), None); + chats.chats.borrow_mut().insert( + "c".into(), + json!({ "id": "c", "deviceId": "laptop", "config": { "harness": "codex" } }), + ); + assert_eq!(agent(&chats).as_deref(), Some("codex")); + assert!(matches!(session_value(&chats, &open, false).field("model"), None | Some(Value::Nil))); + } + #[test] fn back_takes_a_questions_last_page_off_and_gives_its_pick() { let mut open = Open { id: "c".into(), ..Open::default() }; @@ -6993,6 +7191,33 @@ mod tests { assert!(apply(&mut entries, &mut wrong).is_err()); } + #[test] + fn claude_codes_image_note_is_no_message() { + let user = |text: &str| { + json!({ "id": "u", "role": "user", "createdAt": 1_788_900_000_000_i64, + "parts": [{ "id": "t", "kind": "text", "text": text }] }) + }; + for note in [ + "[Image: original 1884x2066, displayed at 1824x2000. Multiply coordinates by 1.03 to map to original image.]", + "[Image: source: /home/me/scratch/test.png]", + " [Image: source: /a.png, original 10x10, displayed at 10x10.]\n", + ] { + assert!(message(&user(note), None).is_none(), "{note} showed"); + } + // Words of its own around it, or a note-like line that isn't one, show. + assert!(message(&user("Look: [Image: original 10x10, displayed at 10x10.]"), None).is_some()); + assert!(message(&user("[Image: the logo]"), None).is_some()); + for typed in [ + "[Image: source: shot.png] why is button [x]", + "[Image: original mockup attached]\nmatch it exactly [urgent]", + "[Image: original mockup attached]", + "[Image: original 10x10, displayed at big]", + "[Image: source: ]", + ] { + assert!(message(&user(typed), None).is_some(), "{typed} hidden"); + } + } + #[test] fn a_transcript_s_subagents_are_listed_once_each_in_order() { let tool = |r: &str, title: &str| { @@ -7153,6 +7378,12 @@ mod tests { assert!(model_value("claude-code", &claude).field("default").is_none()); let marked = json!({ "id": "claude-opus-5-5", "default": true }); assert!(matches!(model_value("claude-code", &marked).field("default"), Some(Value::Bool(true)))); + // A model's provider rides along when the agent names one, and only then. + assert!(model_value("claude-code", &marked).field("provider").is_none()); + let pi = json!({ "id": "openai-codex/gpt-5.5", "label": "GPT-5.5", "provider": { "id": "openai-codex", "name": "Codex" } }); + let provider = model_value("pi", &pi).field("provider").cloned().expect("a provider"); + assert_eq!(provider.field("id").map(text).as_deref(), Some("openai-codex")); + assert_eq!(provider.field("name").map(text).as_deref(), Some("Codex")); } #[test] @@ -7843,6 +8074,74 @@ mod tests { assert!(!rows().contains("tail engine.log"), "the whole copy replaces it: {}", rows()); } + /// A prompt sent from here that a reopened chat's opening tail brings + /// shows once: the engine's copy, the one pending here let go. Shown twice + /// it was two rows with one id, and zgx's virtual list panicked + /// ("duplicate virtual list child key"), freezing the transcript. + #[test] + fn a_prompt_the_opening_tail_brings_shows_once() { + use super::{Entry, Open, Pending, View, draft_value}; + use serde_json::json; + use std::cell::{Cell, RefCell}; + use std::rc::Rc; + use zgx_script::{ScriptHost, Value, testing::TestApp}; + let app = TestApp::new(|runtime| ScriptHost::inline(runtime, "app", "return ui.text { \"x\" }")); + let text = |id: &str, words: &str| json!({ "id": format!("{id}p"), "kind": "text", "text": words }); + let prompt = |id: &str| json!({ "id": id, "role": "user", "parts": [text(id, "go")], "createdAt": 1_762_000_000_000_i64 }); + let reply = |id: &str| json!({ "id": id, "role": "assistant", "status": "complete", "parts": [text(id, "done")], "createdAt": 1_762_000_000_000_i64 }); + let held: Vec = [prompt("u0"), reply("a0")].into_iter().map(Entry::new).collect(); + let view = Rc::new(View { + session: app.host.shared("t.session", Value::Nil), + messages: app.host.shared("t.messages", Value::List(Rc::from([]))), + subagents: app.host.shared("t.subagents", Value::List(Rc::from([]))), + draft: app.host.shared("t.draft", draft_value("", "")), + rpc: RefCell::default(), + open: RefCell::new(Some(Open { id: "c".into(), entries: held, heard: true, has_whole: true, ..Open::default() })), + pending: RefCell::default(), + generation: Cell::new(0), + snapshot: Cell::new(false), + }); + view.pending.borrow_mut().insert( + "c".into(), + vec![Pending { + id: "u1".into(), + words: "go".into(), + paths: Vec::new(), + waiting: "sending", + retry: None, + at: None, + held: false, + row: false, + transfers: Vec::new(), + }], + ); + let ids = || -> Vec { + match view.messages.signal().with_untracked(Clone::clone) { + Value::List(rows) => rows.iter().filter_map(|r| r.field("id")).map(super::text).collect(), + other => panic!("rows: {other:?}"), + } + }; + view.publish_messages(); + assert_eq!(ids(), ["u0", "a0", "u1"], "the prompt shows at once, pending here"); + // The engine's opening tail, the prompt in it. + view.heard_frame(json!({ "reset": [reply("a0"), prompt("u1")], "historyPending": true, "count": 2 })); + assert_eq!(ids(), ["u0", "a0", "u1"], "once, the engine's copy"); + assert!(view.pending.borrow().get("c").is_none(), "the copy pending here is let go"); + } + + /// Rows that would share an id (the transcript's list is keyed by it) + /// show once, the first kept: a pending prompt after the transcript's + /// copy of it, or an entry twice over. + #[test] + fn rows_sharing_an_id_show_once() { + use zgx_script::Value; + let row = |id: &str, text: &str| Value::record([("id", Value::from(id)), ("text", Value::from(text))]); + let mut list = vec![row("u1", "engine"), row("a1", "reply"), Value::record([("text", Value::from("no id"))]), row("u1", "here")]; + super::one_row_per_id(&mut list); + let texts: Vec = list.iter().filter_map(|r| r.field("text")).map(super::text).collect(); + assert_eq!(texts, ["engine", "reply", "no id"]); + } + /// A chat opened shows its rows once its transcript has come (this /// device's copy, read first whatever its host's state), not once the /// chats list has it too; "missing" only when the list is known, hasn't diff --git a/apps/zgx/src/composer_layout_tests.rs b/apps/zgx/src/composer_layout_tests.rs new file mode 100644 index 000000000..1a6aa5341 --- /dev/null +++ b/apps/zgx/src/composer_layout_tests.rs @@ -0,0 +1,120 @@ +//! Pure geometry rules run in Luau, where the production calculation lives. +use zgx_script::{ScriptHost, Value, testing::TestApp}; + +#[test] +fn composer_geometry_rules_have_boundary_header_and_purity_coverage() { + let ui = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui"); + let report = zgx_script::test_runner::run(&ui, Some("composer geometry:"), |outcome| { + if let Some(failure) = &outcome.failure { + eprintln!("{}: {failure}", outcome.name); + } + }) + .expect("geometry tests load"); + assert_eq!(report.outcomes.len(), 10, "all geometry cases must run"); + assert_eq!(report.failed(), 0, "{report:?}"); +} + +#[test] +fn composer_headers_grow_and_shrink_without_replacing_or_covering_the_editor() { + let path = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui/composer_fixture.luau"); + let mut app = TestApp::new(|runtime| ScriptHost::new(runtime, path)); + app.ui.scene.borrow_mut().resize(700., 600.); + app.frames(30); + app.fill("role:textbox", "keep this draft"); + app.frames(30); + let field = app.find("role:textbox").unwrap(); + let editor = app.ui.editor_within(field).unwrap(); + editor.set_selection(1, 8); + let short = app.bounds("role:textbox"); + for (state, value, header) in [ + ( + "test_composer_cargo", + r#"[{"id":"f1","kind":"file","name":"notes.md"}]"#, + "notes.md", + ), + ( + "test_composer_question", + r#"{"text":"Choose a branch","options":[{"value":"main","label":"Main"}]}"#, + "Choose a branch", + ), + ] { + app.host + .set_state(state, Value::from_json(value).unwrap()) + .unwrap(); + for _ in 0..30 { + app.frames(1); + let current = app.find("role:textbox").unwrap(); + let handle = app.ui.editor_within(current).unwrap(); + assert_eq!(handle.node, editor.node); + assert_eq!(handle.selection(), (1, 8)); + assert_eq!(app.ui.input.focused(), Some(editor.node)); + assert_eq!(handle.editor.borrow().text().as_ref(), "keep this draft"); + assert_eq!(app.error(), None); + } + let field_box = app.bounds("role:textbox"); + let role = if state.ends_with("cargo") { + "button" + } else { + "radiogroup" + }; + let head = app + .find(&format!("role:{role} \"{header}\"")) + .unwrap_or_else(|| panic!("{state}: missing {header}\n{}", app.tree())); + let head_box = app.ui.scene.borrow().transformed_bounds(head); + assert!( + field_box.height > short.height, + "header opens the expanded editor" + ); + assert!( + head_box.y + head_box.height <= field_box.y, + "header overlaps the text: {head_box:?}, {field_box:?}" + ); + app.host + .set_state( + state, + if state.ends_with("cargo") { + Value::List(Vec::new().into()) + } else { + Value::Nil + }, + ) + .unwrap(); + app.frames(40); + let back = app.bounds("role:textbox"); + assert!( + (back.y - short.y).abs() < 1. && (back.height - short.height).abs() < 1., + "removing header restores the compact draft" + ); + } +} + +#[test] +fn composer_dictation_transitions_keep_the_editors_draft_and_selection() { + let path = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui/composer_fixture.luau"); + let mut app = TestApp::new(|runtime| ScriptHost::new(runtime, path)); + app.ui.scene.borrow_mut().resize(700., 600.); + app.frames(30); + app.fill("role:textbox", "retained draft"); + app.frames(30); + let field = app.find("role:textbox").unwrap(); + let editor = app.ui.editor_within(field).unwrap(); + editor.set_selection(1, 8); + for dictating in [true, false, true, false] { + app.host + .set_state("test_composer_dictating", Value::Bool(dictating)) + .unwrap(); + for _ in 0..30 { + app.frame(); + assert_eq!(app.error(), None); + let current = app.find("role:textbox").unwrap(); + assert_eq!(app.ui.editor_within(current).unwrap().node, editor.node); + assert_eq!(editor.selection(), (1, 8)); + assert_eq!(editor.value().get(), "retained draft"); + assert_eq!(app.ui.input.focused(), Some(editor.node)); + let bounds = app.bounds("role:textbox"); + assert!(bounds.width > 0. && bounds.height > 0.); + } + } +} diff --git a/apps/zgx/src/composer_metrics_tests.rs b/apps/zgx/src/composer_metrics_tests.rs new file mode 100644 index 000000000..5b24903d7 --- /dev/null +++ b/apps/zgx/src/composer_metrics_tests.rs @@ -0,0 +1,308 @@ +//! The measurement contract, exercised with the real editor provider. +use zgx_script::{ScriptHost, Value, testing::TestApp}; + +fn mount() -> TestApp { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("ui/composer_metrics_fixture.luau"); + let app = TestApp::new(|runtime| ScriptHost::new(runtime, path)); + app.ui.scene.borrow_mut().resize(800., 600.); + app.frames(3); + assert_eq!(app.error(), None); + app +} + +fn result(app: &TestApp) -> Value { + app.host + .states() + .into_iter() + .find(|(n, _)| n == "fixture_metrics_result") + .expect("fixture result") + .1 +} + +fn number(value: &Value, key: &str) -> f64 { + value + .field(key) + .and_then(Value::as_f64) + .unwrap_or_else(|| panic!("no {key}: {value:?}")) +} + +fn ready(app: &TestApp) -> Value { + let r = result(app); + assert_eq!(r.field("status"), Some(&Value::from("ready")), "{r:?}"); + let s = r.field("sample").expect("measured sample").clone(); + assert_eq!(number(&s, "revision"), number(&r, "revision"), "{r:?}"); + assert!( + (number(&s, "width") - number(&r, "width")).abs() < 0.5, + "{r:?}" + ); + s +} + +fn editor_only(app: &mut TestApp) -> zgx::scene::NodeId { + assert!(app.find(".composer-metric-line").is_none()); + assert!(app.find(".composer-metric-wrapped").is_none()); + app.find("metrics-editor") + .expect("the editor is the only text provider") +} + +#[test] +fn composer_metrics_publish_empty_text_as_a_real_sample_then_refresh_equal_size_edits() { + let mut app = mount(); + let nodes = editor_only(&mut app); + let history = app + .host + .states() + .into_iter() + .find(|(n, _)| n == "fixture_metrics_history") + .unwrap() + .1; + assert_eq!( + history.list().first(), + Some(&Value::from("pending")), + "initial zeroes are not a measured empty draft" + ); + let empty = ready(&app); + assert_eq!(number(&empty, "unwrapped_width"), 0., "{empty:?}"); + assert!(number(&empty, "wrapped_height") >= number(&empty, "line_height")); + let mut previous = empty; + for text in ["abc", "cba"] { + app.host + .set_state("fixture_metrics_text", Value::from(text)) + .unwrap(); + assert_eq!(result(&app).field("status"), Some(&Value::from("stale"))); + app.frames(3); + let sample = ready(&app); + assert!(number(&sample, "unwrapped_width") > 0.); + assert!(number(&sample, "revision") > number(&previous, "revision")); + if text == "cba" { + assert_eq!( + number(&sample, "unwrapped_width"), + number(&previous, "unwrapped_width") + ); + assert_eq!( + number(&sample, "wrapped_height"), + number(&previous, "wrapped_height") + ); + } + assert_eq!( + editor_only(&mut app), + nodes, + "edits must retain the same editor" + ); + previous = sample; + } +} + +#[test] +fn composer_metrics_reject_unknown_width_and_coalesce_replaced_requests() { + let app = mount(); + let before = ready(&app); + app.host + .set_state("fixture_metrics_width", Value::Num(0.)) + .unwrap(); + app.frames(3); + let unknown = result(&app); + assert_eq!(unknown.field("status"), Some(&Value::from("stale"))); + assert_eq!( + unknown.field("sample"), + Some(&before), + "zero width cannot replace a valid sample" + ); + for (width, text) in [ + (100., "old"), + (250., "intermediate"), + (180., "latest\nline\n"), + ] { + app.host + .set_state("fixture_metrics_width", Value::Num(width)) + .unwrap(); + app.host + .set_state("fixture_metrics_text", Value::from(text)) + .unwrap(); + } + app.frames(3); + let sample = ready(&app); + assert_eq!(number(&sample, "width"), 180.); + assert_eq!( + number(&sample, "wrapped_height"), + 3. * number(&sample, "line_height") + ); + let settled = result(&app); + app.frames(30); + assert_eq!(result(&app), settled, "idle must not publish new revisions"); +} + +#[test] +fn composer_metrics_keep_the_target_width_when_the_presented_parent_resizes() { + let app = mount(); + app.host + .set_state( + "fixture_metrics_text", + Value::from("words ".repeat(30).as_str()), + ) + .unwrap(); + app.frames(3); + let before = ready(&app); + for width in [600., 400., 200., 500.] { + app.host + .set_state("fixture_metrics_viewport", Value::Num(width)) + .unwrap(); + app.frames(2); + assert_eq!( + ready(&app), + before, + "a transient viewport width must not change target metrics" + ); + } +} + +#[test] +fn composer_metrics_revalidate_restored_samples_and_typography_changes() { + let mut app = mount(); + app.host + .set_state("fixture_metrics_text", Value::from("some words")) + .unwrap(); + app.frames(3); + let before = ready(&app); + app.host.reload().unwrap(); + assert_eq!( + result(&app).field("status"), + Some(&Value::from("stale")), + "restored measures need a fresh layout" + ); + app.frames(3); + let restored = ready(&app); + assert!(number(&restored, "revision") > number(&before, "revision")); + editor_only(&mut app); + assert!(app.host.run_command("fixture.metrics.type")); + app.frames(3); + let changed = ready(&app); + assert_eq!(number(&changed, "line_height"), 28.); + assert!(number(&changed, "revision") > number(&restored, "revision")); + assert!(number(&changed, "unwrapped_width") > number(&restored, "unwrapped_width")); +} + +#[test] +fn composer_metrics_wrap_at_requested_width_and_preserve_a_final_empty_line() { + let app = mount(); + app.host + .set_state("fixture_metrics_text", Value::from("one\ntwo\n")) + .unwrap(); + app.frames(3); + let multiline = ready(&app); + assert!( + number(&multiline, "wrapped_height") >= 3. * number(&multiline, "line_height"), + "{multiline:?}" + ); + app.host + .set_state( + "fixture_metrics_text", + Value::from("words ".repeat(30).as_str()), + ) + .unwrap(); + app.frames(3); + let wide = ready(&app); + app.host + .set_state("fixture_metrics_width", Value::Num(120.)) + .unwrap(); + app.frames(3); + let narrow = ready(&app); + assert_eq!(number(&narrow, "width"), 120.); + assert!(number(&narrow, "wrapped_height") > number(&wide, "wrapped_height")); + assert_eq!( + number(&narrow, "unwrapped_width"), + number(&wide, "unwrapped_width") + ); +} + +#[test] +fn composer_metrics_follow_styled_editor_and_uncommitted_ime_without_extra_nodes() { + let mut app = mount(); + let node = editor_only(&mut app); + app.host + .set_state("fixture_metrics_text", Value::from("@mention hello\n")) + .unwrap(); + app.frames(3); + let editor = app.ui.editor(node).unwrap(); + let shown = editor.text_metrics(320.).unwrap(); + let sample = ready(&app); + assert_eq!( + number(&sample, "unwrapped_width"), + f64::from(shown.unwrapped_width) + ); + assert_eq!( + number(&sample, "wrapped_height"), + f64::from(shown.wrapped_height) + ); + app.ui.input.focus(&app.ui.scene, Some(node)); + editor.set_selection(0, 0); + app.ui.dispatch(zgx::input::InputEvent::ImePreedit { + text: "你好世界".repeat(30), + cursor: Some((0, 0)), + }); + app.frames(3); + let composition = ready(&app); + assert!(number(&composition, "wrapped_height") > number(&sample, "wrapped_height")); + assert!(number(&composition, "revision") > number(&sample, "revision")); + assert_eq!(editor.value().get(), "@mention hello\n"); + assert_eq!(editor_only(&mut app), node); +} + +#[test] +fn composer_metrics_acknowledge_width_only_queries_without_waiting_but_revalidate_content() { + let app = mount(); + // A draft that fits measures the same at any width it fits: a resize + // asks nothing of it (a pane dragged ran the whole chain at each frame). + let fits = ready(&app); + for width in [240., 180., 360.] { + app.host + .set_state("fixture_metrics_width", Value::Num(width)) + .unwrap(); + assert_eq!(result(&app).field("status"), Some(&Value::from("ready"))); + assert_eq!(ready(&app), fits, "a width it fits asks nothing again"); + } + // One that wraps follows the width, each published at once. + app.host + .set_state( + "fixture_metrics_text", + Value::from("words ".repeat(60).as_str()), + ) + .unwrap(); + app.frames(3); + let mut previous = ready(&app); + for width in [240., 180., 360.] { + app.host + .set_state("fixture_metrics_width", Value::Num(width)) + .unwrap(); + let sample = ready(&app); + assert_eq!(number(&sample, "width"), width); + assert!(number(&sample, "revision") > number(&previous, "revision")); + previous = sample; + } + app.host + .set_state("fixture_metrics_text", Value::from("changed words")) + .unwrap(); + app.host + .set_state("fixture_metrics_width", Value::Num(120.)) + .unwrap(); + assert_eq!(result(&app).field("status"), Some(&Value::from("stale"))); + app.frames(3); + assert_eq!(number(&ready(&app), "width"), 120.); +} + +#[test] +fn composer_metrics_width_fast_path_cannot_reuse_an_editor_replaced_under_the_same_ref() { + let mut app = mount(); + let original = editor_only(&mut app); + app.host + .set_state("fixture_metrics_editor", Value::Num(2.)) + .unwrap(); + app.host + .set_state("fixture_metrics_width", Value::Num(120.)) + .unwrap(); + assert_eq!(result(&app).field("status"), Some(&Value::from("stale"))); + app.frames(3); + assert_ne!(editor_only(&mut app), original); + assert_eq!(number(&ready(&app), "width"), 120.); +} diff --git a/apps/zgx/src/composer_motion_tests.rs b/apps/zgx/src/composer_motion_tests.rs new file mode 100644 index 000000000..4ee065ad3 --- /dev/null +++ b/apps/zgx/src/composer_motion_tests.rs @@ -0,0 +1,219 @@ +use zgx_script::{ScriptHost, Value, testing::TestApp}; + +struct Controller { + app: TestApp, +} + +impl Controller { + fn new() -> Self { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("ui/composer_transition_fixture.luau"); + let app = TestApp::new(|runtime| ScriptHost::new(runtime, path)); + app.ui.scene.borrow_mut().resize(800., 600.); + let mut c = Self { app }; + c.frames(30); + c + } + + fn set(&self, key: &str, value: Value) { + self.app.host.set_state(key, value).unwrap(); + } + + fn height(&self, height: f64) { + self.set("fixture_transition_height", Value::Num(height)); + } + + fn frames(&mut self, n: usize) { + for _ in 0..n { + self.app.frame(); + assert_eq!(self.app.error(), None); + } + } + + fn report(&self) -> Value { + assert!(self.app.host.run_command("fixture.transition.inspect")); + self.app + .host + .states() + .into_iter() + .find(|(n, _)| n == "fixture_transition_report") + .unwrap() + .1 + } +} + +fn num(v: &Value, field: &str) -> f64 { + v.field(field) + .and_then(Value::as_f64) + .unwrap_or_else(|| panic!("missing {field}: {v:?}")) +} + +#[test] +fn composer_transition_rules_cover_width_clip_headers_and_interruption() { + let ui = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui"); + let report = zgx_script::test_runner::run(&ui, Some("composer transition:"), |outcome| { + if let Some(failure) = &outcome.failure { + eprintln!("{}: {failure}", outcome.name); + } + }) + .unwrap(); + assert_eq!(report.outcomes.len(), 4); + assert_eq!(report.failed(), 0, "{report:?}"); +} + +#[test] +fn composer_transition_retargets_from_the_presented_frame_and_ignores_equal_destinations() { + let mut c = Controller::new(); + c.height(132.); + c.height(22.); // Reversed before the first display frame: already home. + assert_eq!(c.report().field("active"), Some(&Value::Bool(false))); + c.height(132.); + c.frames(3); + let before = c.report(); + assert_eq!(before.field("active"), Some(&Value::Bool(true))); + c.height(500.); + let replaced = c.report(); + assert_eq!( + replaced.field("origin"), + before.field("frame"), + "retarget must start at the presented snapshot" + ); + assert_eq!(num(&replaced, "progress"), 0.); + c.frames(3); + let growing = c.report(); + c.height(900.); // Same capped geometry, different natural content height. + let unchanged = c.report(); + assert_eq!(num(&unchanged, "progress"), num(&growing, "progress")); + assert_eq!(unchanged.field("origin"), growing.field("origin")); + c.frames(1); + assert!(num(&c.report(), "progress") > num(&growing, "progress")); + c.frames(30); + let settled = c.report(); + assert_eq!(settled.field("active"), Some(&Value::Bool(false))); + assert_eq!(settled.field("frame"), settled.field("destination")); + assert!( + !c.app.clock.wants_frame(), + "completed controller must stop requesting frames" + ); + c.height(22.); + c.frames(3); + let shrinking = c.report(); + assert_eq!(shrinking.field("active"), Some(&Value::Bool(true))); + c.height(180.); + assert_eq!( + c.report().field("origin"), + shrinking.field("frame"), + "reversing a shrink also starts at the presented snapshot" + ); + c.frames(30); + assert_eq!(c.report().field("frame"), c.report().field("destination")); + assert!(!c.app.clock.wants_frame()); +} + +#[test] +fn composer_transition_context_and_reduce_motion_snap_and_cancel_the_running_clip() { + let mut c = Controller::new(); + c.height(132.); + c.frames(3); + c.set("fixture_transition_ready", Value::Bool(false)); + c.set("fixture_transition_snap", Value::Num(1.)); + let snapped = c.report(); + assert_eq!(snapped.field("frame"), snapped.field("destination")); + assert_eq!(snapped.field("active"), Some(&Value::Bool(false))); + c.frames(100); // Readiness is independent of how long the machine takes. + assert_eq!(c.report().field("settling"), Some(&Value::Bool(true))); + c.height(500.); // A late measurement still belongs to the same context. + assert_eq!(c.report().field("frame"), c.report().field("destination")); + c.set("fixture_transition_revision", Value::Num(2.)); + c.set("fixture_transition_ready", Value::Bool(true)); + c.frames(2); + assert_eq!(c.report().field("settling"), Some(&Value::Bool(false))); + c.height(100.); + c.frames(3); + assert_eq!(c.report().field("active"), Some(&Value::Bool(true))); + c.set("motion_reduce", Value::Bool(true)); + let reduced = c.report(); + assert_eq!(reduced.field("frame"), reduced.field("destination")); + assert_eq!(reduced.field("active"), Some(&Value::Bool(false))); + c.frames(30); + assert_eq!( + c.report(), + reduced, + "cancelled callbacks cannot revive the old transition" + ); + assert!(!c.app.clock.wants_frame()); +} + +#[test] +fn composer_transition_unmount_freezes_progress_and_remount_owns_a_new_controller() { + let mut c = Controller::new(); + c.height(500.); + c.frames(3); + let before = c.report(); + c.set("fixture_transition_shown", Value::Bool(false)); + let disposed = c.report(); + assert_eq!(disposed.field("active"), Some(&Value::Bool(false))); + assert_eq!(num(&disposed, "progress"), num(&before, "progress")); + c.height(100.); + c.frames(30); + assert_eq!( + c.report(), + disposed, + "unmounted controller cannot keep updating" + ); + assert!(!c.app.clock.wants_frame()); + c.set("fixture_transition_shown", Value::Bool(true)); + let new = c.report(); + assert_eq!(num(&new, "progress"), 1.); + assert_eq!(new.field("frame"), new.field("destination")); + c.height(180.); + c.frames(3); + assert_eq!(c.report().field("active"), Some(&Value::Bool(true))); + c.frames(30); + assert_eq!(c.report().field("frame"), c.report().field("destination")); +} + +#[test] +fn composer_transition_replaced_context_cannot_acknowledge_a_pending_revision() { + let mut c = Controller::new(); + c.set("fixture_transition_snap", Value::Num(1.)); + // Replace the context before its deferred acknowledgement can run. + c.set("fixture_transition_ready", Value::Bool(false)); + c.set("fixture_transition_revision", Value::Num(2.)); + c.set("fixture_transition_snap", Value::Num(2.)); + c.height(500.); + c.frames(40); + assert_eq!(c.report().field("settling"), Some(&Value::Bool(true))); + assert_eq!(c.report().field("frame"), c.report().field("destination")); + c.set("fixture_transition_ready", Value::Bool(true)); + c.frames(2); + assert_eq!(c.report().field("settling"), Some(&Value::Bool(false))); + assert!(!c.app.clock.wants_frame()); +} + +#[test] +fn composer_width_only_resize_publishes_the_frame_without_animating_and_preserves_height_motion() { + let mut c = Controller::new(); + for height in [22., 132.] { + c.height(height); + c.frames(30); + for width in [620., 580., 660.] { + c.set("fixture_transition_width", Value::Num(width)); + let report = c.report(); + assert_eq!(report.field("active"), Some(&Value::Bool(false))); + assert_eq!(report.field("frame"), report.field("destination")); + assert_eq!(num(report.field("frame").unwrap(), "width"), width); + assert!(!c.app.clock.wants_frame()); + } + } + c.height(500.); + c.frames(3); + let shown = c.report(); + c.set("fixture_transition_width", Value::Num(600.)); + let resized = c.report(); + assert_eq!(resized.field("active"), Some(&Value::Bool(true))); + assert_eq!(resized.field("origin"), shown.field("frame")); + c.frames(30); + assert_eq!(c.report().field("frame"), c.report().field("destination")); + assert!(!c.app.clock.wants_frame()); +} diff --git a/apps/zgx/src/links.rs b/apps/zgx/src/links.rs index 8d647e251..a2486dcce 100644 --- a/apps/zgx/src/links.rs +++ b/apps/zgx/src/links.rs @@ -71,6 +71,41 @@ pub fn open(url: &str) { }); } +/// Banner clicks, taken in this process. The engine posts Zeron's banners, +/// but macOS hands a click to the app its bundle names (Zeron.app's +/// interface, this process), never to the engine that posted it, so the +/// engine's own route (`open -a … zeron://notification/…`) never runs. As +/// Zeron.app's interface always has (crates/ui `notify::on_click`), the +/// click is answered here: Zeron comes forward, on the banner's chat. +pub fn take_banner_clicks() { + zeron_notify::on_click(|target| { + activate(); + clicked(&target); + }); +} + +/// A clicked banner's target (a chat, or agent updates), opened as its +/// `zeron://notification/` link is. +fn clicked(target: &str) { + open(&zeron_notify::link(target)); +} + +/// This app to the front: a banner was clicked. (Main thread: the click +/// comes through the AppKit delegate.) +#[cfg(target_os = "macos")] +fn activate() { + use objc::{class, msg_send, sel, sel_impl}; + unsafe { + let app: *mut objc::runtime::Object = msg_send![class!(NSApplication), sharedApplication]; + if !app.is_null() { + let _: () = msg_send![app, activateIgnoringOtherApps: true]; + } + } +} + +#[cfg(not(target_os = "macos"))] +fn activate() {} + fn tell(target: Target) { let seq = SEQ.with(|s| { s.set(s.get() + 1); @@ -94,6 +129,28 @@ fn tell(target: Target) { mod tests { use super::*; + fn last() -> (Option, Option) { + LAST.with(|l| { + let l = l.borrow(); + let text = |k: &str| match l.field(k) { + Some(Value::Str(s)) => Some(s.to_string()), + Some(Value::Text(s)) => Some(s.to_string()), + _ => None, + }; + (text("chat"), text("settings")) + }) + } + + /// A banner clicked in this process (macOS hands the click to the app, + /// not the engine that posted it) opens its chat as its link would. + #[test] + fn a_clicked_banner_opens_its_chat() { + clicked("chat-42"); + assert_eq!(last(), (Some("chat-42".into()), None)); + clicked(zeron_notify::AGENT_UPDATES_TARGET); + assert_eq!(last(), (None, Some("providers".into()))); + } + #[test] fn banners_and_chat_links_open_where_zeron_s_do() { assert_eq!(parse(&zeron_notify::link("chat-1")), Some((Target::Chat("chat-1".into()), None))); diff --git a/apps/zgx/src/main.rs b/apps/zgx/src/main.rs index 3b9e2fb38..e3431f7b8 100644 --- a/apps/zgx/src/main.rs +++ b/apps/zgx/src/main.rs @@ -86,6 +86,12 @@ mod split_tests; #[cfg(test)] mod route_motion_tests; #[cfg(test)] +mod composer_metrics_tests; +#[cfg(test)] +mod composer_layout_tests; +#[cfg(test)] +mod composer_motion_tests; +#[cfg(test)] mod hit_sweep_tests; #[cfg(test)] mod hit_tests; @@ -346,6 +352,8 @@ fn main() -> Result<(), Box> { } }); } + // A clicked banner: Zeron forward on its chat (src/links.rs). + links::take_banner_clicks(); let options = match screen { Screen::Intro => intro_window(), Screen::Onboarding => onboarding_window(), diff --git a/apps/zgx/src/plugins/grants.rs b/apps/zgx/src/plugins/grants.rs index 6093dfebd..2e731d6e2 100644 --- a/apps/zgx/src/plugins/grants.rs +++ b/apps/zgx/src/plugins/grants.rs @@ -39,6 +39,9 @@ pub const SHARED_READ: &[(&str, Option<&str>)] = &[ ("zeron.project", Some("zeron.sessions")), ("zeron.device", Some("zeron.devices")), ("zeron.devices", Some("zeron.devices")), + // The draft in the window's composer, for a plugin allowed "draft": + // `{ session, text, attachments = { { kind, name } } }`, never a path. + ("zeron.draft", Some("zeron.draft")), // Whether the window shows and is in front (the SDK's `zeron.window`): // work no one would see waits for it. ("zgx.window.shown", None), @@ -77,9 +80,9 @@ pub const ACTIONS: &[(&str, &str)] = &[ pub const NEVER_REPLACED: &[&str] = &["@app/screens/plugins", "@app/screens/shell/settings"]; /// Each plugin's own actions (`plugin..`). -pub const OWN_ACTIONS: &[&str] = &["result", "ack", "send", "menus", "toast", "problem", "open_tab", "add_page", "github_watch", "github_call", "store_set", "setting_status", "open_url", "notify", "cost", "run", "db", "service_call", "agents", "menu_run", "compose_comment", "file", "block"]; +pub const OWN_ACTIONS: &[&str] = &["result", "ack", "send", "menus", "toast", "problem", "open_tab", "add_page", "github_watch", "github_call", "store_set", "setting_status", "open_url", "notify", "cost", "run", "db", "service_call", "agents", "menu_run", "compose_comment", "draft", "draft_of", "file", "block"]; /// Each plugin's own shared state, to read (`plugin..`). -pub const OWN_SHARED: &[&str] = &["calls", "inbox", "records", "github", "store", "settings", "locales", "menu_items", "composed"]; +pub const OWN_SHARED: &[&str] = &["calls", "inbox", "records", "github", "store", "settings", "locales", "menu_items", "composed", "drafts"]; /// The capability naming plugin `id`'s own calls and actions. pub fn own(id: &str) -> Capability { @@ -252,6 +255,9 @@ pub fn capabilities(id: &str, permissions: &[String], change: &[String], replace "pages.add" => out.push(Capability::OverrideElement(page_selector(id))), "navigate" => out.push(named("zeron.navigate")), "compose" => out.push(named("zeron.compose")), + // Reading the composer's draft (`zeron.draft`); taking it and + // putting it back are its own action's, checked by the host. + "draft" => out.push(named("zeron.draft")), "devices" => out.push(named("zeron.devices")), "network" => out.push(Capability::Fetch), "clipboard" => out.push(Capability::Clipboard), @@ -394,6 +400,15 @@ mod tests { assert!(!got.iter().any(|c| matches!(c, Capability::Override(_)))); } + /// "draft" reads the composer's draft; "compose" alone never does. + #[test] + fn only_draft_reads_the_draft() { + let draft = Capability::Named("zeron.draft".into()); + assert_eq!(capabilities("stash", &s(&["draft"]), &[], &[]), vec![own("stash"), draft.clone()]); + assert!(!capabilities("x", &s(&["compose"]), &[], &[]).contains(&draft)); + assert!(SHARED_READ.contains(&("zeron.draft", Some("zeron.draft")))); + } + #[test] fn listed_targets_without_the_permission_give_nothing() { let got = capabilities("x", &[], &s(&["#titlebar-actions"]), &s(&["@app/screens/chat"])); diff --git a/apps/zgx/src/plugins/mod.rs b/apps/zgx/src/plugins/mod.rs index 43e8a8776..a557ef1bc 100644 --- a/apps/zgx/src/plugins/mod.rs +++ b/apps/zgx/src/plugins/mod.rs @@ -456,6 +456,88 @@ pub(crate) fn comment(asked: &Value, shown: &str) -> Option { Some(json_value(&out)) } +/// The longest key a plugin keeps a taken draft under. +const DRAFT_KEY: usize = 64; + +/// A plugin's ask of the composer's draft (`zeron.take_draft`, +/// `put_draft`, `swap_draft`, `drop_draft`), held to `{ op, key }`: `op` +/// one of "take", "put", "swap" or "drop", `key` 1 to 64 characters with +/// no control characters. Anything else is refused. +pub(crate) fn draft_ask(asked: &Value) -> Option { + let op = asked.field("op").map(text)?; + let key = asked.field("key").map(text)?; + let valid_key = !key.is_empty() && key.chars().count() <= DRAFT_KEY && !key.chars().any(char::is_control); + if !matches!(op.as_str(), "take" | "put" | "swap" | "drop") || !valid_key { + return None; + } + Some(Value::record([("op", Value::from(op.as_str())), ("key", Value::from(key.as_str()))])) +} + +/// What `zeron.compose` asks of the composer: its words alone (added to +/// the draft shown, as ever), or with `{ text, replace, session }` (the +/// draft's words replaced, or a chat named other than the one shown). +pub(crate) fn compose(asked: &Value) -> Value { + let Some(words) = asked.field("text") else { + return Value::from(text(asked).as_str()); + }; + let words = match words { + Value::Str(_) | Value::Text(_) => words.clone(), + _ => Value::from(""), + }; + let mut fields = vec![ + ("text", words), + ("replace", Value::from(matches!(asked.field("replace"), Some(Value::Bool(true))))), + ]; + if let Some(session) = asked.field("session").map(text).filter(|s| !s.is_empty()) { + fields.push(("session", Value::from(session.as_str()))); + } + Value::record(fields) +} + +/// The app's shared states a chat's draft lives in (screens/chat/shared), +/// each read with the value the app starts it at: read before the app has +/// made one, it's made as the app would. +const DRAFT_HERE: &str = "chat.composer.here"; +const DRAFT_TEXT: &str = "chat.composer.text"; +const DRAFT_CARGO: &str = "chat.composer.cargo"; +const DRAFTS_KEPT: &str = "chat.composer.drafts"; + +/// What a draft carries, as plugins are told it (as `zeron.draft()` says +/// it, screens/plugins): each chip's kind and name, never a file's path. +fn draft_attachments(cargo: &Value) -> Value { + let said = |item: &Value, field: &str, or: &str| match item.field(field) { + Some(v @ Value::Str(_)) => v.clone(), + _ => Value::from(or), + }; + vlist(cargo.items().iter().map(|item| Value::record([("kind", said(item, "kind", "file")), ("name", said(item, "name", ""))])).collect()) +} + +/// Chat `session`'s draft, for `zeron.draft_of` ("draft"): out in the +/// composer (`here` its chat, "" a new chat's; `shown` its words, `cargo` +/// its chips) or kept for it (`kept`, by chat). Its words as typed, what it +/// carries, and its chat (none for a new chat's). A chat with no draft has +/// no words and carries nothing. +pub(crate) fn draft_of(session: &str, here: &Value, shown: &Value, cargo: &Value, kept: &Value) -> Value { + let (words, carried) = if session == text(here) { + (shown.clone(), cargo.clone()) + } else { + let d = kept.field(session); + ( + d.and_then(|d| d.field("text")).cloned().unwrap_or_default(), + d.and_then(|d| d.field("cargo")).cloned().unwrap_or_default(), + ) + }; + let words = match words { + Value::Str(_) | Value::Text(_) => words, + _ => Value::from(""), + }; + let mut fields = vec![("text", words), ("attachments", draft_attachments(&carried))]; + if !session.is_empty() { + fields.push(("session", Value::from(session))); + } + Value::record(fields) +} + /// Plugins for the main window `cx` shows `host` in. pub fn install(cx: &mut WindowContext, host: &ScriptHost) { expose_surface(host); @@ -2398,6 +2480,49 @@ impl Bridge { } } }); + // The composer's draft taken (its words, its chips, the passages + // quoted in it), put back or let go, under a key of the plugin's, + // for a plugin allowed "draft": screens/plugins keeps what's taken + // (the plugin never holds its files' paths) and tells it what it + // keeps as `plugin..drafts`. + host.action(format!("plugin.{id}.draft"), { + let (me, plugin) = (me.clone(), plugin.clone()); + move |asked| { + if let Some(b) = me.upgrade() + && b.item(&plugin).is_some_and(|i| i.may("draft")) + { + match draft_ask(&asked) { + Some(asked) => b.request("draft", &plugin, asked), + None => eprintln!("zeron-zgx: plugin {plugin}: a draft ask that isn't take, put, swap or drop with a key, refused"), + } + } + } + }); + // Another chat's draft, as it is (`zeron.draft_of`, "draft"): read + // where the app keeps it, once, never followed. + host.async_action(format!("plugin.{id}.draft_of"), { + let (me, plugin) = (me.clone(), plugin.clone()); + move |asked| { + let (me, plugin) = (me.clone(), plugin.clone()); + async move { + let b = me.upgrade().ok_or("This plugin isn't on")?; + let item = b.item(&plugin).ok_or("This plugin isn't on")?; + if !item.may("draft") { + return Err("This plugin wasn't allowed to read what you type in the message box".to_string()); + } + let session = text(&asked); + if session.chars().count() > 200 { + return Err("That isn't a chat".to_string()); + } + let read = |name: &str, initial: Value| b.host.shared(name, initial).signal().with_untracked(Value::clone); + let here = read(DRAFT_HERE, Value::from("")); + let shown = read(DRAFT_TEXT, Value::from("")); + let cargo = read(DRAFT_CARGO, vlist(Vec::new())); + let kept = read(DRAFTS_KEPT, Value::record(Vec::<(&str, Value)>::new())); + Ok(draft_of(&session, &here, &shown, &cargo, &kept)) + } + } + }); host.action(format!("plugin.{id}.open_url"), { let (me, plugin) = (me.clone(), plugin.clone()); move |url| { @@ -3298,9 +3423,9 @@ impl Bridge { }); host.action("zeron.compose.insert", { let me = me.clone(); - move |text_| { + move |asked| { if let Some(b) = me.upgrade() { - b.request("compose", "", Value::from(text(&text_).as_str())); + b.request("compose", "", compose(&asked)); } } }); @@ -3442,6 +3567,52 @@ mod tests { assert_eq!(gone, vec!["clock".to_string(), "ping".to_string()]); } + /// `zeron.compose(text)` adds its words as ever; with options, it says + /// whether they replace the draft and which chat's (none: the shown). + #[test] + fn compose_takes_words_alone_or_with_replace_and_a_chat() { + assert_eq!(compose(&Value::from("hello")), Value::from("hello")); + let asked = json_value(&json!({ "text": "clearer", "replace": true, "session": "s2" })); + let out = compose(&asked); + assert_eq!(text(out.field("text").unwrap()), "clearer"); + assert_eq!(out.field("replace"), Some(&Value::from(true))); + assert_eq!(text(out.field("session").unwrap()), "s2"); + // (Only `true` replaces; a blank chat is the one shown; words that + // aren't text are none.) + let loose = json_value(&json!({ "text": 5, "replace": "yes", "session": "" })); + let out = compose(&loose); + assert_eq!(text(out.field("text").unwrap()), ""); + assert_eq!(out.field("replace"), Some(&Value::from(false))); + assert!(out.field("session").is_none()); + } + + /// `zeron.draft_of`: the chat shown's draft (from the composer), or + /// another chat's (kept), with its chat and its chips by kind and name + /// alone; a new chat's has no chat; a chat with none, nothing. + #[test] + fn a_chats_draft_is_read_where_it_is_kept_without_paths() { + let kept = json_value(&json!({ + "s2": { "text": "kept words", "cargo": [{ "kind": "file", "name": "a.rs", "path": "/Users/me/a.rs" }] }, + "": { "text": "new chat words", "cargo": [] }, + })); + let (here, shown) = (Value::from("s1"), Value::from("typing now")); + let cargo = json_value(&json!([{ "kind": "image", "name": "shot.png", "path": "/tmp/shot.png" }])); + let out = draft_of("s1", &here, &shown, &cargo, &kept); + assert_eq!(value_json(&out), json!({ "text": "typing now", "session": "s1", "attachments": [{ "kind": "image", "name": "shot.png" }] })); + let out = draft_of("s2", &here, &shown, &cargo, &kept); + assert_eq!(value_json(&out), json!({ "text": "kept words", "session": "s2", "attachments": [{ "kind": "file", "name": "a.rs" }] })); + assert!(!out.to_json().contains("/Users/me"), "never a path"); + // A chat with no draft: nothing written, nothing carried. + let out = draft_of("s9", &here, &shown, &cargo, &kept); + assert_eq!(value_json(&out), json!({ "text": "", "session": "s9", "attachments": [] })); + // A new chat's draft, kept while a chat shows: no chat. + let out = draft_of("", &here, &shown, &cargo, &kept); + assert_eq!(value_json(&out), json!({ "text": "new chat words", "attachments": [] })); + // Before the app has made its states: nothing, not an error. + let out = draft_of("s1", &Value::Nil, &Value::Nil, &Value::Nil, &Value::Nil); + assert_eq!(text(out.field("text").unwrap()), ""); + } + /// R21: a plugin's review comment goes on the chat shown alone, with /// at most the 40 lines of code that are sent (a 20,000-character /// snippet once rode along unseen, onto any chat's draft). @@ -3462,6 +3633,23 @@ mod tests { assert!(text(comment(&wide, "s1").unwrap().field("snippet").unwrap()).len() <= COMMENT_BYTES); } + /// A plugin's ask of the draft is take, put, swap or drop, under a key + /// of 1 to 64 characters; nothing else rides along to the app. + #[test] + fn a_draft_ask_is_take_put_or_drop_with_a_key() { + let ask = |v: Json| draft_ask(&json_value(&v)); + let took = ask(json!({ "op": "take", "key": "stash", "extra": "dropped" })).expect("a take"); + assert_eq!(value_json(&took), json!({ "op": "take", "key": "stash" })); + assert!(ask(json!({ "op": "put", "key": "k".repeat(64) })).is_some()); + assert!(ask(json!({ "op": "drop", "key": "é" })).is_some()); + assert!(ask(json!({ "op": "swap", "key": "stash" })).is_some()); + assert!(ask(json!({ "op": "send", "key": "stash" })).is_none(), "not an op"); + assert!(ask(json!({ "op": "take", "key": "" })).is_none(), "no key"); + assert!(ask(json!({ "op": "take" })).is_none(), "no key"); + assert!(ask(json!({ "op": "take", "key": "k".repeat(65) })).is_none(), "too long"); + assert!(ask(json!({ "op": "take", "key": "a\nb" })).is_none(), "a control character"); + } + #[test] fn only_a_plugin_on_loads_from_its_snapshot_with_its_grants() { let on = item(json!({ diff --git a/apps/zgx/src/plugins/preview.rs b/apps/zgx/src/plugins/preview.rs index f6b43c8ad..4b3e7a029 100644 --- a/apps/zgx/src/plugins/preview.rs +++ b/apps/zgx/src/plugins/preview.rs @@ -79,6 +79,9 @@ pub const BLOCKED: &[&str] = &[ "chat.configure", "agents.install", "agents.set_key", + // (An API key, and what an agent's keys are called.) + "agents.add_key", + "agents.rename", "agents.sign_in", "agents.sign_out", "agents.remove", @@ -92,6 +95,7 @@ pub const BLOCKED: &[&str] = &[ "projects.clone", "projects.delete", "github.disconnect", + "github.forget", "engine.restart", "billing.checkout", // (Each runs a machine, or says which one new chats run on: credits.) @@ -536,12 +540,48 @@ mod tests { std::fs::write(path, text).unwrap(); } + /// Every action the app's code refuses to a preview (`refuse("…")`, + /// `refuse_aloud("…")`) is in `BLOCKED`: else its refusal never fires. + #[test] + fn every_action_the_code_refuses_is_blocked() { + fn walk(dir: &Path, out: &mut Vec<(PathBuf, String)>) { + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + out.push((path.clone(), std::fs::read_to_string(&path).unwrap())); + } + } + } + let mut files = Vec::new(); + walk(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files); + let mut named = Vec::new(); + for (path, text) in &files { + for marker in ["refuse(\"", "refuse_aloud(\""] { + let mut rest = text.as_str(); + while let Some(at) = rest.find(marker) { + rest = &rest[at + marker.len()..]; + let Some(end) = rest.find('"') else { break }; + let action = &rest[..end]; + // (Action names only: this test's own doc says `refuse("…")`.) + if action.chars().all(|c| c.is_ascii_lowercase() || c == '_' || c == '.') { + named.push((path.display().to_string(), action.to_string())); + } + } + } + } + assert!(named.iter().any(|(_, a)| a == "agents.add_key"), "the scan finds the calls"); + let missing: Vec<_> = named.iter().filter(|(_, action)| !blocked(action)).collect(); + assert!(missing.is_empty(), "refused but not in BLOCKED: {missing:?}"); + } + #[test] fn preview_refuses_the_dangerous_actions_only() { set(None); assert!(refuse("terminal.start").is_ok(), "nothing in preview: all allowed"); set(Some(Preview { id: "agent".into(), name: "Agent's".into() })); - for action in ["terminal.start", "terminal.write", "account.sign_out", "account.delete", "plugins.install", "templates.use", "files.write", "chat.send", "chat.respond", "chat.retry", "chat.queue_edit", "chat.queue_finish", "chat.configure", "files.open_external"] { + for action in ["terminal.start", "terminal.write", "account.sign_out", "account.delete", "plugins.install", "templates.use", "files.write", "chat.send", "chat.respond", "chat.retry", "chat.queue_edit", "chat.queue_finish", "chat.configure", "files.open_external", "github.forget", "github.disconnect"] { assert!(refuse(action).is_err(), "{action}"); } for action in ["files.read", "files.list", "chat.open", "appearance", "templates.review", "sessions.seen"] { diff --git a/apps/zgx/src/route_motion_tests.rs b/apps/zgx/src/route_motion_tests.rs index 66bc2f353..62348b2d8 100644 --- a/apps/zgx/src/route_motion_tests.rs +++ b/apps/zgx/src/route_motion_tests.rs @@ -1,85 +1,709 @@ -//! The composer between a new chat and a session (ui/screens/chat/composer, -//! mounted headless on ui/shell_fixture.luau): another chat opened or a new -//! chat puts it where it goes at once, no fade and no slide. (The Lua tests can't read an opacity: -//! ui/tests/shell_route_motion.test.luau has the panel's side of it.) +//! Composer focus and layout transitions on the real shell fixture. +//! TestApp supplies the frame/timer clock; readiness is revision-based. -use std::time::Duration; +use zgx::{ + input::{InputEvent, Key}, + scene::{NodeId, Rect}, +}; +use zgx_script::{ScriptHost, Value, testing::TestApp}; -use zgx_script::{ScriptHost, testing::TestApp}; +// Characterization, not a reproduction of the reported visual glitch. +// These snapshots observe the scene, not GPU pixels. See +// docs/composer.md for the separate visual procedure. +const FIELD: &str = "#chat-composer >> role:textbox"; +const BUILD: &str = "#shell-sidebar >> role:button \"Fix the build\""; +const DOCS: &str = "#shell-sidebar >> role:button \"Write the docs\""; +const NEW: &str = "#shell-sidebar >> role:button \"New chat\""; -fn mount() -> TestApp { - // (This checkout's `ui/`, or `ZERON_ZGX_TEST_UI`'s: another copy, to see - // the test fail on code from before a fix.) - let ui = std::env::var_os("ZERON_ZGX_TEST_UI") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui")); - let path = ui.join("shell_fixture.luau"); - let app = TestApp::new(|runtime| ScriptHost::new(runtime, path)); - app.ui.scene.borrow_mut().resize(1200., 800.); - app.frames(30); - app +struct Shell { + app: TestApp, + frame: u32, } -/// A frame and a little of the clock, `n` times: each look at the dock's -/// opacity, the composer's top and its height (the pill's, with what hangs -/// off it). -fn watch(app: &mut TestApp, n: usize) -> Vec<(f32, f32, f32)> { - (0..n) - .map(|_| { - app.frames(1); - std::thread::sleep(Duration::from_millis(12)); - let b = app.bounds("chat-composer"); - (app.opacity("chat-composer-dock"), b.y, b.height) - }) - .collect() +impl Shell { + fn new(reduced: bool) -> Self { + Self::of("shell_fixture.luau", reduced) + } + + fn of(fixture: &str, reduced: bool) -> Self { + let ui = std::env::var_os("ZERON_ZGX_TEST_UI") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui")); + let app = TestApp::new(|runtime| ScriptHost::new(runtime, ui.join(fixture))); + app.ui.scene.borrow_mut().resize(1200., 800.); + let motion = app + .host + .states() + .into_iter() + .find(|(name, _)| name.ends_with("::motion_reduce")) + .expect("the shell's motion preference") + .0; + app.host.set_state(&motion, Value::Bool(reduced)).unwrap(); + let mut shell = Self { app, frame: 0 }; + shell.frames(60); + shell + } + + fn frames(&mut self, n: usize) { + for _ in 0..n { + self.frame += 1; + self.app.frame(); + assert_eq!( + self.app.error(), + None, + "script error at frame {}", + self.frame + ); + } + } + + fn geometry(&mut self) -> Geometry { + let composer = self.app.find("#chat-composer").expect("composer"); + let field = self.app.find(FIELD).expect("draft field"); + let scene = self.app.ui.scene.borrow(); + Geometry { + composer: scene.transformed_bounds(composer), + field: scene.transformed_bounds(field), + } + } } -/// Every look after a switch: shown in full (no fade), at its final height -/// (nothing growing or shrinking), and already where it ends (`to`), give -/// or take a frame of its size being measured (a quarter of the way -/// between the two places; a slide would pass through the rest). -fn at_once(seen: &[(f32, f32, f32)], from: f32, to: f32, what: &str) { - let way = (from - to).abs() / 4.; - let tall = seen.last().unwrap().2; - for (i, (opacity, y, h)) in seen.iter().enumerate() { - assert!((opacity - 1.0).abs() < 0.01, "{what}: faded, frame {}: opacity {opacity}", i + 1); - assert!((h - tall).abs() <= 0.5, "{what}: frame {} {h} tall, growing to {tall}", i + 1); - assert!((y - to).abs() <= way, "{what}: frame {} at {y}, not yet where it goes ({to}, from {from})", i + 1); +#[derive(Clone, Copy, Debug)] +struct Geometry { + composer: Rect, + field: Rect, +} + +#[derive(Debug)] +struct Sample { + frame: u32, + editor: NodeId, + focused: Option, + selection: (usize, usize), + text: String, + presented: Geometry, + target: Geometry, + opacity: f32, + visible: bool, +} + +struct Composer { + shown: Shell, + target: Shell, + editor: NodeId, + trace: Vec, + print_trace: bool, +} + +impl Composer { + fn new(session: bool) -> Self { + let mut shown = Shell::new(false); + let mut target = Shell::new(true); + if session { + shown.app.click(BUILD); + target.app.click(BUILD); + shown.frames(60); + target.frames(60); + } + let field = shown.app.find(FIELD).unwrap(); + let editor = shown.app.ui.editor_within(field).unwrap().node; + Self { + shown, + target, + editor, + trace: Vec::new(), + print_trace: std::env::var_os("ZERON_ZGX_COMPOSER_TRACE").is_some_and(|v| v != "0"), + } + } + + /// Same input in both shells. The reduced-motion shell supplies the + /// destination through real layout rather than duplicating its formulas. + fn act(&mut self, action: impl Fn(&mut TestApp)) { + action(&mut self.shown.app); + action(&mut self.target.app); + self.target.frames(2); + } + + fn watch(&mut self, n: usize) { + for _ in 0..n { + self.shown.frames(1); + let presented = self.shown.geometry(); + let target = self.target.geometry(); + let field = self.shown.app.find(FIELD).unwrap(); + let editor = self.shown.app.ui.editor_within(field).unwrap(); + let scene = self.shown.app.ui.scene.borrow(); + let opacity = std::iter::once(editor.node) + .chain(scene.ancestors(editor.node)) + .map(|id| scene.effects(id).opacity) + .product(); + let sample = Sample { + frame: self.shown.frame, + editor: editor.node, + focused: self.shown.app.ui.input.focused(), + selection: editor.selection(), + text: editor.editor.borrow().text().into_owned(), + presented, + target, + opacity, + visible: scene.visible_bounds(editor.node).is_some(), + }; + drop(scene); + self.trace.push(sample); + let s = self.trace.last().unwrap(); + if self.print_trace { + eprintln!( + "composer-trace {} {s:?}", + std::thread::current().name().unwrap_or("unnamed") + ); + } + assert_eq!(s.editor, self.editor, "editor replaced: {:?}", self.trace); + assert!( + s.visible && s.opacity > 0.99, + "editor hidden: {:?}", + self.trace + ); + for r in [ + s.presented.composer, + s.presented.field, + s.target.composer, + s.target.field, + ] { + assert!( + r.x.is_finite() + && r.y.is_finite() + && r.width.is_finite() + && r.height.is_finite() + && r.width > 0. + && r.height > 0., + "invalid geometry: {:?}", + self.trace + ); + } + } + } + + fn last(&self) -> &Sample { + self.trace.last().expect("observed frames") + } + + fn draft(&self, text: &str, selection: (usize, usize)) { + for s in &self.trace { + assert_eq!( + s.text, text, + "draft changed at frame {}: {:?}", + s.frame, self.trace + ); + assert_eq!( + s.selection, selection, + "selection changed: {:?}", + self.trace + ); + assert_eq!(s.focused, Some(self.editor), "focus lost: {:?}", self.trace); + } + } + + fn at_target(&self) { + let s = self.last(); + for (a, b) in [ + (s.presented.composer, s.target.composer), + (s.presented.field, s.target.field), + ] { + assert!( + (a.x - b.x).abs() < 1. + && (a.y - b.y).abs() < 1. + && (a.width - b.width).abs() < 1. + && (a.height - b.height).abs() < 1., + "did not reach reduced-motion target: {:?}", + self.trace + ); + } + } +} + +fn select(app: &mut TestApp, anchor: usize, focus: usize) { + let field = app.find(FIELD).unwrap(); + app.ui + .editor_within(field) + .unwrap() + .set_selection(anchor, focus); +} + +fn type_at_caret(app: &mut TestApp, text: &str) { + // TestApp::type_text clicks again; dispatch directly so typing really + // preserves the current caret/selection, including during a transition. + app.ui.dispatch(InputEvent::Text(text.into())); + app.settle(); +} + +#[test] +fn composer_rest_size_is_independent_of_animated_draft_size_and_picker_placement() { + let mut c = Composer::new(false); + let sizes = |app: &TestApp| { + app.host + .states() + .into_iter() + .find(|(n, _)| n.ends_with("::chat_composer_sizes")) + .unwrap() + .1 + }; + let rest = sizes(&c.shown.app).field("rest").unwrap().as_f64().unwrap(); + c.act(|app| app.fill(FIELD, "one\ntwo\nthree\nfour\nfive\nsix")); + c.watch(3); + let moving = sizes(&c.shown.app); + assert_eq!(moving.field("rest").unwrap().as_f64(), Some(rest)); + assert!(moving.field("target").unwrap().as_f64().unwrap() > rest); + assert!( + moving.field("presented").unwrap().as_f64().unwrap() + < moving.field("target").unwrap().as_f64().unwrap() + ); + c.watch(40); + c.act(|app| app.fill(FIELD, "")); + c.watch(1); + assert_eq!( + sizes(&c.shown.app).field("rest").unwrap().as_f64(), + Some(rest), + "clearing needs no settle timer" + ); + c.watch(40); + c.act(|app| app.click("#chat-composer >> role:button \"Model\"")); + c.watch(2); + let button = c + .shown + .app + .find("#chat-composer >> role:button \"Model\"") + .unwrap(); + let y = c.shown.app.ui.scene.borrow().transformed_bounds(button).y; + c.act(|app| { + app.host + .set_state( + "chat.composer.text", + Value::from("one\ntwo\nthree\nfour\nfive\nsix"), + ) + .unwrap() + }); + c.watch(40); + let held = c.shown.app.ui.scene.borrow().transformed_bounds(button).y; + assert!( + (held - y).abs() < 1., + "open picker retains its anchor: {y} -> {held}" + ); +} + +#[test] +fn composer_transition_near_the_height_cap_preserves_scroll_editing_and_the_caret() { + for session in [false, true] { + let mut c = Composer::new(session); + c.act(|app| app.click(FIELD)); + let first = (0..10) + .map(|i| format!("line {i}")) + .collect::>() + .join("\n"); + c.act(|app| type_at_caret(app, &first)); + c.watch(3); + let more = (10..80).map(|i| format!("\nline {i}")).collect::(); + c.act(|app| type_at_caret(app, &more)); + c.trace.clear(); + c.watch(40); + let text = format!("{first}{more}"); + c.draft(&text, (text.len(), text.len())); + c.at_target(); + let cap = c.last().presented; + let field = c.shown.app.find(FIELD).unwrap(); + let editor = c.shown.app.ui.editor_within(field).unwrap(); + let caret_before = c + .shown + .app + .ui + .scene + .borrow() + .transformed_bounds(editor.caret); + c.act(|app| app.scroll(FIELD, -120.)); + c.watch(3); + let caret_scrolled = c + .shown + .app + .ui + .scene + .borrow() + .transformed_bounds(editor.caret); + assert!( + (caret_before.y - caret_scrolled.y).abs() > 20., + "the test must actually scroll the editor" + ); + c.act(|app| type_at_caret(app, " typed after scrolling")); + c.trace.clear(); + c.watch(20); + let text = format!("{text} typed after scrolling"); + c.draft(&text, (text.len(), text.len())); + for s in &c.trace { + assert_eq!( + s.presented.composer.height, cap.composer.height, + "typing above the cap must not resize the composer" + ); + assert_eq!(s.presented.field, cap.field); + } + let caret = c + .shown + .app + .ui + .scene + .borrow() + .transformed_bounds(editor.caret); + assert!( + caret.y >= cap.field.y - 1. + && caret.y + caret.height <= cap.field.y + cap.field.height + 1., + "typing must reveal the caret inside the viewport: {caret:?}, {cap:?}" + ); + } +} + +#[test] +fn composer_click_and_focus_preserve_geometry_and_the_selected_draft() { + for session in [false, true] { + let mut c = Composer::new(session); + c.watch(1); + let empty = c.last().presented; + c.act(|app| app.click(FIELD)); + c.trace.clear(); + c.watch(6); + c.draft("", (0, 0)); + for s in &c.trace { + assert_eq!( + s.presented.composer, empty.composer, + "empty click resized composer: {s:?}" + ); + assert_eq!( + s.presented.field, empty.field, + "empty click moved field: {s:?}" + ); + } + c.trace.clear(); + c.act(|app| app.fill(FIELD, "hello composer")); + c.watch(40); + c.at_target(); + let before = c.last().presented; + c.trace.clear(); + c.act(|app| { + app.ui.input.focus(&app.ui.scene, None); + }); + c.watch(2); + assert_eq!(c.last().focused, None); + c.act(|app| app.click(FIELD)); + c.trace.clear(); + c.watch(2); + let clicked = c.last().selection; + c.draft("hello composer", clicked); + for s in &c.trace { + assert_eq!(s.presented.field, before.field, "click moved field: {s:?}"); + } + c.act(|app| select(app, 1, 8)); + c.trace.clear(); + c.watch(40); + c.draft("hello composer", (1, 8)); + for s in &c.trace { + assert_eq!( + s.presented.composer, before.composer, + "focus resized composer: {s:?}" + ); + assert_eq!(s.presented.field, before.field, "focus moved field: {s:?}"); + } + c.at_target(); + } +} + +#[test] +fn composer_character_typing_crosses_the_wrap_boundary_and_folds_back() { + let mut c = Composer::new(true); + c.act(|app| app.click(FIELD)); + c.watch(1); + let compact = c.last().target.composer.height; + let compact_width = c.last().presented.field.width; + let mut text = String::new(); + // Find the boundary with the actual font, without copying width rules. + while c.last().target.composer.height <= compact + 1. { + assert!(text.len() < 256, "never expanded: {:?}", c.trace); + text.push('W'); + c.act(|app| type_at_caret(app, "W")); + c.trace.clear(); + c.watch(1); + c.draft(&text, (text.len(), text.len())); + } + c.watch(30); + c.at_target(); + let expanded_width = c.last().target.field.width; + let mut width = compact_width; + let mut changes = 0; + for s in &c.trace { + let next = s.presented.field.width; + assert!( + (next - compact_width).abs() < 1. || (next - expanded_width).abs() < 1., + "mode change must not rewrap through intermediate widths: {s:?}" + ); + if (next - width).abs() >= 1. { + changes += 1; + } + width = next; + } + assert_eq!( + changes, 1, + "the real editor changes width once at expansion" + ); + assert!(c.last().presented.composer.height > compact + 20.); + while !text.is_empty() { + c.act(|app| app.key(Key::Backspace)); + text.pop(); + c.trace.clear(); + c.watch(1); + c.draft(&text, (text.len(), text.len())); + } + c.watch(40); + c.at_target(); + assert!((c.last().presented.composer.height - compact).abs() < 1.); +} + +#[test] +fn composer_growth_shrink_and_typing_during_a_transition_keep_the_editor() { + for session in [false, true] { + let mut c = Composer::new(session); + c.act(|app| app.click(FIELD)); + c.watch(1); + let short = c.last().presented.composer.height; + let first = "one\ntwo\nthree\nfour\nfive\nsix"; + c.act(|app| type_at_caret(app, first)); + c.trace.clear(); + c.watch(3); + c.draft(first, (first.len(), first.len())); + let mid = c.last(); + assert!( + mid.presented.composer.height > short + 1. + && mid.presented.composer.height < mid.target.composer.height - 1., + "must interrupt an actual growth transition: {:?}", + c.trace + ); + c.act(|app| type_at_caret(app, "\nseven")); + c.trace.clear(); + c.watch(40); + let text = format!("{first}\nseven"); + c.draft(&text, (text.len(), text.len())); + c.at_target(); + let tall = c.last().presented.composer.height; + c.act(|app| { + select(app, 0, text.len()); + type_at_caret(app, "short"); + }); + c.trace.clear(); + c.watch(3); + assert!( + c.last().presented.composer.height < tall - 1. + && c.last().presented.composer.height > c.last().target.composer.height + 1., + "shrink should ease: {:?}", + c.trace + ); + c.watch(40); + c.draft("short", (5, 5)); + c.at_target(); } } #[test] fn a_new_chat_and_a_session_switch_the_composer_at_once() { - let mut app = mount(); - app.click("#shell-sidebar >> role:button \"Fix the build\""); - watch(&mut app, 60); - let docked = app.bounds("chat-composer").y; - assert!((app.opacity("chat-composer-dock") - 1.0).abs() < 0.01, "the composer shows, docked"); + let mut c = Composer::new(true); + c.watch(1); + let docked = c.last().presented.composer.y; + for selector in [NEW, BUILD] { + c.act(|app| app.click(selector)); + c.trace.clear(); + c.watch(30); + for s in &c.trace { + assert!( + (s.presented.composer.y - s.target.composer.y).abs() < 1. + && (s.presented.composer.height - s.target.composer.height).abs() < 1., + "route switch did not snap: {:?}", + c.trace + ); + } + c.at_target(); + if selector == NEW { + assert!(c.last().presented.composer.y < docked - 50.); + } else { + assert!((c.last().presented.composer.y - docked).abs() < 1.); + } + } + c.act(|app| app.fill(FIELD, "build draft")); + c.watch(40); + c.act(|app| app.click(DOCS)); + c.trace.clear(); + c.watch(30); + assert_eq!(c.last().text, ""); + c.act(|app| app.fill(FIELD, "docs draft")); + c.watch(40); + c.act(|app| app.click(BUILD)); + c.trace.clear(); + c.watch(30); + assert_eq!(c.last().text, "build draft"); + c.act(|app| { + app.click(FIELD); + select(app, 0, 5); + }); + c.trace.clear(); + c.watch(30); + c.draft("build draft", (0, 5)); + c.at_target(); +} - // To a new chat: mid-page from the first frame, never faded. - app.click("#shell-sidebar >> role:button \"New chat\""); - let seen = watch(&mut app, 60); - let hero = app.bounds("chat-composer").y; - assert!(hero < docked - 50., "it stands mid-page on a new chat ({hero} vs {docked})"); - at_once(&seen, docked, hero, "to a new chat"); - - // And back to the session: docked from the first frame. - app.click("#shell-sidebar >> role:button \"Fix the build\""); - let seen = watch(&mut app, 60); - assert!((app.bounds("chat-composer").y - docked).abs() <= 1., "docked again"); - at_once(&seen, hero, docked, "back to the session"); - - // Growing in the same chat (lines typed) still eases: seen on its way. - std::thread::sleep(Duration::from_millis(500)); - let short = app.bounds("chat-composer").height; - app.fill("#chat-composer >> role:textbox", "one\ntwo\nthree\nfour"); - let seen = watch(&mut app, 40); - let tall = seen.last().unwrap().2; - assert!(tall > short + 20., "the lines opened it out ({short} → {tall})"); +/// A send from a new chat: the composer slides down to the dock with its +/// prompt and eases into its docked form on the way (no snap: its size +/// passes through between), as the page's one slide; with motion reduced +/// it's there at once. Any other move to or from a new chat snaps (above). +#[test] +fn a_send_from_a_new_chat_slides_the_composer_down_and_eases_it_docked() { + let snaps = |shell: &Shell| { + shell + .app + .host + .states() + .into_iter() + .find(|(n, _)| n.ends_with("::chat_composer_snap")) + .and_then(|(_, v)| v.as_f64()) + .expect("the composer's snaps") + }; + let mut shells = [false, true].map(|reduced| { + let mut shell = Shell::of("chat_fixture.luau", reduced); + assert!(shell.app.host.run_command("go_new")); + shell.frames(30); + shell.app.fill(FIELD, "please fix the build"); + shell.frames(40); + shell + }); + let start = shells[0].geometry().composer; + let snapped = snaps(&shells[0]); + for shell in &mut shells { + shell.app.key(Key::Enter); + } + shells[1].frames(2); + let end = shells[1].geometry().composer; assert!( - seen.iter().any(|(_, _, h)| *h > short + 1. && *h < tall - 1.), - "it grew at once, not eased ({short} → {tall}): {:?}", - seen.iter().map(|s| s.2).collect::>() + end.y > start.y + 100. && end.height < start.height - 20., + "the session docks it lower, one line: {start:?} -> {end:?}" + ); + let mut trace = Vec::new(); + for _ in 0..30 { + shells[0].frames(1); + trace.push(shells[0].geometry().composer); + } + let between = trace + .iter() + .filter(|r| { + r.y > start.y + 1. + && r.y < end.y - 1. + && r.height < start.height - 1. + && r.height > end.height + 1. + }) + .count(); + assert!( + between >= 5, + "its place and its size ease together, neither snapped: {start:?} -> {end:?}, {trace:?}" + ); + for pair in trace.windows(2) { + assert!( + pair[1].y >= pair[0].y - 0.01 && pair[1].height <= pair[0].height + 0.01, + "one way, down and smaller: {trace:?}" + ); + } + let last = trace.last().unwrap(); + assert!( + (last.y - end.y).abs() < 1. && (last.height - end.height).abs() < 1., + "lands where the reduced-motion shell put it: {end:?}, {trace:?}" + ); + assert_eq!(snaps(&shells[0]), snapped, "a send snaps nothing"); +} + +#[test] +fn composer_resize_theme_transparency_and_zoom_reflow_preserve_the_draft() { + for session in [false, true] { + let mut c = Composer::new(session); + let text = "**bold** café 你好 @mention and words to wrap\n".repeat(8); + c.act(|app| { + app.fill(FIELD, &text); + select(app, 2, 6); + }); + c.watch(40); + for (width, height, zoom, theme, frosted) in [ + (1200., 800., 1., "zeron-dark", true), + (950., 800., 1.25, "zeron-light", false), + (1400., 900., 0.9, "zeron-dark", true), + ] { + c.trace.clear(); + c.act(|app| { + app.ui.theme().set(theme).unwrap(); + app.ui.set_zoom(zoom); + // The native host reflows at window points / zoom. Model + // that logical layout here; this does not validate GPU scale. + app.ui + .scene + .borrow_mut() + .resize(width / zoom as f32, height / zoom as f32); + app.ui.refresh_text_geometry(); + let key = app + .host + .states() + .into_iter() + .find(|(key, _)| key.ends_with("::frosted")) + .unwrap() + .0; + app.host.set_state(&key, Value::Bool(frosted)).unwrap(); + }); + c.target.frames(30); + c.watch(40); + c.draft(&text, (2, 6)); + c.at_target(); + } + } +} + +/// Typing in a long draft costs what typing in a short one past the cap +/// does: the composer's natural size can't change there (open, capped), so +/// the draft isn't measured again. Measuring walked every line twice at each +/// keystroke, past what the editor's span cache holds (a 5,000-line draft: +/// 10,039 script calls and 47 ms a key; 30,000 lines: 294 ms). +#[test] +fn typing_in_a_long_draft_costs_what_a_short_one_does() { + let per_key = |lines: usize| { + let mut shell = Shell::new(false); + shell.app.click(BUILD); + shell.frames(60); + let text: String = (0..lines) + .map(|i| format!("line {i} with some words that go on for a while here\n")) + .collect(); + shell.app.fill(FIELD, &text); + shell.frames(60); + let capped = shell.geometry().composer.height; + let before = shell.app.calls(); + for _ in 0..20 { + shell.app.ui.dispatch(InputEvent::Text("x".into())); + shell.app.settle(); + shell.frames(3); + } + let calls = (shell.app.calls() - before) / 20; + let field = shell.app.find(FIELD).unwrap(); + let editor = shell.app.ui.editor_within(field).unwrap(); + assert!( + editor + .editor + .borrow() + .text() + .ends_with("xxxxxxxxxxxxxxxxxxxx") + ); + assert!( + (shell.geometry().composer.height - capped).abs() < 0.5, + "typing past the cap must not resize the composer" + ); + calls + }; + let (short, long) = (per_key(20), per_key(5000)); + assert!( + long <= short && long <= 20, + "{long} script calls a key in 5,000 lines, {short} in 20" ); } @@ -95,12 +719,15 @@ fn a_new_chat_and_a_session_switch_the_composer_at_once() { #[test] fn the_panel_s_content_and_the_page_only_fade_as_they_come_and_go() { const FLOOR: f32 = 0.3; - let mut app = mount(); + let mut app = Shell::new(false).app; app.click("#shell-sidebar >> role:button \"Fix the build\""); - watch(&mut app, 20); + app.frames(20); let warnings = |app: &mut TestApp| -> Vec { app.ui.prepare_frame(); - zgx::inspect::layout_warnings(&app.ui).iter().map(|w| w.to_string()).collect() + zgx::inspect::layout_warnings(&app.ui) + .iter() + .map(|w| w.to_string()) + .collect() }; // (Where its right edge is painted: it stands at its column's side by // the window's edge, the panel's content at the window's right, the @@ -109,7 +736,11 @@ fn the_panel_s_content_and_the_page_only_fade_as_they_come_and_go() { let node = app.find(&format!("#{id}")).expect("it"); app.ui.prepare_frame(); let b = app.ui.scene.borrow().transformed_bounds(node); - if id == "shell-page-room" { b.x } else { b.x + b.width } + if id == "shell-page-room" { + b.x + } else { + b.x + b.width + } }; // (What the fixture has before the panel ever opens.) let before = warnings(&mut app); @@ -118,31 +749,68 @@ fn the_panel_s_content_and_the_page_only_fade_as_they_come_and_go() { let seen: Vec<(f32, f32, bool)> = (0..30) .map(|_| { app.frames(1); - std::thread::sleep(Duration::from_millis(12)); // (Whether its column shows: the panel under 2 points shows none.) let shows = id == "shell-page-room" || app.opacity("shell-files") > 0.; (app.opacity(id), edge(&mut app, id), shows) }) .collect(); - let (lo, hi) = seen.iter().filter(|s| s.2).fold((f32::MAX, f32::MIN), |(lo, hi), s| (lo.min(s.1), hi.max(s.1))); + let (lo, hi) = seen + .iter() + .filter(|s| s.2) + .fold((f32::MAX, f32::MIN), |(lo, hi), s| { + (lo.min(s.1), hi.max(s.1)) + }); let drift = hi - lo; - assert!(drift <= 0.011, "{what}: {id} moved {drift} points: {seen:?}"); + assert!( + drift <= 0.011, + "{what}: {id} moved {drift} points: {seen:?}" + ); let between = seen.iter().filter(|s| s.0 > 0.02 && s.0 < 0.98).count(); - let jump = seen.windows(2).map(|w| (w[1].0 - w[0].0).abs()).fold(0., f32::max); + let jump = seen + .windows(2) + .map(|w| (w[1].0 - w[0].0).abs()) + .fold(0., f32::max); assert!(between >= 2 && jump <= 0.7, "{what}: {id} at {seen:?}"); - let showing = seen.iter().filter(|s| (s.0 - to).abs() > 0.01).map(|s| s.0).fold(1., f32::min); - assert!(showing >= FLOOR - 0.01, "{what}: {id} fades only to the floor as it shows: {seen:?}"); - assert!((seen.last().unwrap().0 - to).abs() < 0.01, "{what}: {id} ends at {seen:?}"); + let showing = seen + .iter() + .filter(|s| (s.0 - to).abs() > 0.01) + .map(|s| s.0) + .fold(1., f32::min); + assert!( + showing >= FLOOR - 0.01, + "{what}: {id} fades only to the floor as it shows: {seen:?}" + ); + assert!( + (seen.last().unwrap().0 - to).abs() < 0.01, + "{what}: {id} ends at {seen:?}" + ); // At rest, nothing it holds is laid out in a box that shows none of // it (`zgx inspect errors` names nothing new). app.frames(30); - assert_eq!(warnings(&mut app), before, "{what}: settled, the layout's warnings"); + assert_eq!( + warnings(&mut app), + before, + "{what}: settled, the layout's warnings" + ); }; - fade("#titlebar >> role:button \"Panel\"", "shell-files-content", 1., "opening"); + fade( + "#titlebar >> role:button \"Panel\"", + "shell-files-content", + 1., + "opening", + ); fade("#panel-expand", "shell-page-room", 0., "expanding"); fade("#panel-expand", "shell-page-room", 1., "collapsing"); - fade("#titlebar >> role:button \"Panel\"", "shell-files-content", FLOOR, "closing"); - assert!(app.opacity("shell-files") < 0.01, "closed, the panel shows none of it"); + fade( + "#titlebar >> role:button \"Panel\"", + "shell-files-content", + FLOOR, + "closing", + ); + assert!( + app.opacity("shell-files") < 0.01, + "closed, the panel shows none of it" + ); } /// The sidebar folds and comes back as the panel opens and closes: its @@ -155,9 +823,9 @@ fn the_panel_s_content_and_the_page_only_fade_as_they_come_and_go() { #[test] fn the_sidebar_s_content_stands_still_and_only_fades_as_it_folds() { const FLOOR: f32 = 0.3; - let mut app = mount(); + let mut app = Shell::new(false).app; app.click("#shell-sidebar >> role:button \"Fix the build\""); - watch(&mut app, 20); + app.frames(20); let at = |app: &mut TestApp, sel: &str| -> Option<(f32, f32)> { let node = app.find(sel)?; app.ui.prepare_frame(); @@ -169,22 +837,41 @@ fn the_sidebar_s_content_stands_still_and_only_fades_as_it_folds() { let mut rows = Vec::new(); for _ in 0..24 { app.frames(1); - std::thread::sleep(Duration::from_millis(12)); let side = at(&mut app, "#shell-sidebar").expect("its column"); let page = at(&mut app, "#shell-page-room").expect("the page"); let row = at(&mut app, "#shell-sidebar >> role:button \"Fix the build\""); - let fade = if app.find("#sidebar-content").is_some() { app.opacity("sidebar-content") } else { 1. }; + let fade = if app.find("#sidebar-content").is_some() { + app.opacity("sidebar-content") + } else { + 1. + }; // (Its card more than the window's gap wide: the gap is whole.) if side.1 > 10. { rows.push(row.expect("its row").0); - assert!((page.0 - (side.0 + side.1) - 4.).abs() < 0.05, "{what}: the gap beside it, {}", page.0 - side.0 - side.1); - assert!(fade >= FLOOR - 0.01, "{what}: it fades only to the floor as it shows: {fade}"); + assert!( + (page.0 - (side.0 + side.1) - 4.).abs() < 0.05, + "{what}: the gap beside it, {}", + page.0 - side.0 - side.1 + ); + assert!( + fade >= FLOOR - 0.01, + "{what}: it fades only to the floor as it shows: {fade}" + ); } } - let (lo, hi) = rows.iter().fold((f32::MAX, f32::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x))); - assert!(rows.len() >= 4 && hi - lo <= 0.011, "{what}: its row stands at {lo}..{hi} over {} frames", rows.len()); + let (lo, hi) = rows + .iter() + .fold((f32::MAX, f32::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + assert!( + rows.len() >= 4 && hi - lo <= 0.011, + "{what}: its row stands at {lo}..{hi} over {} frames", + rows.len() + ); let end = if what == "folding" { FLOOR } else { 1. }; - assert!((app.opacity("sidebar-content") - end).abs() < 0.01, "{what}: it ends faded to {end}"); + assert!( + (app.opacity("sidebar-content") - end).abs() < 0.01, + "{what}: it ends faded to {end}" + ); app.frames(30); } } diff --git a/apps/zgx/src/sessions.rs b/apps/zgx/src/sessions.rs index 7e5810e89..f446abc04 100644 --- a/apps/zgx/src/sessions.rs +++ b/apps/zgx/src/sessions.rs @@ -191,6 +191,21 @@ struct RowWith { working_side_chats: u32, known_project: bool, agent_icon: Option, + /// The last turn its agent finished, as its session row marks it + /// (`lastCompletedTurn`): what a "finished" chime rings on moving. + turn: Option, +} + +/// A session row's finished turn, and whether the row is fresh: written in +/// the last `SESSION_STALE_MS`, so a turn's end just published rather than +/// an old row a sync or reconnect brings back (the shipping app's chime +/// rule, crates/engine/src/desktop_notify.rs `SessionNotificationState`). +fn finished_turn(session: Option<&Session>, at: chrono::DateTime) -> (Option, bool) { + let Some(s) = session else { + return (None, false); + }; + let fresh = at.signed_duration_since(s.updated_at).num_milliseconds() <= zeron_proto::view::SESSION_STALE_MS; + (s.last_completed_turn.clone(), fresh) } /// `slot` holds `item` now; whether that's new. @@ -621,6 +636,7 @@ fn child_row(rows: &mut HashMap, c: &Json, id: &str, parent: &str, working_side_chats: 0, known_project: false, agent_icon: harness.and_then(crate::agents::registry_icon), + turn: None, }; if rows.get(id).is_some_and(|row| row.with == with) { return; @@ -681,6 +697,7 @@ fn top_row( working_side_chats, known_project: project.is_some(), agent_icon: harness.and_then(crate::agents::registry_icon), + turn: finished_turn(session, at).0, }; if let Some(row) = rows.get(id).filter(|row| row.with == with) { return row.value.clone(); @@ -721,6 +738,12 @@ fn top_row( // it woke (Unix seconds). ("sleep_until", with.sleep.filter(|s| s.0).map_or(Value::Nil, |s| Value::from(s.1 as f64))), ("woke", with.sleep.filter(|s| !s.0).map_or(Value::Nil, |s| Value::from(s.1 as f64))), + // The last turn its agent finished (an opaque mark), and whether its + // session row was fresh when that was read: the chimes ring + // "finished" on this moving, never on the status alone ("done" is + // only unseen activity, which your own send makes too). + ("turn", with.turn.as_deref().map_or(Value::Nil, Value::from)), + ("turn_fresh", Value::from(finished_turn(session, at).1)), ]); rows.insert(id.to_owned(), Row { moved: moved(c), updated: updated as f64, marks, with, value: value.clone() }); value @@ -2516,6 +2539,33 @@ mod tests { assert!(!s.rows.borrow().contains_key("b")); } + /// A chat's finished turn (what the "done" chime rings on, issue #1437): + /// its session's `lastCompletedTurn`, published as it moves, and whether + /// the row saying so is fresh. + #[test] + fn a_chat_s_finished_turn_is_published_as_it_moves() { + let now = now_seconds(); + let s = with_children("2099-01-01T00:00:00Z"); + s.heard.set(true); + let row = |turn: &str, ago: i64| { + json!([{ "chatId": "p", "deviceId": "d", "status": "idle", "updatedAt": iso(now - ago), "lastCompletedTurn": turn }]) + }; + s.set_live(row("t1", 1)); + s.publish(); + let p = s.value(); + assert_eq!(chat(&p, "p").field("turn").map(crate::auth::text).as_deref(), Some("t1")); + assert!(chat(&p, "p").field("turn_fresh").is_some_and(zgx_script::Value::truthy)); + let before = s.published.get(); + s.heard(Slot::Live, row("t2", 0)); + assert_eq!(s.published.get(), before + 1, "a finish is shown at once"); + assert_eq!(chat(&s.value(), "p").field("turn").map(crate::auth::text).as_deref(), Some("t2")); + // An end published long ago (a sync, a reconnect): not fresh. + s.heard(Slot::Live, row("t3", 600)); + let p = s.value(); + assert_eq!(chat(&p, "p").field("turn").map(crate::auth::text).as_deref(), Some("t3")); + assert!(!chat(&p, "p").field("turn_fresh").is_some_and(zgx_script::Value::truthy)); + } + #[test] fn an_update_that_changes_nothing_publishes_nothing() { let s = with_children("2099-01-01T00:00:00Z"); diff --git a/apps/zgx/src/split_tests.rs b/apps/zgx/src/split_tests.rs index ee2287518..7c878059c 100644 --- a/apps/zgx/src/split_tests.rs +++ b/apps/zgx/src/split_tests.rs @@ -25,7 +25,10 @@ const W: f32 = 1400.; const H: f32 = 860.; fn ui() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui") + // Compare an archived interface with the same host and frame clock. + std::env::var_os("ZERON_ZGX_TEST_UI") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui")) } fn scratch(name: &str) -> PathBuf { @@ -1636,7 +1639,9 @@ fn drag_script_of(fixture: &Path, panes_n: usize) -> u64 { app.frames(60); let calls = app.calls(); drag_sidebar(&mut app, 120., |_| ()); - (app.calls() - calls) / 20 + let per_frame = (app.calls() - calls) / 20; + eprintln!("RESIZE-CALLS {panes_n} panes: {per_frame}"); + per_frame } /// The sidebar's edge dragged, the sidebar's list isn't built again, and diff --git a/apps/zgx/src/terminal.rs b/apps/zgx/src/terminal.rs index 1b0ee3f6e..1027bc641 100644 --- a/apps/zgx/src/terminal.rs +++ b/apps/zgx/src/terminal.rs @@ -161,13 +161,15 @@ async fn start(arg: Value) -> Result { let dir = claims_dir(); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let claim = dir.join(format!("{}-{}", std::process::id(), operation_nonce())); - let line = format!( + // (In base64: no quote inside it for a shell to read as its own, `runnable`.) + let open = base64::engine::general_purpose::STANDARD.encode(Json::Object(params).to_string()); + let line = runnable(format!( "{} terminal-bridge --port {port} --data {} --open {} --claim {}", quote(&exe.to_string_lossy()), quote(&data.to_string_lossy()), - quote(&Json::Object(params).to_string()), + quote(&open), quote(&claim.to_string_lossy()), - ); + )); note_issued(&line); Ok(Value::record([("command", Value::from(line.as_str())), ("claim", Value::from(claim.to_string_lossy().as_ref()))])) } @@ -295,10 +297,42 @@ fn command(arg: Value, device: Option) -> Result { if let Some(device) = device { line.push_str(&format!(" --device {}", quote(&device))); } + let line = runnable(line); note_issued(&line); Ok(Value::from(line.as_str())) } +/// The line zgx's terminal runs for the bridge's `line`. The Windows beta is +/// a GUI program (main.rs `windows_subsystem`), and Windows attaches none to +/// the pseudoconsole it's started on: the bridge would have no console, its +/// shell opened and nothing shown. So cmd.exe, a console program, is started +/// on it, waits for the bridge, and the bridge attaches to its console +/// (`attach_console`). Each word is in quotes with none inside (the open +/// parameters are base64), so cmd takes nothing in them for its own syntax. +#[cfg(all(windows, feature = "beta"))] +fn runnable(line: String) -> String { + let cmd = std::env::var("ComSpec").unwrap_or_else(|_| r"C:\Windows\System32\cmd.exe".into()); + format!("{} /d /s /c \"{line}\"", quote(&cmd)) +} +#[cfg(not(all(windows, feature = "beta")))] +fn runnable(line: String) -> String { + line +} + +/// The console of the cmd.exe that started this bridge (`runnable`), when +/// it has none of its own (a GUI program's). +#[cfg(all(windows, feature = "beta"))] +fn attach_console() { + use windows_sys::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole, GetConsoleMode, GetStdHandle, STD_INPUT_HANDLE}; + // SAFETY: the process's own standard handle, and a mode for it to fill. + unsafe { + let mut mode = 0; + if GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &mut mode) == 0 { + AttachConsole(ATTACH_PARENT_PROCESS); + } + } +} + // --------------------------------------------------------------------------- // The bridge: its own process, run by zgx's terminal. @@ -327,10 +361,14 @@ fn parse(args: &[String]) -> Result { "--port" => port = value.parse().ok(), "--data" => data = Some(PathBuf::from(value)), "--terminal" => terminal = Some(value.clone()), - "--open" => match serde_json::from_str::(value) { - Ok(Json::Object(params)) => open = Some(params), - _ => return Err("--open takes OpenTerminal's parameters".into()), - }, + // (As JSON, or JSON in base64: `start`'s.) + "--open" => { + let decoded = base64::engine::general_purpose::STANDARD.decode(value).ok().and_then(|bytes| String::from_utf8(bytes).ok()); + match serde_json::from_str::(decoded.as_deref().unwrap_or(value)) { + Ok(Json::Object(params)) => open = Some(params), + _ => return Err("--open takes OpenTerminal's parameters".into()), + } + } "--claim" => claim = Some(PathBuf::from(value)), "--device" => device = Some(value.clone()), other => return Err(format!("unknown flag {other}")), @@ -377,7 +415,30 @@ fn window_size() -> Option<(u16, u16)> { (libc::ioctl(0, libc::TIOCGWINSZ, &mut size) == 0 && size.ws_col > 0).then_some((size.ws_col, size.ws_row)) } } -#[cfg(not(unix))] +/// The visible window of the console this bridge writes to: the +/// pseudoconsole zgx's terminal sized (cmd.exe's, `attach_console`), which +/// follows the tab as zgx resizes it. Windows says nothing as it changes: +/// the bridge looks on each of its turns (`bridge`), as cheap as a call. +#[cfg(windows)] +fn window_size() -> Option<(u16, u16)> { + use windows_sys::Win32::System::Console::{CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo, GetStdHandle, STD_OUTPUT_HANDLE}; + // SAFETY: the process's own standard handle, and a struct for it to fill. + let info = unsafe { + let mut info: CONSOLE_SCREEN_BUFFER_INFO = std::mem::zeroed(); + (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) != 0).then_some(info) + }?; + console_window_size(info.srWindow.Left, info.srWindow.Top, info.srWindow.Right, info.srWindow.Bottom) +} + +/// Columns and rows of a console window's inclusive rectangle, if it has any. +#[cfg(any(windows, test))] +fn console_window_size(left: i16, top: i16, right: i16, bottom: i16) -> Option<(u16, u16)> { + let cols = i32::from(right) - i32::from(left) + 1; + let rows = i32::from(bottom) - i32::from(top) + 1; + (cols > 0 && rows > 0).then(|| (cols.min(i32::from(u16::MAX)) as u16, rows.min(i32::from(u16::MAX)) as u16)) +} + +#[cfg(not(any(unix, windows)))] fn window_size() -> Option<(u16, u16)> { None } @@ -482,6 +543,78 @@ impl Drop for Raw { } } +/// The console's modes and code pages as found, put back as the bridge ends. +#[cfg(windows)] +struct Raw(Option); +#[cfg(windows)] +struct RawWas { + input: u32, + output: u32, + input_cp: u32, + output_cp: u32, +} +#[cfg(windows)] +impl Raw { + /// Its console in raw mode, as `cfmakeraw` puts a Unix one: a cooked + /// console echoed each line before the shell at the other end did (every + /// line shown twice), ended it with a carriage return and a line feed + /// (PowerShell read the second as a continued line, `>>`), and took + /// Ctrl+C as a signal to every process on it, cmd.exe and the bridge + /// included, leaving the tab with nothing behind it. Raw, what's typed goes + /// on as it is (Ctrl+C as its byte, which the shell's own console turns + /// into its interrupt), in the terminal's sequences; what the shell wrote + /// comes out as it is, in UTF-8. + fn new() -> Self { + use windows_sys::Win32::System::Console::{ + DISABLE_NEWLINE_AUTO_RETURN, ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleCP, GetConsoleMode, GetConsoleOutputCP, GetStdHandle, + STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, SetConsoleCP, SetConsoleMode, SetConsoleOutputCP, + }; + // SAFETY: the process's own standard handles, modes read from them + // and changed; nothing if either isn't a console. + unsafe { + let (stdin, stdout) = (GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE)); + let (mut input, mut output) = (0, 0); + if GetConsoleMode(stdin, &mut input) == 0 || GetConsoleMode(stdout, &mut output) == 0 { + return Raw(None); + } + let was = RawWas { input, output, input_cp: GetConsoleCP(), output_cp: GetConsoleOutputCP() }; + SetConsoleMode(stdin, raw_input_mode(input)); + SetConsoleMode(stdout, output | ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN); + const UTF8: u32 = 65001; + SetConsoleCP(UTF8); + SetConsoleOutputCP(UTF8); + Raw(Some(was)) + } + } +} +#[cfg(windows)] +impl Drop for Raw { + fn drop(&mut self) { + use windows_sys::Win32::System::Console::{GetStdHandle, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, SetConsoleCP, SetConsoleMode, SetConsoleOutputCP}; + if let Some(was) = &self.0 { + // SAFETY: restores what `new` read from the same handles. + unsafe { + SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), was.input); + SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), was.output); + SetConsoleCP(was.input_cp); + SetConsoleOutputCP(was.output_cp); + } + } + } +} + +/// A console input mode made raw: no echo, no lines, no Ctrl+C signal; +/// keys as the terminal's sequences. (Its other flags are left as found.) +#[cfg(any(windows, test))] +fn raw_input_mode(mode: u32) -> u32 { + // (windows-sys's values, here so the rule is tested everywhere.) + const ENABLE_PROCESSED_INPUT: u32 = 0x0001; + const ENABLE_LINE_INPUT: u32 = 0x0002; + const ENABLE_ECHO_INPUT: u32 = 0x0004; + const ENABLE_VIRTUAL_TERMINAL_INPUT: u32 = 0x0200; + (mode & !(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)) | ENABLE_VIRTUAL_TERMINAL_INPUT +} + /// Sends a call. On a socket that doesn't block, what doesn't go at once /// waits in tungstenite's buffer (`rpc::would_block`) for the socket to /// have room. @@ -532,6 +665,8 @@ fn resizes() -> Option { /// Runs the bridge; returns the process's exit code. pub fn bridge(args: &[String]) -> i32 { + #[cfg(all(windows, feature = "beta"))] + attach_console(); let args = match parse(args) { Ok(args) => args, Err(why) => { @@ -550,7 +685,7 @@ pub fn bridge(args: &[String]) -> i32 { }; // (A device given is another's: the app only passes it then.) let mut device = args.device.clone(); - #[cfg(unix)] + #[cfg(any(unix, windows))] let _raw = Raw::new(); let mut size = None; // A new one: opened here, at the size zgx gave this pseudoterminal, so @@ -626,7 +761,7 @@ pub fn bridge(args: &[String]) -> i32 { let mut look_at_size = true; loop { // Its size, told as it changes (zgx resizes its pseudoterminal, and - // says so with SIGWINCH). + // says so with SIGWINCH; on Windows, looked at each turn). let now = if look_at_size { window_size() } else { size }; look_at_size = cfg!(not(unix)); if now.is_some() && now != size { @@ -774,6 +909,26 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A Windows console made raw: no echo, no lines, no Ctrl+C signal, keys + /// as sequences, and whatever else it had kept. + #[test] + fn a_raw_console_neither_echoes_nor_cooks_nor_signals() { + // A cooked console's defaults: processed, line, echo, insert, quick + // edit, extended flags. + let cooked = 0x0001 | 0x0002 | 0x0004 | 0x0020 | 0x0040 | 0x0080; + assert_eq!(super::raw_input_mode(cooked), 0x0020 | 0x0040 | 0x0080 | 0x0200); + assert_eq!(super::raw_input_mode(0x0200), 0x0200); + } + + /// A console's size is its visible window's: inclusive edges. + #[test] + fn a_consoles_size_is_its_windows() { + assert_eq!(super::console_window_size(0, 0, 79, 23), Some((80, 24))); + // Scrolled down its buffer: still the window's size. + assert_eq!(super::console_window_size(0, 900, 39, 947), Some((40, 48))); + assert_eq!(super::console_window_size(5, 5, 4, 10), None); + } + #[test] fn an_older_engine_says_to_update() { assert_eq!(said("unknown method: TerminalStatus".into()), "Update Zeron to use terminals here."); diff --git a/apps/zgx/src/tool_details.rs b/apps/zgx/src/tool_details.rs index 7d15c92dd..c18978ab9 100644 --- a/apps/zgx/src/tool_details.rs +++ b/apps/zgx/src/tool_details.rs @@ -278,13 +278,165 @@ pub fn tool_fields(part: &Json) -> Vec<(&'static str, Value)> { { fields.push(("diff", diff)); } + if let Some(pictures) = pictures_value(part) { + fields.push(("pictures", pictures)); + } fields } +/// Pictures a tool row opens to, at most (the shipping chip's +/// `MAX_IMAGES_PER_TOOL`). +const MAX_PICTURES: usize = 4; + +/// The pictures a tool's result carried (`previewPaths`: the engine's copies +/// in the profile's uploads, on the chat's host), each `{ path, name }`: its +/// name the file the call named (a Read's) when it carried one, else the +/// copy's own. Nil when it carried none: a path a tool only named is never +/// read from here, and neither is any path that isn't such a copy +/// (`stored_tool_picture`). +fn pictures_value(part: &Json) -> Option { + let data_dir = engine::data_dir(); + pictures_in(part, data_dir.as_deref()) +} + +fn pictures_in(part: &Json, data_dir: Option<&std::path::Path>) -> Option { + let paths: Vec<&str> = part["previewPaths"] + .as_array()? + .iter() + .filter_map(Json::as_str) + .filter(|p| stored_tool_picture(p, data_dir)) + .take(MAX_PICTURES) + .collect(); + if paths.is_empty() { + return None; + } + // (The call's file names its one picture; several are each their own.) + let named = (paths.len() == 1) + .then(|| part["call"]["path"].as_str().and_then(file_name)) + .flatten(); + let list: Vec = paths + .iter() + .map(|path| { + let name = named.or_else(|| file_name(path)).unwrap_or_default(); + Value::record([("path", Value::from(*path)), ("name", Value::from(name))]) + }) + .collect(); + Some(Value::List(list.into())) +} + +/// Whether `path` is a copy the engine stored of a tool result's picture: +/// named as the engine names them (`tool---image.`, a +/// raster it sniffed). A local chat's pictures are read straight from disk, +/// so one that is here must also be a file within the engine's data (its +/// profiles' uploads) and no larger than a picture can be: a doc naming +/// `/dev/zero`, a picture elsewhere on this Mac, or a huge file is never +/// opened. One on another device is read from there, through its engine's +/// own jail. +fn stored_tool_picture(path: &str, data_dir: Option<&std::path::Path>) -> bool { + let Some(name) = file_name(path) else { + return false; + }; + let Some(stem) = ["png", "jpg", "webp", "gif"] + .iter() + .find_map(|ext| name.strip_suffix(&format!("-image.{ext}"))) + else { + return false; + }; + let mut parts = stem.splitn(3, '-'); + let hex = |s: Option<&str>, len: usize| { + s.is_some_and(|s| s.len() == len && s.bytes().all(|b| b.is_ascii_hexdigit())) + }; + if parts.next() != Some("tool") || !hex(parts.next(), 16) || !hex(parts.next(), 64) { + return false; + } + let Ok(meta) = std::fs::symlink_metadata(path) else { + // (Not on this device: another's, read through its engine.) + return true; + }; + let within = || -> Option { + let file = std::fs::canonicalize(path).ok()?; + let data = std::fs::canonicalize(data_dir?).ok()?; + Some(file.starts_with(data) && file.components().any(|c| c.as_os_str() == "uploads")) + }; + meta.is_file() + && meta.len() <= zeron_proto::IMAGE_MAX_BYTES as u64 + && within().unwrap_or(false) +} + +fn file_name(path: &str) -> Option<&str> { + path.rsplit(['/', '\\']).find(|s| !s.is_empty()) +} + #[cfg(test)] mod tests { use super::*; + const STORED: &str = "/home/me/.zeron/uploads/tool-0123456789abcdef-0000000000000000000000000000000000000000000000000000000000000001-image.png"; + + #[test] + fn a_result_s_stored_pictures_are_the_row_s_named_as_the_call_s_file() { + let part = json!({ + "kind": "tool", "id": "t1", "isError": false, + "call": { "kind": "readFile", "path": "/home/me/scratch/shot.png" }, + "previewPaths": [STORED], + }); + let fields = tool_fields(&part); + let (_, pictures) = fields.iter().find(|(k, _)| *k == "pictures").expect("pictures"); + let Value::List(list) = pictures else { panic!("not a list: {pictures:?}") }; + assert_eq!(list.len(), 1); + assert_eq!(list[0].field("path").map(crate::auth::text).as_deref(), Some(STORED)); + assert_eq!(list[0].field("name").map(crate::auth::text).as_deref(), Some("shot.png")); + // Several: each is its own, not all the call's one file. + let two = STORED.replace("01-image.png", "02-image.png"); + let several = json!({ + "kind": "tool", "id": "t3", + "call": { "kind": "readFile", "path": "/home/me/scratch/shot.png" }, + "previewPaths": [STORED, two], + }); + let Some(Value::List(list)) = pictures_in(&several, None) else { panic!("no pictures") }; + let names: Vec<_> = list.iter().map(|p| p.field("name").map(crate::auth::text).unwrap_or_default()).collect(); + assert!(names.iter().all(|n| n.starts_with("tool-") && n.ends_with("-image.png")), "{names:?}"); + // None stored (an older doc, a path only named): no pictures. + let bare = json!({ "kind": "tool", "id": "t2", "call": { "kind": "readFile", "path": "/x/a.png" } }); + assert!(!tool_fields(&bare).iter().any(|(k, _)| *k == "pictures")); + } + + /// Only the engine's own copies are a row's pictures: a doc naming a + /// device file, a picture elsewhere on this computer, or a huge file + /// under the engine's name is never read; a copy inside the engine's + /// uploads is. + #[test] + fn only_the_engines_stored_copies_are_pictures() { + let data = tempfile::tempdir().unwrap(); + let uploads = data.path().join("orgs").join("o").join("uploads"); + std::fs::create_dir_all(&uploads).unwrap(); + let name = "tool-0123456789abcdef-0000000000000000000000000000000000000000000000000000000000000001-image.png"; + let inside = uploads.join(name); + std::fs::write(&inside, b"\x89PNG\r\n\x1a\n").unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + let outside = elsewhere.path().join(name); + std::fs::write(&outside, b"\x89PNG\r\n\x1a\n").unwrap(); + let big = uploads.join(name.replace("01-image", "02-image")); + std::fs::File::create(&big).unwrap().set_len(zeron_proto::IMAGE_MAX_BYTES as u64 + 1).unwrap(); + let dir = Some(data.path()); + let ok = |p: &std::path::Path| stored_tool_picture(p.to_str().unwrap(), dir); + assert!(ok(&inside)); + assert!(!ok(&outside), "a copy outside the engine's data"); + assert!(!ok(&big), "larger than a picture can be"); + assert!(!stored_tool_picture(inside.to_str().unwrap(), None), "no data dir to check against"); + #[cfg(unix)] + { + let link = uploads.join(name.replace("01-image", "03-image")); + std::os::unix::fs::symlink(&outside, &link).unwrap(); + assert!(!ok(&link), "a link out of uploads"); + } + for path in ["/dev/zero", "/etc/hosts", "/home/me/Pictures/private.png", "/x/uploads/ab12-image.png", "/x/uploads/tool-0123-01-image.png", ""] { + assert!(!stored_tool_picture(path, dir), "{path}"); + } + // Another device's copy (no such file here) is read there, by its engine. + assert!(stored_tool_picture(&format!("/Users/other/.zeron/uploads/{name}"), dir)); + } + #[test] fn a_diff_is_hunks_with_three_lines_of_context_numbered_from_one() { let old = (1..=20).map(|i| format!("line {i}\n")).collect::(); diff --git a/apps/zgx/ui/account/agents.luau b/apps/zgx/ui/account/agents.luau index 102e9ef41..a5a218401 100644 --- a/apps/zgx/ui/account/agents.luau +++ b/apps/zgx/ui/account/agents.luau @@ -8,6 +8,8 @@ -- list = { Agent } } -- agents.load() looks again (and the first time) -- agents.sign_in(id) a new account for that agent, through the browser +-- agents.sign_in_to(id, provider) the same, for one model provider of +-- an agent that keeps a login per provider -- agents.cancel(id) gives up that sign-in -- agents.dismiss(id) forgets one that failed -- agents.set_enabled(id, on) @@ -26,6 +28,16 @@ -- week_resets? }, `session` and `week` its plan's two windows, 0 to 1, and -- when each starts over (seconds since the epoch). -- +-- An agent that keeps a login per model provider (Pi, OpenCode, Hermes) +-- also has `groups`: its accounts by provider, `{ id, name, accounts, +-- login?, key?, hint?, read_only }` (`login`, who Zeron signs you in to for +-- it; `key`, who issues the API key Zeron adds; neither: `hint` says how the +-- agent does), and its sign-in's provider, `login_for`. Its accounts each +-- say their `provider`. +-- agents.add_key(id, provider, key) an API key for one such provider on +-- this Mac's agent (a promise; rejects with why not — +-- "remote" while another device is shown) +-- -- A Codex account also has what it banks: `banked` (how many resets) and -- `resets`, soonest to expire first ({ id, title, scope?, expires? }, -- `expires` in seconds since the epoch), and its last reset's word, @@ -52,6 +64,17 @@ export type Account = { banked: number?, resets: { Reset }?, reset: ResetWord?, + switchable: boolean?, + provider: string?, +} +export type Group = { + id: string, + name: string, + accounts: { Account }, + login: string?, + key: string?, + hint: string?, + read_only: boolean?, } export type Agent = { id: string, @@ -64,6 +87,8 @@ export type Agent = { installing: boolean, login: string, accounts: { Account }, + groups: { Group }?, + login_for: string?, } export type Now = { state: string, list: { Agent }, target: string? } @@ -85,6 +110,38 @@ function M.sign_in(id: string) ui.call("agents.sign_in", id):after(function() end, quietly()) end +-- A new account for one model provider of an agent that keeps a login per +-- provider (one of its `groups`). +function M.sign_in_to(id: string, provider: string) + ui.call("agents.sign_in", { id = id, provider = provider }):after(function() end, quietly()) +end + +-- An API key for one provider of an agent that keeps a login per provider, +-- on this Mac (a key is never sent to another device): a promise. +function M.add_key(id: string, provider: string, key: string, name: string?): any + return ui.call("agents.add_key", { id = id, provider = provider, key = key, name = name or "" }) +end + +-- An API key's name (empty: its default, " ···"): a promise. +function M.rename(id: string, account: string, name: string): any + return ui.call("agents.rename", { id = id, account = account, name = name }) +end + +-- A key asked for from elsewhere (the model picker's Account row): which +-- agent's which provider ("pi:openrouter"), for its card to open its key +-- field; "" once it has. +M.key_request = ui.state("agents_key_request", "") + +-- Again, the sign-in that failed: to the provider it was for, if it was for +-- one. +function M.retry(a: Agent) + if a.login_for then + M.sign_in_to(a.id, a.login_for) + else + M.sign_in(a.id) + end +end + function M.cancel(id: string) ui.invoke("agents.cancel", id) end @@ -124,8 +181,10 @@ function M.set_enabled(id: string, on: boolean) ui.call("agents.set_enabled", { id = id, enabled = on }):after(function() end, quietly()) end -function M.switch(id: string, account: string) - ui.call("agents.switch", { id = id, account = account }):after(function() end, quietly()) +-- That account in use: a promise, rejecting with why not (the engine's +-- words, or "offline"). +function M.switch(id: string, account: string): any + return ui.call("agents.switch", { id = id, account = account }) end -- Each device's accounts for its composers, by device id ("": this one's), @@ -133,6 +192,11 @@ end -- plan, active, can_switch, error?, windows = { { label, used } } }`. M.on_device = ui.shared("agents.on_device", {} :: { [string]: { [string]: { any } } }) +-- Each per-provider agent's providers Zeron adds to, by provider: `{ +-- [harness] = { [provider] = { name, login?, key? } } }` (who it signs you +-- in to, who issues the key it adds). +M.logins = ui.shared("agents.logins", {} :: { [string]: { [string]: { name: string, login: string?, key: string? } } }) + -- Their accounts, on first sight of a device. (A host with no accounts to -- say, a fixture's: none come.) function M.watch_device(key: string) diff --git a/apps/zgx/ui/account/sessions.luau b/apps/zgx/ui/account/sessions.luau index 22b51e557..7940c4c68 100644 --- a/apps/zgx/ui/account/sessions.luau +++ b/apps/zgx/ui/account/sessions.luau @@ -77,6 +77,11 @@ export type Chat = { -- woke (Unix seconds). sleep_until: number?, woke: number?, + -- The last turn its agent finished (an opaque mark, nil before its + -- first), and whether its session row was fresh as that was read: what + -- the "finished" chime rings on moving (screens/settings/chimes). + turn: string?, + turn_fresh: boolean?, } export type WaitingOn = { id: string, kind: string, label: string } -- A side chat: a chat under another (its `parent`). diff --git a/apps/zgx/ui/assets/icons/provider-anthropic.svg b/apps/zgx/ui/assets/icons/provider-anthropic.svg new file mode 100644 index 000000000..cbfbc69cc --- /dev/null +++ b/apps/zgx/ui/assets/icons/provider-anthropic.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/zgx/ui/assets/icons/provider-deepseek.svg b/apps/zgx/ui/assets/icons/provider-deepseek.svg new file mode 100644 index 000000000..cf8e9a8e9 --- /dev/null +++ b/apps/zgx/ui/assets/icons/provider-deepseek.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/zgx/ui/assets/icons/provider-gemini.svg b/apps/zgx/ui/assets/icons/provider-gemini.svg new file mode 100644 index 000000000..953e56267 --- /dev/null +++ b/apps/zgx/ui/assets/icons/provider-gemini.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/zgx/ui/assets/icons/provider-openai.svg b/apps/zgx/ui/assets/icons/provider-openai.svg new file mode 100644 index 000000000..3f4000510 --- /dev/null +++ b/apps/zgx/ui/assets/icons/provider-openai.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/zgx/ui/assets/icons/provider-openrouter.svg b/apps/zgx/ui/assets/icons/provider-openrouter.svg new file mode 100644 index 000000000..a9c4752f3 --- /dev/null +++ b/apps/zgx/ui/assets/icons/provider-openrouter.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/zgx/ui/assets/icons/provider-xai.svg b/apps/zgx/ui/assets/icons/provider-xai.svg new file mode 100644 index 000000000..8c5f59324 --- /dev/null +++ b/apps/zgx/ui/assets/icons/provider-xai.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/zgx/ui/chat_fixture.luau b/apps/zgx/ui/chat_fixture.luau index 651d89aa8..16d15fda3 100644 --- a/apps/zgx/ui/chat_fixture.luau +++ b/apps/zgx/ui/chat_fixture.luau @@ -92,6 +92,13 @@ do note(`switch_on:{key}:{id}:{account}`) return { after = function(_: any, done: (any) -> ()) done(nil) end } end + -- (An Account row adding one of its provider's accounts.) + stub_agents.target = function(device: string?) + note(`target:{device or ""}`) + end + stub_agents.sign_in_to = function(id: string, provider: string) + note(`sign_in_to:{id}:{provider}`) + end end local function publish(id: string, patch: { [string]: any }?) @@ -879,6 +886,16 @@ ui.command { end, } +-- A settled reply the host gave no time (as Windows did before it could +-- read one): its Copy shows all the same (tests/chat_in_place). +ui.command { + id = "reply_without_time", + title = "A reply with no time", + run = function() + store.messages:push { id = "notime1", role = "assistant", text = "Answered with no clock.", copy = "Answered with no clock." } + end, +} + -- Messages from other chats, as the host gives them: one from a chat that's -- listed, one from a chat that isn't, one with a long title (tests/chat_sender). ui.command { @@ -1165,6 +1182,17 @@ ui.command { seed() end, } +-- A Codex session on its agent's default model (none set, so none the +-- catalog names): its agent only the one its config records. +ui.command { + id = "codex_model_less", + title = "A Codex session with no model", + run = function() + META.s3 = { title = "Codex chat", project = "atlas", agent = "codex", harness = "codex", access = "full", plan = false } + TRANSCRIPTS.s3 = { { id = "z1", role = "user", text = "Hi" } } + seed() + end, +} -- A session of long messages (each folds to five lines). do local long_chat = {} @@ -1588,6 +1616,29 @@ ui.effect(function() table.sort(keys) plugin_comments:set(table.concat(keys, ",")) end) +-- The draft lifted out whole and laid back (a plugin's `zeron.take_draft` +-- and `put_draft`; screens/plugins keeps it between the two, as this +-- does). `test_lifted` says what was lifted: its words and how many chips. +local lifted: any = nil +local lifted_said = ui.state("test_lifted", "") +ui.command { + id = "draft_lift", + title = "A plugin takes the draft", + run = function() + lifted = require("@app/screens/chat/shared").lift() + lifted_said:set(if lifted then `{lifted.text}|{#lifted.cargo}` else "nothing") + end, +} +ui.command { + id = "draft_lay", + title = "A plugin puts the draft back", + run = function() + if lifted then + require("@app/screens/chat/shared").lay(lifted) + lifted = nil + end + end, +} ui.command { id = "comment_moves", title = "The comment is carried two lines down", diff --git a/apps/zgx/ui/chimes_fixture.luau b/apps/zgx/ui/chimes_fixture.luau new file mode 100644 index 000000000..a9788cbae --- /dev/null +++ b/apps/zgx/ui/chimes_fixture.luau @@ -0,0 +1,7 @@ +-- The session chimes (screens/settings/chimes) with no engine: a test sets +-- the `sessions` shared state as the engine would publish it, and reads what +-- played from `settings_stub_calls` ("sound.play:done", …). +require("./settings_stub") +require("@app/screens/settings/chimes") + +return ui.column {} diff --git a/apps/zgx/ui/composer_fixture.luau b/apps/zgx/ui/composer_fixture.luau index 351e4a07f..df1bf47b5 100644 --- a/apps/zgx/ui/composer_fixture.luau +++ b/apps/zgx/ui/composer_fixture.luau @@ -6,6 +6,8 @@ ui.theme.strict("warn") local ds = require("@ds") local Composer = require("@ds/composer") +local Cargo = require("@ds/composer_cargo") +local Ask = require("@ds/composer_ask") ds.setup() local HARNESSES: { ds.Harness } = { { id = "claude", label = "Claude", mark = "claude" } } @@ -28,6 +30,9 @@ return ui.column { harnesses = HARNESSES, models = MODELS, notice = ui.state("test_composer_notice", nil :: Composer.Notice?), + dictating = ui.state("test_composer_dictating", false), + cargo = ui.state("test_composer_cargo", {} :: { Cargo.Item }), + question = ui.state("test_composer_question", nil :: Ask.Question?), project = ui.state("test_composer_project", "atlas" :: string?), projects = PROJECTS, }, diff --git a/apps/zgx/ui/composer_metrics_fixture.luau b/apps/zgx/ui/composer_metrics_fixture.luau new file mode 100644 index 000000000..ed634b407 --- /dev/null +++ b/apps/zgx/ui/composer_metrics_fixture.luau @@ -0,0 +1,55 @@ +local ds = require("@ds") +local Metrics = require("@ds/composer_metrics") +ds.setup() + +local value = ui.state("fixture_metrics_text", "") +local width = ui.state("fixture_metrics_width", 320) +local viewport = ui.state("fixture_metrics_viewport", 800) +local editor_key = ui.state("fixture_metrics_editor", 1) +local field = ui.ref() +local metrics = Metrics.use { + value = value, + width = function(peek: boolean?) + return if peek then width:peek() else width:get() + end, + editor = field, + keep = "fixture", +} +local result = ui.state("fixture_metrics_result", {} :: any) +local history = ui.state("fixture_metrics_history", {} :: { string }) +ui.effect(function() + local r = metrics.result:get() + result:set(r) + local h = table.clone(history:peek()) + table.insert(h, r.status) + history:set(h) +end) + +ui.command { + id = "fixture.metrics.type", + title = "Larger composer type", + run = function() + ui.theme.tokens { zeron = { composer = { text = 18, line = 28 } } } + end, +} + +return ui.div { + w = viewport, + h_full = true, + relative = true, + ui.presence(function(): string return tostring(editor_key:get()) end, function(): Node + return ui.textarea { + id = "metrics-editor", + ref = field, + value = value, + w_full = true, + h = 22, + text_size = "$zeron.composer.text", + line_height = "$zeron.composer.line", + highlight = function(line) + local a, b = string.find(line, "@[%w_]+") + return if a then { { a, b, weight = 700 } } else {} + end, + } + end), +} diff --git a/apps/zgx/ui/composer_transition_fixture.luau b/apps/zgx/ui/composer_transition_fixture.luau new file mode 100644 index 000000000..66009c954 --- /dev/null +++ b/apps/zgx/ui/composer_transition_fixture.luau @@ -0,0 +1,42 @@ +-- Controller-only fixture: no engine, editor or unrelated animations. +local ds = require("@ds") +local Layout = require("@ds/composer_layout") +local Motion = require("@ds/composer_motion") +ds.setup() +local width = ui.state("fixture_transition_width", 660) +local height = ui.state("fixture_transition_height", 22) +local shown = ui.state("fixture_transition_shown", true) +local snap = ui.state("fixture_transition_snap", 0) +local ready = ui.state("fixture_transition_ready", true) +local revision = ui.state("fixture_transition_revision", 0) +local settlement = ui.computed(function() + return { revision = revision:get(), status = if ready:get() then "ready" else "pending" } +end) +local report = ui.state("fixture_transition_report", {} :: any) +local target = ui.computed(function() + return Layout.calculate({ + width = width:get(), + sample = { unwrapped_width = 40, wrapped_height = height:get(), line_height = 22 }, + trailing_width = 64, control_corner = 25, + header_height = 0, header_gap = 12, + expanded = false, cargo = false, asking = false, dictating = false, + multiline = height:get() > 22, + }, false) +end) +local last: any = nil +ui.command { + id = "fixture.transition.inspect", + title = "Inspect the last controller, even after unmount", + run = function() + if last then + report:set({ frame = last.frame:peek(), origin = last.origin:peek(), + destination = last.destination:peek(), progress = last.progress:peek(), active = last.active:peek(), settling = last.settling:peek() }) + end + end, +} +local Controller = ui.component(function(): Node + last = Motion.use(target, snap, settlement) + local own = last + return ui.div { w = width, h = function() return own.frame:get().height end } +end) +return ui.show(function() return shown:get() end, Controller {}) diff --git a/apps/zgx/ui/composer_transition_preview.luau b/apps/zgx/ui/composer_transition_preview.luau new file mode 100644 index 000000000..050df4754 --- /dev/null +++ b/apps/zgx/ui/composer_transition_preview.luau @@ -0,0 +1,65 @@ +-- Real composer for visual transition checks. All input is fixture-local; +-- the development host's engine/account updates cannot replace this draft. +-- It leaves the build's own settings as it found them: Reduce motion is +-- persisted (`motion_reduce`), so it is only changed by its button here and +-- put back as the preview goes, as is the theme it shows in. +local ds = require("@ds") +local motion = require("@ds/motion") +ds.setup() +local reduce_was = motion.reduce:peek() +local theme_was = ui.theme.current:peek() +ui.theme.current:set("zeron-dark") + +local draft = ui.state("fixture_preview_draft", "short") +local focus = ui.state("fixture_preview_focus", 0) +local cargo = ui.state("fixture_preview_cargo", {} :: { any }) +local function lines(n: number): string + local out = {} + for i = 1, n do table.insert(out, `Line {i} for composer transition checks`) end + return table.concat(out, "\n") +end +local function set_draft(text: string) + ui.batch(function() + draft:set(text) + focus:set(focus:peek() + 1) + end) +end + +local Preview = ui.component(function(): Node + ui.on_cleanup(function() + if motion.reduce:peek() ~= reduce_was then + motion.reduce:set(reduce_was) + end + ui.theme.current:set(theme_was) + end) + return ui.column { + w_full = true, h_full = true, p = "$space.4", gap = "$space.4", + bg = "$background", + ui.row { + gap = "$space.2", + ds.Button { "Short", on_click = function() set_draft("short") end }, + ds.Button { "10 lines", on_click = function() set_draft(lines(10)) end }, + ds.Button { "80 lines", on_click = function() set_draft(lines(80)) end }, + ds.Button { "Header", on_click = function() + cargo:set(if #cargo:peek() == 0 then { { id = "f", kind = "file", name = "notes.md" } } else {}) + focus:set(focus:peek() + 1) + end }, + -- (scripts/composer_frames.py clicks these by place: keep the labels.) + ds.Button { "Reduce motion", on_click = function() motion.reduce:set(not motion.reduce:peek()) end }, + ds.Button { "Wrap", on_click = function() set_draft(string.rep("W", 60)) end }, + }, + ui.div { grow = 1 }, + ui.div { + w = 660, + ds.Composer { + value = draft, cargo = cargo, focus = focus, + model = ui.state("fixture_preview_model", "sonnet" :: string?), + effort = ui.state("fixture_preview_effort", "medium" :: string?), + harnesses = { { id = "claude", label = "Claude", mark = "claude" } }, + models = { { value = "sonnet", label = "Sonnet", harness = "claude" } }, + }, + }, +} +end) + +return Preview {} diff --git a/apps/zgx/ui/consent_fixture.luau b/apps/zgx/ui/consent_fixture.luau index 666c0d1fd..0c70daf87 100644 --- a/apps/zgx/ui/consent_fixture.luau +++ b/apps/zgx/ui/consent_fixture.luau @@ -174,9 +174,9 @@ local PLUGINS: { [string]: any } = { hash = "long-1", status = "pending", author = { kind = "unknown" }, - permissions = { "ui.add", "ui.change", "profile.read", "sessions.read", "messages.read", "account.email", "files.read", "panel.tabs", "pages.add", "github", "github.write", "notifications", "links.open", "navigate", "compose", "network", "clipboard", "files", "web", "windows", "tools", "devices", "service", "commands", "native" }, + permissions = { "ui.add", "ui.change", "profile.read", "sessions.read", "messages.read", "account.email", "files.read", "panel.tabs", "pages.add", "github", "github.write", "notifications", "links.open", "navigate", "compose", "draft", "network", "clipboard", "files", "web", "windows", "tools", "devices", "service", "commands", "native" }, allowed = {}, - ask = { "ui.add", "ui.change", "profile.read", "sessions.read", "messages.read", "account.email", "files.read", "panel.tabs", "pages.add", "github", "github.write", "notifications", "links.open", "navigate", "compose", "network", "clipboard", "files", "web", "windows", "tools", "devices", "service", "commands", "native" }, + ask = { "ui.add", "ui.change", "profile.read", "sessions.read", "messages.read", "account.email", "files.read", "panel.tabs", "pages.add", "github", "github.write", "notifications", "links.open", "navigate", "compose", "draft", "network", "clipboard", "files", "web", "windows", "tools", "devices", "service", "commands", "native" }, ui = { change = { "#shell" } }, commands = { "git" }, tools = { { name = "a", description = "First." } }, diff --git a/apps/zgx/ui/ds/activity.luau b/apps/zgx/ui/ds/activity.luau index 5ee2ea6a0..4ecca2770 100644 --- a/apps/zgx/ui/ds/activity.luau +++ b/apps/zgx/ui/ds/activity.luau @@ -26,6 +26,7 @@ local status = require("@self/status") local ToolDetail = require("@self/tool_detail") local Markdown = require("@self/markdown") local locale = require("@self/locale") +local ReplyPicture = require("@self/reply_picture") local FoldButton = require("@self/fold_button") -- (`cloud`, `git`: a Cloud machine's own setup steps, the machine and its @@ -62,6 +63,10 @@ export type Tool = { diff_ref: string?, stats: { ToolDetail.Stat }?, diff: ToolDetail.Diff?, + -- The pictures its result carried (a Read of a screenshot), as the + -- engine keeps them: copies on the chat's host, which the row opens to + -- (Zeron's chip previews, crates/ui tool_images.rs). + pictures: { { path: string, name: string? } }?, } export type Writing = { words: (id: string) -> string?, seeded: () -> boolean } @@ -83,6 +88,9 @@ export type Props = { -- A subagent's spawn row (its tool's `subagent`): what opens it (its -- lane). Without it, the row opens its call as any does. open_subagent: ((sub: any) -> ())?, + -- Where a tool's pictures are read from (ds/transcript's + -- `shown_pictures`: files on the chat's host). Without it, none show. + pictures: ReplyPicture.Pictures?, -- A thought being written: `words`, a thought's words as they arrive, by -- its id (nil for one not being written: the reply's draft holds them, -- so a tick of them doesn't build its rows again); `seeded`, whether what @@ -229,14 +237,46 @@ end -- scrolled back): each tool's call by its id, each group by its key. One -- map each, holding only what's open (or, for a group, chosen), not a -- state per tool. --- A row's call and what it did, as it opens (`row`): `now`, its tool. -local Opened = ui.component(function(props: { now: () -> Tool }): Node + +-- A tool's pictures under its opened row: small thumbnails in a row (the +-- theme's `zeron.prose.picture.thumb`), each opening in the lightbox among +-- the others, a lightbox group of their own. +local function tool_pictures(now: () -> Tool, shown: ReplyPicture.Pictures): Node + local function entries(): { ReplyPicture.Entry } + local out = {} + for _, it in now().pictures or {} do + table.insert(out, { src = it.path, alt = it.name or "" }) + end + return out + end + return ReplyPicture.Thumbs { pictures = shown, items = entries, group = `tool:{now().id}`, set = entries } +end + +-- A row's call and what it did, as it opens (`row`): `now`, its tool; +-- `pictures`, where its result's pictures are read from (without it, they +-- don't show). +local Opened = ui.component(function(props: { now: () -> Tool, pictures: ReplyPicture.Pictures? }): Node local now = props.now + local pictures = props.pictures return ui.column { w_full = true, ui.show(function(): boolean return now().call ~= nil end, call_block(now)), + if pictures + then ui.show( + function(): boolean + local list = now().pictures + return list ~= nil and #list > 0 + end, + ui.div { + ml = ui.raw(GUTTER, "under the line's words, past the tree's gutter"), + mt = "$space.1", + mb = "$space.1", + tool_pictures(now, pictures), + } + ) + else nil, ui.show( function(): boolean return ToolDetail.has(now() :: any) @@ -555,7 +595,8 @@ local function row( writing: Writing?, group: string?, resized: ((size: { w: number, h: number }) -> ())?, - settled: boolean? + settled: boolean?, + pictures: ReplyPicture.Pictures? ): Node local t = now() if t.kind == "thought" then @@ -573,9 +614,14 @@ local function row( local function has_detail(): boolean return ToolDetail.has(now() :: any) end + -- The pictures its result carried, where they can be read. + local function has_pictures(): boolean + local list = now().pictures + return pictures ~= nil and list ~= nil and #list > 0 + end -- Open as the reader left it (opened or closed), else closed. local function showing(): boolean - if not (has_call() or has_detail()) then + if not (has_call() or has_detail() or has_pictures()) then return false end return CALLS_OPEN:get()[id] == true @@ -584,7 +630,7 @@ local function row( local function lane(): any return if open_subagent then (now() :: any).subagent else nil end - local opens = t.call ~= nil or lane() ~= nil or OPENS[t.kind] == true + local opens = t.call ~= nil or lane() ~= nil or OPENS[t.kind] == true or has_pictures() -- (Only a subagent's spawn says more than its line: one that may open -- its lane follows it.) local label: string | () -> string = if t.target then `{t.verb} {line_of(t)}` else t.verb @@ -650,7 +696,7 @@ local function row( open_subagent(sub) return end - if has_call() or has_detail() then + if has_call() or has_detail() or has_pictures() then local all = table.clone(CALLS_OPEN:peek()) all[id] = not showing() CALLS_OPEN:set(all) @@ -749,7 +795,7 @@ local function row( }, -- What it opens to, made only once it's opened (a component's body -- runs as it mounts: closed, nothing of it is made). - ui.show(showing, Opened { now = now }), + ui.show(showing, Opened { now = now, pictures = pictures }), } end @@ -907,7 +953,7 @@ return ui.component(function(props: Props): Node return place() < last_branch:get() end, function(): boolean return live() and place() == count:get() - end, props.open_subagent, props.thought, props.key, resized, place() < count:peek()) + end, props.open_subagent, props.thought, props.key, resized, place() < count:peek(), props.pictures) end -- (A call arriving joins as a row joining a `ui.each` does; the rest -- are made as they come into view, as they were.) diff --git a/apps/zgx/ui/ds/composer.luau b/apps/zgx/ui/ds/composer.luau index 10a7eaa5d..7b876dd88 100644 --- a/apps/zgx/ui/ds/composer.luau +++ b/apps/zgx/ui/ds/composer.luau @@ -54,9 +54,17 @@ local mentions = require("@self/composer_mentions") local locale = require("@self/locale") local VoiceWave = require("@self/voice_wave").VoiceWave local context_usage = require("@self/context_usage") -local motion = require("@self/motion") +local TextMetrics = require("@self/composer_metrics") +local Layout = require("@self/composer_layout") +local ComposerMotion = require("@self/composer_motion") local EditorMenu = require("@self/editor_menu") +type ViewGeometry = { + height: number, header_height: number, tray_inset: number, + text: { left: number, right: number, top: number, height: number }, + controls: Layout.Controls, +} + -- What the model's context holds, as its agent reports it: the tokens in -- it and the window's size (either may be missing). export type Usage = context_usage.Usage @@ -91,7 +99,9 @@ export type Notice = { export type Answer = { values: { string }, text: string } -- Where an existing chat works (`branch_fixed`). export type Fixed = { device: string?, name: string?, worktree: boolean, project: string?, hue: string?, src: string?, emoji: string? } +export type Sizes = { rest: number, target: number, presented: number, active: boolean, ready: boolean, settling: boolean, context: number } export type Props = { + on_sizes: ((sizes: Sizes) -> ())?, value: State, placeholder: (string | Message)?, -- What sends (the shipping app's setting): "enter", ↩ sends and ⇧↩ @@ -136,7 +146,8 @@ export type Props = { default_model: (() -> string?)?, -- A model's agent's accounts, putting one in use, and asking after them -- again (ds.ModelPicker's). - accounts: ((harness: string, model: string) -> { ModelPicker.Account }?)?, + accounts: ((harness: string, model: string, provider: string?) -> { ModelPicker.Account }?)?, + account_group: ((harness: string, provider: string?) -> ModelPicker.AccountGroup?)?, on_account: ((harness: string, id: string) -> ())?, on_accounts_open: (() -> ())?, -- How much of the model's context is used (0 to 1): a ring beside its @@ -293,39 +304,6 @@ export type Props = { mention_sections: { [string]: { { id: string, label: any } } }?, } --- Zeron's geometry. The one line: 47 points inside the hairline, the text --- centred in it. Opened out: the text box (16 above the text, 4 below) --- between its floor and cap, then the controls' row (2, a 32-point chip --- zone, 8). Round controls are 28 across, concentric with the pill's --- corner: on one line (a pill, its corner half its height) centred in it, --- as far from its sides as from its foot; opened out, as far in from the --- side and the foot as the pill's corner (inside its hairline) is round --- less theirs. -local LINE = 22 -local ONE_LINE = 47 -local TEXT_TOP, TEXT_BOTTOM, TEXT_MIN, TEXT_MAX = 16, 4, 76, 260 -local ACTIONS = 42 -local HAIRLINES = 2 -local CONTROL = 28 -local INSET_LINE = (ONE_LINE - CONTROL) / 2 -local function open_inset(): number - return control.nest("$zeron.composer.radius", 1) - CONTROL / 2 -end --- The controls' row opened out: its 42 points, or more where a rounder --- pill (a template's) sets its controls further in from the foot, so they --- keep the room over them they have at Zeron's own corner (its controls' --- top 3 under the row's) rather than rising into the text. -local ACTIONS_OVER = 3 -local function actions(): number - return math.max(ACTIONS, open_inset() + CONTROL + ACTIONS_OVER) -end --- The draft's own inset either side on one line, and opened out. -local TEXT_SIDE = 8 -local TEXT_OPEN_SIDE = 16 --- Opened out, the pill folds back to one line only once the text is this --- much narrower than the line holds, so a width at the boundary cannot --- flicker between the two. -local HYSTERESIS = 32 -- How wide where-it-works stays before the access mode folds: its project's -- name (to PROJECT_MAX) and BRANCH_KEEP of the branch's, with the chip's -- own room (its padding, the glyph, the gaps, the chevron); until @@ -982,14 +960,6 @@ fn fill(input: FillInput) -> vec4 { local lightboxes = 0 return ui.component(function(props: Props): Node - -- Opened out, the controls' inset: from the theme's corner, as this one - -- is built. - local INSET_OPEN = open_inset() - -- On the tray, the chips' inset from the pill's edge above them, the - -- tray's foot and its sides: the pill's own controls' (+ and Send sit - -- this far in from its edge, its hairline and INSET_OPEN), so the row - -- keeps the pill's spacing and its chips line up with those buttons. - local TRAY_INSET = INSET_OPEN + HAIRLINES / 2 -- On the tray, the step under the pill and above the tray's foot (one -- token: the footer's margins and the tray's height both read it), and -- how far the tray tucks up behind the pill, its top hidden there. @@ -1018,8 +988,26 @@ return ui.component(function(props: Props): Node return if props.keep then ui.state(`composer:{props.keep}:{key}`, initial) else ui.use_state(initial) end local pill_w = kept("pill_w", 0) - local line_w = kept("line_w", 0) - local wrapped_h = kept("wrapped_h", 0) + local metrics = TextMetrics.use { + value = value, + keep = props.keep, + editor = field, + width = function(peek: boolean?): number + -- The surface's content box excludes its two hairlines. Both + -- expanded text insets come out of that, never the eased field. + return Layout.measurement(if peek then pill_w:peek() else pill_w:get()).width + end, + -- Past the cap a draft is measured no more: its size changes nothing + -- (Layout.estimate). The type's line height changed (tracked), it is + -- measured again. + estimate = function(text: string, line_height: number): Layout.Sample? + local line = ui.theme.get("zeron.composer.line") + if type(line) == "number" and math.abs(line - line_height) > 0.01 then + return nil + end + return Layout.estimate(text, line_height) + end, + } local head_h_seen = kept("head_h", 0) local trailing_seen = kept("trailing_w", 0) local footer_w = kept("footer_w", 0) @@ -1171,128 +1159,62 @@ return ui.component(function(props: Props): Node return (if w > 0 then w else 1000) < NARROW end - -- One line or opened out. On one line the text has the pill less the - -- leading control and the trailing ones; opened out, it folds back only - -- once comfortably short again. Anything over the draft opens it out. - -- The controls at the right, as measured; until they are (a composer - -- just made, a reload's), their usual two (the microphone and Send), - -- so the text is laid out where it rests from the first frame rather - -- than easing in from the full width. - local function trailing_w(): number - local w = trailing_seen:get() - return if w > 0 then w else CONTROL * 2 + 8 + -- A pure calculation owns all target geometry. The effect commits the + -- explicit text-hysteresis state; rendering/computeds mutate no history. + local previous_text_expanded = ui.use_state(read(props.expanded) == true) + local function layout_input(): Layout.Input + local _ = ui.theme.current:get() + return { + width = pill_w:get(), + -- Retain the last complete sample while a request is stale. + sample = metrics.sample:get(), + trailing_width = trailing_seen:get(), + control_corner = control.nest("$zeron.composer.radius", Layout.BORDER), + header_height = head_h_seen:get(), + header_gap = head_gap(), + expanded = read(props.expanded) == true, + cargo = has_cargo(), + asking = asking(), + dictating = dictating(), + multiline = string.find(value:get(), "\n") ~= nil, + } end - local function expanded(): boolean - return read(props.expanded) == true - end - local was_open = expanded() - local open = ui.computed(function(): boolean - -- Dictating, the words land in the draft over the track. - if expanded() or has_cargo() or asking() or dictating() then - return true - end - local text = value:get() - local width = pill_w:get() - local tail = trailing_w() - local need = line_w:get() - if width <= 0 then - return false - end - local room = width - HAIRLINES - (INSET_LINE + CONTROL + TEXT_SIDE) - (TEXT_SIDE + tail + INSET_LINE) - local want - if string.find(text, "\n") then - want = true - elseif was_open then - want = need > room - HYSTERESIS - else - want = need > room - end - was_open = want - return want - end) - - -- What is over the draft: nothing, or its measured height. - local head_h = ui.computed(function(): number - if not has_cargo() and not asking() then - return 0 - end - return head_h_seen:get() - end) - -- The text box opened out: the wrapped text with its insets, between - -- the floor and the cap. - local box = ui.computed(function(): number - local h = math.max(wrapped_h:get(), LINE) - return math.clamp(h + TEXT_TOP + TEXT_BOTTOM, TEXT_MIN, TEXT_MAX) - end) - local HEAD_GAP = head_gap() - local height = ui.computed(function(): number - if open:get() then - local head = head_h:get() - -- With something over it, the draft's box starts under that - -- with the strip's own gap rather than the pill's top. - return head + (if head > 0 then box:get() - TEXT_TOP + HEAD_GAP else box:get()) + actions() + HAIRLINES - end - return ONE_LINE + HAIRLINES - end) - -- Where the text sits: beside the controls on one line, over them - -- opened out, under whatever is over it. - local text_left = ui.computed(function(): number - return if open:get() then TEXT_OPEN_SIDE else INSET_LINE + CONTROL + TEXT_SIDE - end) - local text_right = ui.computed(function(): number - return if open:get() then TEXT_OPEN_SIDE else TEXT_SIDE + trailing_w() + INSET_LINE - end) - local text_top = ui.computed(function(): number - if not open:get() then - return (ONE_LINE - LINE) / 2 - end - local head = head_h:get() - return if head > 0 then head + HEAD_GAP else TEXT_TOP - end) - local text_h = ui.computed(function(): number - return if open:get() then box:get() - TEXT_TOP - TEXT_BOTTOM else LINE - end) - local EASE: TweenOptions = { duration = 220, ease = "out(3)" } - -- Each of the pill's measures as it shows: eased (EASE) as it grows or - -- shrinks in place; at once for a moment after `snap` moves (what - -- settles its size, measured, lands over a frame or two), and with - -- motion reduced. - local SNAP_MS = 400 - local snap_seen = if props.snap then props.snap:peek() else nil - local snap_until = 0 - local function at_once(): boolean - if props.snap then - local n = props.snap:get() - if n ~= snap_seen then - snap_seen = n - snap_until = ui.now() + SNAP_MS + local target_geometry = ui.use_state(Layout.calculate(layout_input(), previous_text_expanded:peek())) + ui.effect(function() + local next = Layout.calculate(layout_input(), previous_text_expanded:peek()) + ui.batch(function() + previous_text_expanded:set(next.next_text_expanded) + -- Only a target laid out differently: a pane resized changes the + -- widths layout applies itself, and a new target at each of its + -- frames woke the motion, its frame and every binding of it. + if not Layout.same_target(target_geometry:peek(), next) then + target_geometry:set(next) end - end - return motion.reduced_now() or ui.now() < snap_until - end - local function eased(src: ReadOnlyState): State - local value = ui.use_state(src:peek()) - local run: any = nil - ui.effect(function() - local v = src:get() - local now = at_once() - if run then - run:cancel() - run = nil - end - if now or math.abs(value:peek() - v) < 0.01 then - value:set(v) - return - end - run = anime.animate(value, { value = v, duration = EASE.duration, ease = EASE.ease }) end) - return value - end - -- (One on a line, another opened out.) - local function by_open(line: number, opened: number): State - return eased(ui.computed(function(): number - return if open:get() then opened else line - end)) + end) + local settlement = ui.computed(function() + local metrics_now = metrics.result:get() + local actual = pill.height + return { revision = metrics_now.revision, + status = if metrics_now.status == "ready" and actual ~= nil + and math.abs(actual - target_geometry:get().height) < 0.5 then "ready" else "pending" } + end) + local transition = ComposerMotion.use(target_geometry, props.snap, settlement) + local frame_geometry = transition.frame + -- Width is applied by layout, not a view binding. Project the presented + -- snapshot once so width/measurement metadata alone cannot wake every + -- height, inset and control binding in each split composer. + local view_geometry = ui.computed(function(): ViewGeometry + local g = frame_geometry:get() + return { height = g.height, header_height = g.header_height, + text = { left = g.text.left, right = g.text.right, top = g.text.top, height = g.text.height }, + controls = g.controls, tray_inset = g.tray_inset } + end) + -- Every binding reads the same frame snapshot; none starts an animation. + local function presented(select: (ViewGeometry) -> number): () -> number + return function(): number + return select(view_geometry:get()) + end end -- +, as a secondary button: a fill of its own, so it reads as a control @@ -1469,6 +1391,7 @@ return ui.component(function(props: Props): Node model_label = props.model_label, default_model = props.default_model, accounts = props.accounts, + account_group = props.account_group, on_account = props.on_account, on_accounts_open = props.on_accounts_open, placement = { side = at, align = "end", offset = 6 }, @@ -1658,9 +1581,9 @@ return ui.component(function(props: Props): Node return ui.div { absolute = true, -- (Insets take points: the control, the sides, and a breath.) - left = by_open(INSET_LINE + CONTROL + 8, INSET_OPEN + CONTROL + 8), - right = by_open(INSET_LINE + CONTROL * 2 + 8 + 8, INSET_OPEN + CONTROL * 2 + 8 + 8), - bottom = by_open(INSET_LINE, INSET_OPEN), + left = presented(function(g) return g.controls.voice.left end), + right = presented(function(g) return g.controls.voice.right end), + bottom = presented(function(g) return g.controls.voice.bottom end), h = "$zeron.composer.voice.h", ref = track_w, overflow = "hidden", @@ -1835,14 +1758,14 @@ return ui.component(function(props: Props): Node on_resize = measure(pill_w, "w"), relative = true, w_full = true, - h = eased(height), + h = presented(function(g) return g.height end), overflow = "hidden", -- (Its glass, edge and shadow are the frame's, round it and the deck -- over it: one surface. Its own corner only clips what's in it, and -- its edge, clear, keeps the room the frame's takes, so everything in -- it sits where it always has.) rounded = "$zeron.composer.radius", - border = 1, + border = Layout.BORDER, border_color = "#00000000", -- (Neither `on_files` nor its overlay: files are what's around it to -- take, the drop going on up to it.) @@ -1873,44 +1796,21 @@ return ui.component(function(props: Props): Node focus_on_press = false, on_press = to_draft, }, - -- The measures: the draft on one line, and wrapped as it would be - -- opened out (a mark after it, so a last empty line counts). - ui.text { - on_resize = measure(line_w, "w"), - absolute = true, - left = 0, - top = 0, - opacity = 0, - pointer_events = "none", - text_size = "$zeron.composer.text", - line_height = "$zeron.composer.line", - function() - return value:get() - end, + -- Measure the natural header inside a separate presented clip. The + -- clip's animated height must never feed the header measurement. + ui.div { + absolute = true, left = 0, right = 0, top = 0, + h = presented(function(g) return g.header_height end), + overflow = "hidden", + head, }, - ui.text { - on_resize = measure(wrapped_h, "h"), - absolute = true, - left = TEXT_OPEN_SIDE, - right = TEXT_OPEN_SIDE, - top = 0, - opacity = 0, - pointer_events = "none", - wrap = true, - text_size = "$zeron.composer.text", - line_height = "$zeron.composer.line", - function() - return value:get() .. "\u{200B}" - end, - }, - head, -- The draft. ui.div { absolute = true, - left = eased(text_left), - right = eased(text_right), - top = eased(text_top), - h = eased(text_h), + left = presented(function(g) return g.text.left end), + right = presented(function(g) return g.text.right end), + top = presented(function(g) return g.text.top end), + h = presented(function(g) return g.text.height end), ui.textarea(EditorMenu.on({ ref = field, value = value, @@ -2059,8 +1959,8 @@ return ui.component(function(props: Props): Node -- The controls, on the pill's foot. ui.div { absolute = true, - left = by_open(INSET_LINE, INSET_OPEN), - bottom = by_open(INSET_LINE, INSET_OPEN), + left = presented(function(g) return g.controls.leading.left end), + bottom = presented(function(g) return g.controls.leading.bottom end), ui.show(function() return not asking() end, attach), @@ -2069,10 +1969,10 @@ return ui.component(function(props: Props): Node ui.row { on_resize = measure(trailing_seen, "w"), absolute = true, - right = by_open(INSET_LINE, INSET_OPEN), + right = presented(function(g) return g.controls.trailing.right end), -- (Its row is 32: the control centred in it.) - bottom = by_open(INSET_LINE - 2, INSET_OPEN - 2), - h = 32, + bottom = presented(function(g) return g.controls.trailing.bottom end), + h = presented(function(g) return g.controls.trailing.height end), items = "center", gap = "$space.2", ui.show(asking, ask_controls()), @@ -2303,7 +2203,7 @@ return ui.component(function(props: Props): Node return if on_tray() then `${TRAY_GAP}` else 0 end :: any, px = function(): any - return if on_tray() then ui.raw(TRAY_INSET, "the pill's controls' inset") else "$zeron.space.snug" + return if on_tray() then ui.raw(view_geometry:get().tray_inset, "the pill's controls' inset") else "$zeron.space.snug" end :: any, items = "center", gap = "$space.1", @@ -2431,6 +2331,7 @@ return ui.component(function(props: Props): Node -- The pill (the mentions' popover anchored on it: its panel opens at -- the caret inside), its trays behind, the footer under. + local footer_size, deck_size, outer_size = ui.ref(), ui.ref(), ui.ref() local body = ui.column { w_full = true, relative = true, @@ -2441,7 +2342,7 @@ return ui.component(function(props: Props): Node -- footer, tucked behind the pill (its top hidden under it, its sides -- the pill's), so the chips sit on the composer's surface rather than -- on the art. They sit as far in from its sides as the pill's own - -- controls sit in it (TRAY_INSET), a tight step (TRAY_GAP) below the + -- controls sit in it, a tight step (TRAY_GAP) below the -- pill and above its foot; its height is theirs (tray_h), its corner -- the trays'. ui.presence(function(): string? @@ -2509,10 +2410,10 @@ return ui.component(function(props: Props): Node return if material.see_through() then "$zeron.composer.rest" else "$zeron.composer.shadow" end, }, - trays, + ui.column { ref = deck_size, w_full = true, shrink = 0, trays }, ui.popover(m.popover(surface)), }, - footer, + ui.column { ref = footer_size, w_full = true, shrink = 0, footer }, -- Folded, what waits on the agent: a pill floating just over the -- composer's middle, out of the layout (the conversation shows under -- it, as under "Scroll to end", which it moves aside for). @@ -2530,7 +2431,49 @@ return ui.component(function(props: Props): Node else nil, } + if props.on_sizes then + local on_sizes = props.on_sizes + -- Each its own computed, so what changes and leaves it the same (the + -- pill's width, a keystroke, a new metrics revision) wakes nothing. + local rest = ui.computed(function(): number + local _ = ui.theme.current:get() + return Layout.calculate({ + -- (Its height is the same at any width: it is never measured.) + width = pill_w:peek(), sample = nil, trailing_width = trailing_seen:get(), + control_corner = control.nest("$zeron.composer.radius", Layout.BORDER), + header_height = 0, header_gap = 0, expanded = read(props.expanded) == true, + cargo = false, asking = false, dictating = false, multiline = false, + }, false).height + end) + local ready = ui.computed(function(): boolean + return settlement:get().status == "ready" + end) + local target_h = ui.computed(function(): number + return target_geometry:get().height + end) + local last: Sizes? = nil + ui.effect(function() + local footer_h, deck_h, actual = footer_size.height, deck_size.height, outer_size.height + local context = if props.snap then props.snap:get() else 0 + if footer_h == nil or deck_h == nil or not actual or actual <= 0 then + return + end + local sizes: Sizes = { rest = rest:get() + footer_h + deck_h, target = target_h:get() + footer_h + deck_h, + presented = actual, active = transition.active:get(), ready = ready:get(), + settling = transition.settling:get(), context = context } + local was = last + if was and was.rest == sizes.rest and was.target == sizes.target and was.presented == sizes.presented + and was.active == sizes.active and was.ready == sizes.ready and was.settling == sizes.settling + and was.context == sizes.context then + return + end + last = sizes + on_sizes(sizes) + end) + end + return ui.column { + ref = outer_size, w_full = true, gap = 0, body, diff --git a/apps/zgx/ui/ds/composer_layout.luau b/apps/zgx/ui/ds/composer_layout.luau new file mode 100644 index 000000000..a6698dca0 --- /dev/null +++ b/apps/zgx/ui/ds/composer_layout.luau @@ -0,0 +1,176 @@ +-- Pure target geometry. No theme reads, signals, animation or history +-- mutations: callers resolve theme tokens and explicitly carry the text +-- expansion decision from one input change to the next. +local M = {} + +local LINE, ONE_LINE = 22, 47 +local TEXT_TOP, TEXT_BOTTOM, TEXT_MIN, TEXT_MAX = 16, 4, 76, 260 +local CONTROL, TEXT_SIDE, TEXT_OPEN_SIDE = 28, 8, 16 +local INSET_LINE = (ONE_LINE - CONTROL) / 2 +local ACTIONS, ACTIONS_OVER, HYSTERESIS = 42, 3, 32 +M.BORDER = 1 + +export type Sample = { unwrapped_width: number, wrapped_height: number, line_height: number } +export type Input = { + width: number, + sample: Sample?, + trailing_width: number, + -- Already resolved by control.nest(radius token, border), preserving + -- control.nest's special handling of fully rounded corners. + control_corner: number, + header_height: number, + header_gap: number, + expanded: boolean, + cargo: boolean, + asking: boolean, + dictating: boolean, + multiline: boolean, +} +export type Controls = { + leading: { left: number, bottom: number, height: number }, + trailing: { right: number, bottom: number, height: number }, + voice: { left: number, right: number, bottom: number }, +} +export type Geometry = { + width: number, + mode: "compact" | "expanded", + expanded: boolean, + next_text_expanded: boolean, + natural_height: number, + height: number, + header_height: number, + tray_inset: number, + -- Constraints for deriving a safe viewport from a presented frame. + line_height: number, + compact_inset: number, + compact_text: { left: number, right: number }, + text: { left: number, right: number, width: number, top: number, height: number }, + controls: Controls, +} + +function M.measurement(width: number) + return { left = TEXT_OPEN_SIDE, width = math.max(0, width - M.BORDER * 2 - TEXT_OPEN_SIDE * 2) } +end + +-- A draft whose size can't change the layout, standing in for measuring it: +-- one with enough hard lines to fill the text box to its cap at +-- `line_height` (each line at least that tall, however it wraps). It has a +-- newline, so it's open whatever its widest line, and capped, whatever it +-- wraps to. Measuring a long draft walks every line at each keystroke; this +-- looks for at most a dozen newlines. Nil: the draft must be measured. +function M.estimate(text: string, line_height: number): Sample? + local need = math.ceil((TEXT_MAX - TEXT_TOP - TEXT_BOTTOM) / math.max(1, line_height)) + local lines, at = 1, 1 + while lines < need do + local newline = string.find(text, "\n", at, true) + if newline == nil then + return nil + end + lines += 1 + at = newline + 1 + end + return { unwrapped_width = 0, wrapped_height = lines * line_height, line_height = line_height } +end + +-- Whether two targets lay the composer out alike: every field a view binds +-- or the motion reads, leaving out the widths layout applies itself (the +-- pill's, the text's) and the natural height past the cap, which nothing +-- shows. A pane resized changes only those, so it publishes no new target. +local UNBOUND = { width = true, natural_height = true } +local function same_fields(a: any, b: any): boolean + if type(a) ~= "table" or type(b) ~= "table" then + return a == b + end + for key, value in a do + if not UNBOUND[key] and not same_fields(value, b[key]) then + return false + end + end + for key in b do + if not UNBOUND[key] and a[key] == nil then + return false + end + end + return true +end +function M.same_target(a: Geometry, b: Geometry): boolean + return same_fields(a, b) +end + +-- Also used by the footer/tray to line up with the pill's controls; their +-- own layout stays outside the text geometry calculation. +local function chrome_of(control_corner: number) + local inset = control_corner - CONTROL / 2 + return { + inset = inset, + tray_inset = inset + M.BORDER, + actions_height = math.max(ACTIONS, inset + CONTROL + ACTIONS_OVER), + } +end + +function M.calculate(p: Input, previous_text_expanded: boolean): Geometry + local chrome = chrome_of(p.control_corner) + local tail = if p.trailing_width > 0 then p.trailing_width else CONTROL * 2 + TEXT_SIDE + local line_left = INSET_LINE + CONTROL + TEXT_SIDE + local line_right = TEXT_SIDE + tail + INSET_LINE + local room = p.width - M.BORDER * 2 - line_left - line_right + local forced = p.expanded or p.cargo or p.asking or p.dictating + local next_text_expanded = previous_text_expanded + local expanded = forced + if not forced and p.width > 0 then + if p.multiline then + expanded = true + elseif p.sample == nil then + expanded = previous_text_expanded + elseif previous_text_expanded then + expanded = p.sample.unwrapped_width > room - HYSTERESIS + else + expanded = p.sample.unwrapped_width > room + end + next_text_expanded = expanded + end + -- Forced modes and an unknown width don't change text hysteresis. + local head = if p.cargo or p.asking then math.max(0, p.header_height) else 0 + local natural_text = if p.sample then math.max(p.sample.wrapped_height, p.sample.line_height) else LINE + local natural_box = natural_text + TEXT_TOP + TEXT_BOTTOM + local box = math.clamp(natural_box, TEXT_MIN, TEXT_MAX) + local head_adjustment = if head > 0 then head + p.header_gap - TEXT_TOP else 0 + local height = if expanded then box + head_adjustment + chrome.actions_height + M.BORDER * 2 else ONE_LINE + M.BORDER * 2 + local natural_height = if expanded then natural_box + head_adjustment + chrome.actions_height + M.BORDER * 2 else height + local left = if expanded then TEXT_OPEN_SIDE else line_left + local right = if expanded then TEXT_OPEN_SIDE else line_right + local inset = if expanded then chrome.inset else INSET_LINE + return { + width = math.max(0, p.width), + mode = if expanded then "expanded" else "compact", + expanded = expanded, + next_text_expanded = next_text_expanded, + -- Natural is before the text box's min/max; height is the limited + -- target pill height. Neither is its animated/presented height. + natural_height = natural_height, + height = height, + header_height = head, + tray_inset = chrome.tray_inset, + line_height = if p.sample then p.sample.line_height else LINE, + compact_inset = INSET_LINE, + compact_text = { left = line_left, right = line_right }, + text = { + left = left, + right = right, + width = math.max(0, p.width - M.BORDER * 2 - left - right), + top = if expanded then (if head > 0 then head + p.header_gap else TEXT_TOP) else (ONE_LINE - LINE) / 2, + height = if expanded then box - TEXT_TOP - TEXT_BOTTOM else LINE, + }, + controls = { + leading = { left = inset, bottom = inset, height = CONTROL }, + trailing = { right = inset, bottom = inset - 2, height = 32 }, + voice = { + left = inset + CONTROL + TEXT_SIDE, + right = inset + CONTROL * 2 + TEXT_SIDE * 2, + bottom = inset, + }, + }, + } +end + +return M diff --git a/apps/zgx/ui/ds/composer_metrics.luau b/apps/zgx/ui/ds/composer_metrics.luau new file mode 100644 index 000000000..267c80c96 --- /dev/null +++ b/apps/zgx/ui/ds/composer_metrics.luau @@ -0,0 +1,190 @@ +-- The editor owns shaping, spans and IME. This adapter keeps a complete +-- last sample during initialization and tags every publication with the +-- request revision, independent of the editor's animated viewport. +local M = {} + +export type Sample = { + unwrapped_width: number, + wrapped_height: number, + line_height: number, + width: number, + revision: number, +} +type Request = { + width: number, editor: Element?, source: Sample?, estimate: Size?, revision: number, + text: string, theme: string, mount: number, +} +export type Result = { + -- A complete last sample, never one axis from a different request. + sample: Sample?, + status: "pending" | "stale" | "ready", + revision: number, + width: number, +} +-- What layout reads of a sample: its size alone, so a new revision of the +-- same size (an edit that wraps alike, a width that wraps alike) wakes no +-- layout. +export type Size = { unwrapped_width: number, wrapped_height: number, line_height: number } +export type Props = { + value: State, + -- Content width at the expanded destination, not the animated viewport; + -- with `peek`, read without following it. + width: (peek: boolean?) -> number, + editor: Ref, + keep: string?, + -- A size standing in for the editor's measure where the caller knows + -- the exact one can't change its layout (a long draft past the cap), + -- with the line height last measured; nil to measure. Measuring walks + -- every line of the draft, so a long one paid that at every keystroke. + estimate: ((text: string, line_height: number) -> Size?)?, +} + +function M.use(props: Props) + -- Keep measurements under the editor-metrics provider namespace. + local measured: State = if props.keep + then ui.state(`composer:{props.keep}:editor_text_metrics`, nil :: Sample?) + else ui.use_state(nil :: Sample?) + local function size_of(s: Sample?): Size? + return if s then { unwrapped_width = s.unwrapped_width, wrapped_height = s.wrapped_height, line_height = s.line_height } else nil + end + local size: State = if props.keep + then ui.state(`composer:{props.keep}:editor_text_size`, size_of(measured:peek())) + else ui.use_state(size_of(measured:peek())) + local revision = if measured:peek() then (measured:peek() :: Sample).revision else 0 + -- Element userdata wrappers are recreated on reads. Follow the ref's + -- mount generation to distinguish replacement from a width-only query. + local mount_revision = 0 + local mounted = ui.computed(function() + local editor = props.editor:get() + mount_revision += 1 + return { editor = editor, revision = mount_revision } + end) + -- The editor, theme and line height of the last exact measure: an + -- estimate stands in only while those hold (a theme's type changes the + -- line height it counts by). + local exact: { mount: number, theme: string, line_height: number }? = nil + -- Whether a new width can change the measure: only while the widest + -- line doesn't fit (it wraps, or would, narrower). A draft that fits, an + -- empty one, one past the cap (estimated), measures the same at any + -- width it fits, so a pane resized asks nothing of it at each frame. + local follows = ui.computed(function(): boolean + local s = size:get() + return s == nil or s.unwrapped_width >= math.max(0, props.width()) - 1 + end) + local last: Request? = nil + local request = ui.computed(function(): Request + -- Track edits even when the measured dimensions stay equal. + local text = props.value:get() + local width = math.max(0, if follows:get() then props.width() else props.width(true)) + local theme = ui.theme.current:get() + local mount = mounted:get() + local el = mount.editor + local source, estimate = nil, nil + if el and width > 0 then + if props.estimate and exact and exact.mount == mount.revision and exact.theme == theme then + estimate = props.estimate(text, exact.line_height) + end + -- Reading follows the editor's settled content/IME/style revision. + if estimate == nil then + source = el:text_metrics(width) + end + end + -- An estimate as the last one, for the same editor, theme and width: + -- the same request, which notifies nobody (a keystroke past the cap + -- publishes nothing). + local was = last + if estimate and was and was.estimate and was.editor == el and was.mount == mount.revision + and was.theme == theme and was.width == width + and was.estimate.wrapped_height == estimate.wrapped_height + and was.estimate.line_height == estimate.line_height then + return was + end + revision += 1 + local now: Request = { width = width, editor = el, source = source, estimate = estimate, revision = revision, text = text, theme = theme, mount = mount.revision } + last = now + return now + end) + local settled: { mount: number, text: string, theme: string, revision: number, width: number }? = nil + local function publish(wanted: Request, source: Size, width: number) + ui.batch(function() + -- (An equal size notifies nobody: layout wakes only for a new one.) + size:set { + unwrapped_width = source.unwrapped_width, + wrapped_height = source.wrapped_height, + line_height = source.line_height, + } + measured:set { + unwrapped_width = source.unwrapped_width, + wrapped_height = source.wrapped_height, + line_height = source.line_height, + width = width, + revision = wanted.revision, + } + end) + end + local function publish_exact(wanted: Request, source: Sample) + settled = { mount = wanted.mount, text = wanted.text, theme = wanted.theme, + revision = source.revision, width = wanted.width } + exact = { mount = wanted.mount, theme = wanted.theme, line_height = source.line_height } + publish(wanted, source, source.width) + end + local alive = true + local cancel: (() -> ())? = nil + ui.effect(function() + local wanted = request:get() + if cancel then + cancel() + cancel = nil + end + local editor = wanted.editor + if wanted.estimate and editor then + publish(wanted, wanted.estimate, wanted.width) + return + end + if wanted.source == nil or editor == nil then + return + end + -- A width-only query already measures settled editor content at that + -- exact width. Publish it as one sample now, avoiding a stale/ready + -- round-trip for every frame of a page resize. Content, IME, style, + -- editor replacement and initial requests still need acknowledgement. + if settled and settled.width ~= wanted.width and settled.mount == wanted.mount + and settled.text == wanted.text and settled.theme == wanted.theme + and settled.revision == wanted.source.revision then + publish_exact(wanted, wanted.source) + return + end + -- Defer publication until bindings and editor layout have consumed + -- the request. A replacement effect cancels this acknowledgement. + cancel = ui.after(0, function() + if not alive or request:peek().revision ~= wanted.revision then + return + end + local source = editor:text_metrics(wanted.width) + if source == nil or source.revision ~= wanted.source.revision then + return + end + publish_exact(wanted, source) + end) + end) + ui.on_cleanup(function() + alive = false + if cancel then + cancel() + end + end) + local result = ui.computed(function(): Result + local want, sample = request:get(), measured:get() + return { + sample = sample, + status = if sample == nil then "pending" elseif sample.revision == want.revision then "ready" else "stale", + revision = want.revision, + width = want.width, + } + end) + -- Geometry follows measured dimensions; request/readiness changes have + -- their own subscribers and do not invalidate the last complete sample. + return { result = result, sample = size :: ReadOnlyState } +end + +return M diff --git a/apps/zgx/ui/ds/composer_motion.luau b/apps/zgx/ui/ds/composer_motion.luau new file mode 100644 index 000000000..35a964d8f --- /dev/null +++ b/apps/zgx/ui/ds/composer_motion.luau @@ -0,0 +1,190 @@ +-- One progress and one complete geometry per frame. The editor stays +-- compact until a whole line fits above the controls, then takes its final +-- expanded width in one step. It never wraps through interpolated insets. +local Layout = require("@ds/composer_layout") +local M = {} + +local function mix(a: number, b: number, p: number): number + return a + (b - a) * p +end + +function M.frame(from: Layout.Geometry, to: Layout.Geometry, progress: number): Layout.Geometry + local p = math.clamp(progress, 0, 1) + if p == 1 then + return to + end + local g = table.clone(to) + g.height = mix(from.height, to.height, p) + g.header_height = mix(from.header_height, to.header_height, p) + g.controls = { + leading = { + left = mix(from.controls.leading.left, to.controls.leading.left, p), + bottom = mix(from.controls.leading.bottom, to.controls.leading.bottom, p), + height = to.controls.leading.height, + }, + trailing = { + right = mix(from.controls.trailing.right, to.controls.trailing.right, p), + bottom = mix(from.controls.trailing.bottom, to.controls.trailing.bottom, p), + height = to.controls.trailing.height, + }, + voice = { + left = mix(from.controls.voice.left, to.controls.voice.left, p), + right = mix(from.controls.voice.right, to.controls.voice.right, p), + bottom = mix(from.controls.voice.bottom, to.controls.voice.bottom, p), + }, + } + -- Animate the vertical envelope continuously, deriving the viewport + -- from the current container and reserved space. Switching width must + -- not also jump the text vertically or leave it over the buttons. + local top = mix(from.text.top, to.text.top, p) + local from_bottom = from.height - Layout.BORDER * 2 - from.text.top - from.text.height + local to_bottom = to.height - Layout.BORDER * 2 - to.text.top - to.text.height + local bottom = mix(from_bottom, to_bottom, p) + local available = math.max(0, g.height - Layout.BORDER * 2 - top - bottom) + local controls = math.max(g.controls.leading.bottom + g.controls.leading.height, + g.controls.trailing.bottom + g.controls.trailing.height) + local expand = to.expanded and bottom >= controls - 0.001 + and available >= math.min(to.line_height, to.text.height) - 0.001 + local left = if expand then to.text.left else to.compact_text.left + local right = if expand then to.text.right else to.compact_text.right + if not expand then + -- Keep compact text and controls beside each other, including themes + -- with deeply inset expanded controls. Their vertical anchors move. + g.controls.leading.left = to.compact_inset + g.controls.trailing.right = to.compact_inset + end + g.text = { + left = left, right = right, + width = math.max(0, to.width - Layout.BORDER * 2 - left - right), + top = top, height = available, + } + g.expanded = expand + g.mode = if expand then "expanded" else "compact" + return g +end + +-- Changes in natural content height at the viewport cap, or in hysteresis +-- metadata, don't change the destination and must not restart a run. +local function same_shape(a: Layout.Geometry, b: Layout.Geometry): boolean + if a.height ~= b.height or a.mode ~= b.mode or a.expanded ~= b.expanded + or a.header_height ~= b.header_height then + return false + end + for name, value in a.text :: { [string]: number } do + if name ~= "width" and (b.text :: any)[name] ~= value then + return false + end + end + for key, anchors in a.controls :: { [string]: { [string]: number } } do + for name, value in anchors do + if (b.controls :: any)[key][name] ~= value then + return false + end + end + end + return true +end + +function M.same_destination(a: Layout.Geometry, b: Layout.Geometry): boolean + return a.width == b.width and a.text.width == b.text.width and same_shape(a, b) +end + +function M.use(target: ReadOnlyState, snap: State?, settlement: ReadOnlyState<{ revision: number, status: string }>?) + local motion = require("@self/motion") + local initial = target:peek() + local origin = ui.use_state(initial) + local destination = ui.use_state(initial) + local progress = ui.use_state(1) + local active = ui.use_state(false) + local frame = ui.computed(function(): Layout.Geometry + return M.frame(origin:get(), destination:get(), progress:get()) + end) + local run: any = nil + local alive, generation = true, 0 + local snap_seen = if snap then snap:peek() else nil + local settling = ui.use_state(false) + local cancel_ack: (() -> ())? = nil + local function cancel() + generation += 1 + if run then + run:cancel() + run = nil + end + active:set(false) + end + local function settle(next: Layout.Geometry) + cancel() + ui.batch(function() + origin:set(next) + destination:set(next) + progress:set(1) + end) + end + ui.effect(function() + local next = target:get() + local reduced = motion.reduced() + if cancel_ack then cancel_ack(); cancel_ack = nil end + if snap then + local n = snap:get() + if n ~= snap_seen then + snap_seen = n + settling:set(true) + end + end + if reduced then + settle(next) + settling:set(false) + return + end + if settling:peek() then + local measured = if settlement then settlement:get() else { revision = 0, status = "ready" } + settle(next) + if measured.status == "ready" then + local context, revision = snap_seen, measured.revision + cancel_ack = ui.after(0, function() + local current = if settlement then settlement:peek() else measured + if alive and context == snap_seen and current.status == "ready" + and current.revision == revision and M.same_destination(target:peek(), next) then + settling:set(false) + end + end) + end + return + end + if M.same_destination(destination:peek(), next) then + destination:set(next) + return + end + local shown = frame:peek() + -- Layout already applies width; an otherwise unchanged frame needs no run. + if same_shape(shown, next) then + settle(next) + return + end + cancel() + local own = generation + ui.batch(function() + origin:set(shown) + destination:set(next) + progress:set(0) + active:set(true) + end) + run = anime.animate(progress, { + value = 1, duration = 220, ease = "out(3)", + onComplete = function() + if alive and generation == own then + run = nil + active:set(false) + end + end, + }) + end) + ui.on_cleanup(function() + alive = false + if cancel_ack then cancel_ack() end + cancel() + end) + return { frame = frame, origin = origin, destination = destination, progress = progress, active = active, settling = settling } +end + +return M diff --git a/apps/zgx/ui/ds/dialog.luau b/apps/zgx/ui/ds/dialog.luau index b07c90a88..30e2b1b66 100644 --- a/apps/zgx/ui/ds/dialog.luau +++ b/apps/zgx/ui/ds/dialog.luau @@ -40,7 +40,9 @@ local M = {} -- `keep_open`: the confirm leaves it open (the caller closes it once its -- work is done); `busy`, while true, the confirm spins in its label's -- place and takes no click (an install on its way). -export type Action = { label: string | Message | () -> string, on_click: (() -> ())?, keep_open: boolean?, busy: (() -> boolean)? } +-- `disabled`, while true, the confirm takes no click and no Enter (nothing +-- typed yet). +export type Action = { label: string | Message | () -> string, on_click: (() -> ())?, keep_open: boolean?, busy: (() -> boolean)?, disabled: (() -> boolean)? } export type DialogProps = { open: State, title: string | Message | () -> string, @@ -57,6 +59,10 @@ export type DialogProps = { confirm_text: string?, -- Whether a click outside closes it (not for one that must be answered). dismissable: boolean?, + -- While true, nothing closes it — Cancel, Escape, a click outside — as + -- what the confirm started can't be taken back (a key being checked + -- and kept). + hold: (() -> boolean)?, -- What stands in it built as it opens, after its children: choices -- made from the data as it is then (its focus starts on their first). build: (() -> Node)?, @@ -71,7 +77,7 @@ local OUT = { duration = 130, ease = "in(2)" } -- The stage: the modal, kept up while the panel leaves. `phase` runs from 0 -- (gone) to 1 (here) and the caller's panel follows it; `panel` builds it, -- and `w`, `h` and `placement` place it; `ref` is the bare panel's. -local function stage(props: { open: State, label: Label, dismissable: boolean, w: any, h: any, placement: any, ref: any?, panel: (phase: State) -> Node }): Node +local function stage(props: { open: State, label: Label, dismissable: boolean, hold: (() -> boolean)?, w: any, h: any, placement: any, ref: any?, panel: (phase: State) -> Node }): Node local open = props.open -- (From where it stands: open across a hot reload, it doesn't arrive -- again.) @@ -106,6 +112,11 @@ local function stage(props: { open: State, label: Label, dismissable: b return shown:get() end, on_close = function() + -- (Held while its work is under way: Escape and a click outside + -- wait for it.) + if props.hold and props.hold() then + return + end open:set(false) end, label = props.label, @@ -150,6 +161,10 @@ local DialogBody = ui.component(function(args: { props: DialogProps, close: () - local danger = props.tone == "danger" local typed = ui.use_state("") local function ready(): boolean + local confirm = props.confirm + if confirm and confirm.disabled and confirm.disabled() then + return false + end return props.confirm_text == nil or typed:get() == props.confirm_text end local function go() @@ -258,7 +273,14 @@ local DialogBody = ui.component(function(args: { props: DialogProps, close: () - } else nil, if props.cancel ~= false - then Button { (props.cancel or locale.t("common.cancel")) :: any, tone = "secondary", on_click = close } + then Button { + (props.cancel or locale.t("common.cancel")) :: any, + tone = "secondary", + disabled = function(): boolean + return props.hold ~= nil and props.hold() + end, + on_click = close, + } else nil, if props.confirm then Button { @@ -293,6 +315,7 @@ M.Dialog = ui.component(function(props: DialogProps): Node open = open, label = props.title, dismissable = props.dismissable ~= false, + hold = props.hold, w = `$zeron.dialog.{props.size or "sm"}`, panel = function(phase: State): Node return DialogBody { props = props, close = close, phase = phase } diff --git a/apps/zgx/ui/ds/dropdown.luau b/apps/zgx/ui/ds/dropdown.luau index 13f798121..61230b3cb 100644 --- a/apps/zgx/ui/ds/dropdown.luau +++ b/apps/zgx/ui/ds/dropdown.luau @@ -12,6 +12,7 @@ -- icon = "folder", placeholder = "No project", search = "Search projects…" }` local Icon = require("@self/icon") +local motion = require("@self/motion") local Mark = require("@self/mark") local AgentMark = require("@self/agent_mark") local RollText = require("@self/roll_text") @@ -51,6 +52,14 @@ export type Item = { -- A picture chosen for it (a project's emoji), on its hue's wash. emoji: string?, description: string?, + -- Quiet words beside its name, in the name's size and on its line (a + -- model's provider, telling it from a namesake), searched as its name + -- is. The name gives way first: it fades, the hint stays whole. With + -- `hint_when_found`, they show only while a search found the row by + -- them (its name alone doesn't hold what was typed). A row whose hint + -- changes is built again (its key holds them). + hint: string?, + hint_when_found: boolean?, -- Its label is an email address: drawn as ds.PrivateText draws one, its -- tile no letter of it (`seed`'s avatar). private: boolean?, @@ -386,12 +395,144 @@ return ui.component(function(props: Props): Node return control.text(props.placeholder) or locale.s("ds.dropdown.placeholder") end + -- Whether a search finds an item: by its name, else by its hint from the + -- start of one of its words ("code" finds OpenCode's, "ai" not OpenAI's), + -- or by its name and hint read together ("gpt-5.5 codex"). + local function word_start(text: string, q: string): boolean + local low = string.lower(text) + local at = string.find(low, q, 1, true) + while at do + local before = if at > 1 then string.sub(text, at - 1, at - 1) else " " + -- A word starts after a space or a mark, or at a capital inside + -- one (Open|Code). + if not string.match(before, "%w") or (string.match(before, "%l") and string.match(string.sub(text, at, at), "%u")) then + return true + end + at = string.find(low, q, at + 1, true) + end + return false + end + local function by_name(item: Item, q: string): boolean + return q == "" or string.find(string.lower(item.label), q, 1, true) ~= nil + end + local function found(item: Item, q: string): boolean + if by_name(item, q) then + return true + end + local hint = item.hint + if not hint then + return false + end + if word_start(hint, q) then + return true + end + -- Read together, the search runs from the name on into the hint, + -- reaching it at a word's start (its first). + local label = string.lower(item.label) + local together = label .. " " .. string.lower(hint) + local from, to = string.find(together, q, 1, true) + while from do + if from <= #label and (to :: number) > #label + 1 then + return true + end + from, to = string.find(together, q, from + 1, true) + end + return false + end + -- Whether an item's hint shows now (`hint_when_found`: while a search + -- found it by its hint, not its name). + local function hint_shown(now: Item): boolean + return now.hint ~= nil and (not now.hint_when_found or not by_name(now, string.lower(query:get()))) + end + -- A name with its hint beside it, read as one line: where it runs past + -- the row, its right edge fades (as FadeText's does), and while the row + -- is highlighted (`lit`: under the pointer, or the keys') the line glides + -- left until its end shows, rests, and glides back, over and over. With + -- motion reduced it stays put, faded. + local NAMED_FADE = 24 + local function named(item: Item, lit: () -> boolean): Node + local clip, line = ui.ref(), ui.ref() + local el: any = nil + local run: any = nil + -- How far the line runs past its row. + local function over(): number + return math.max(0, (line.width or 0) - (clip.width or 0)) + end + local function still() + if run then + run:cancel() + run = nil + end + if el then + anime.utils.cleanInlineStyles(el, "x") + end + end + ui.effect(function() + local on = lit() + local past = over() + if not on or past <= 0.5 or motion.reduced() or not el then + still() + return + end + if run then + return + end + local travel = past + NAMED_FADE + run = anime.animate(el, { + x = { 0, -travel }, + -- (About 40 points a second: read as it passes, not a jump.) + duration = math.max(900, travel * 25), + delay = 700, + loopDelay = 1000, + loop = true, + alternate = true, + ease = "inOut(2)", + }) + ui.on_cleanup(still) + end) + return ui.row { + ref = clip, + grow = 1, + min_w = 0, + overflow = "hidden", + items = "center", + fade_x = function() + local past = (line.width or 0) > (clip.width or 0) + 0.5 + -- (Gliding, its start runs off the left too.) + local moving = past and lit() and not motion.reduced() + return { if moving then NAMED_FADE else 0, if past then NAMED_FADE else 0 } + end, + ui.row { + ref = line, + shrink = 0, + gap = "$space.2", + items = "center", + on_mount = function(node: any) + el = node + end, + ui.text { + item.label, + shrink = 0, + text_size = "$font.size.md", + color = "$text.primary", + }, + ui.show(function(): boolean + return hint_shown(item) + end, ui.text { + item.hint :: string, + shrink = 0, + text_size = "$font.size.md", + color = "$text.tertiary", + }), + }, + } + end local shown = ui.computed(function(): { Item } local q = string.lower(query:get()) local out: { Item } = {} local keep = props.filter for _, item in items() do - if (keep == nil or keep(item)) and (q == "" or string.find(string.lower(item.label), q, 1, true)) then + if (keep == nil or keep(item)) and found(item, q) then table.insert(out, item) end end @@ -1091,6 +1232,13 @@ return ui.component(function(props: Props): Node ui.each(shown, function(item: Item) local r = row({ role = "option", + -- A row with a hint is heard as it reads: its name, + -- then its hint while that shows. + label = if item.hint + then function(): string + return if hint_shown(item) then `{item.label} {item.hint}` else item.label + end + else nil, -- What assistive technology hears the selected -- state as (the check it no longer shows). selected = function(): boolean @@ -1162,6 +1310,9 @@ return ui.component(function(props: Props): Node wrap = true, }, } + elseif item.hint then named(item, function(): boolean + return hi:get() == item.value + end) else text(item.label), if item.tag then ui.text { @@ -1207,8 +1358,12 @@ return ui.component(function(props: Props): Node r, } end, { + -- (A row whose hint changes, or comes or goes, is built + -- again: its hint is part of what it is.) key = function(item: Item) - return item.value + return if item.hint + then `{item.value}\0{item.hint}\0{if item.hint_when_found then "found" else "always"}` + else item.value end, w_full = true, }) @@ -1386,7 +1541,18 @@ return ui.component(function(props: Props): Node table.insert(rows, gated(list)) end if props.actions and #props.actions > 0 then - table.insert(rows, rule()) + local all = props.actions + -- (The rule and the actions' inset only while an action + -- shows: a menu whose every action is hidden ends at its + -- last item, with no line or gap under it.) + local function any_shown(): boolean + for _, action in all do + if not action.shown or action.shown() then + return true + end + end + return false + end local acts: { Node } = {} for n, action in props.actions do local key = `action:{n}` @@ -1408,7 +1574,18 @@ return ui.component(function(props: Props): Node }, false) table.insert(acts, if action.shown then ui.show(action.shown, made) else made) end - table.insert(rows, ui.column { w_full = true, p = "$space.1", gap = "$zeron.list.gap", table.unpack(acts) }) + table.insert( + rows, + ui.show( + any_shown, + ui.column { + w_full = true, + gap = 0, + rule(), + ui.column { w_full = true, p = "$space.1", gap = "$zeron.list.gap", table.unpack(acts) }, + } + ) + ) end if bottom_up then place_top() diff --git a/apps/zgx/ui/ds/init.luau b/apps/zgx/ui/ds/init.luau index 55b140a14..0722a344a 100644 --- a/apps/zgx/ui/ds/init.luau +++ b/apps/zgx/ui/ds/init.luau @@ -26,6 +26,7 @@ export type SidebarProject = sidebar.Project export type StatusKind = status.Kind export type Harness = model_picker.Harness export type Model = model_picker.Model +export type ComposerSizes = composer.Sizes export type ComposerDevice = composer.Device export type ComposerUsage = composer.Usage export type ComposerFixed = composer.Fixed diff --git a/apps/zgx/ui/ds/locale_en.luau b/apps/zgx/ui/ds/locale_en.luau index 56f010956..797581c81 100644 --- a/apps/zgx/ui/ds/locale_en.luau +++ b/apps/zgx/ui/ds/locale_en.luau @@ -690,6 +690,8 @@ return { ["ds.model_picker.default"] = "Default", ["ds.model_picker.reasoning"] = "REASONING", ["ds.model_picker.account"] = "Account", + ["ds.model_picker.account_of"] = "{name} account", + ["ds.model_picker.no_account"] = "None", ["ds.model_picker.model"] = "Model", ["ds.model_picker.search_starred"] = "Search starred models…", ["ds.model_picker.search_agent"] = "Search {agent} models…", @@ -702,6 +704,7 @@ return { ["ds.model_picker.not_found_hint"] = "Nothing in {where} matches “{q}”", ["ds.model_picker.where_starred"] = "starred models", ["ds.model_picker.where_models"] = "models", + ["ds.model_picker.add_key"] = "Add {name} API key", ["ds.effort_slider.reasoning"] = "Reasoning", ["ds.provider_card.resets_at"] = "resets {when}", ["ds.provider_card.usage"] = "{label} usage", @@ -783,6 +786,22 @@ return { ["ds.provider_card.key_name"] = "{var}", ["ds.provider_card.get_key"] = "Get a key", ["ds.provider_card.save_key"] = "Save", + ["ds.provider_card.add_named_account"] = "Add {name} account", + ["ds.provider_card.add_api_key"] = "Add API key", + ["ds.provider_card.key_offline"] = "Zeron's engine isn't answering — try again in a moment.", + ["ds.provider_card.key_remote"] = "API keys are added on the computer that runs {name}.", + ["ds.provider_card.key_failed"] = "The key couldn't be added — try again.", + ["ds.provider_card.key_title"] = "Add API key", + ["ds.provider_card.key_provider"] = "Provider", + ["ds.provider_card.key_body"] = "{agent} uses this key for {name} models.", + ["ds.provider_card.key_field"] = "API key", + ["ds.provider_card.key_kept"] = "Stored on this Mac in {agent}'s settings.", + ["ds.provider_card.key_name_label"] = "Name", + ["ds.provider_card.key_name_placeholder"] = "Work, Personal…", + ["ds.provider_card.rename"] = "Rename", + ["ds.provider_card.rename_title"] = "Rename API key", + ["ds.provider_card.rename_hint"] = "Leave it blank for its default name.", + ["ds.provider_card.key_name_optional"] = "Name (optional)", ["ds.command_palette.scope.all"] = "All", ["ds.command_palette.scope.sessions"] = "Sessions", ["ds.command_palette.scope.commands"] = "Commands", diff --git a/apps/zgx/ui/ds/mark.luau b/apps/zgx/ui/ds/mark.luau index 7826ff160..260e1216a 100644 --- a/apps/zgx/ui/ds/mark.luau +++ b/apps/zgx/ui/ds/mark.luau @@ -18,6 +18,14 @@ export type Name = | "pi" | "hermes" | "muse" + -- Model providers (an agent's accounts per provider, their API keys): + -- one set, one ink each. + | "provider-anthropic" + | "provider-openai" + | "provider-openrouter" + | "provider-gemini" + | "provider-xai" + | "provider-deepseek" local FILES: { [Name]: string } = { claude = "claude-mark", @@ -30,11 +38,29 @@ local FILES: { [Name]: string } = { pi = "pi-mark", hermes = "hermes-mark", muse = "muse-mark", + ["provider-anthropic"] = "provider-anthropic", + ["provider-openai"] = "provider-openai", + ["provider-openrouter"] = "provider-openrouter", + ["provider-gemini"] = "provider-gemini", + ["provider-xai"] = "provider-xai", + ["provider-deepseek"] = "provider-deepseek", } -- Marks drawn in one ink (black, for the white tile): bare, they take the -- colour of the text around them instead, or they vanish on dark. -local MONO: { [Name]: boolean } = { openai = true, grok = true, cursor = true, devin = true, hermes = true } +local MONO: { [Name]: boolean } = { + openai = true, + grok = true, + cursor = true, + devin = true, + hermes = true, + ["provider-anthropic"] = true, + ["provider-openai"] = true, + ["provider-openrouter"] = true, + ["provider-gemini"] = true, + ["provider-xai"] = true, + ["provider-deepseek"] = true, +} local RegistryMark = require("@self/registry_mark") diff --git a/apps/zgx/ui/ds/model_picker.luau b/apps/zgx/ui/ds/model_picker.luau index e836887d5..fee67e5d1 100644 --- a/apps/zgx/ui/ds/model_picker.luau +++ b/apps/zgx/ui/ds/model_picker.luau @@ -37,13 +37,18 @@ export type Choice = { id: string, label: string } -- An option of a model (Devin Fusion's lead and sidekick): its choices and -- the one it starts on (by id). export type Option = { id: string, label: string, default: string, choices: { Choice } } +-- Where a model is served from, for an agent reaching models through +-- several providers (Pi signed in to Codex and OpenCode): its id and name. +export type Provider = { id: string, name: string } -- A model: its agent, its reasoning levels (low to high) and the one it --- starts on, whether it offers Fast mode, its other options, and whether --- it's its agent's default (what a chat that names no model runs). +-- starts on, whether it offers Fast mode, its other options, whether it's +-- its agent's default (what a chat that names no model runs), and its +-- provider. export type Model = { value: string, label: string, harness: string, + provider: Provider?, efforts: { EffortSlider.Level }?, effort: string?, fast: boolean?, @@ -62,11 +67,20 @@ export type Account = { active: boolean, can_switch: boolean, } +-- The accounts a model runs on, where its agent keeps a login per model +-- provider (Pi, OpenCode, Hermes): who they're with ("ChatGPT"), and, where +-- Zeron can sign in to it, what adds one and what that does. +export type AccountGroup = { name: string, add: string?, on_add: (() -> ())? } export type Props = { -- The accounts of a model's agent (nil or none: no row, no ring), followed - -- as they change. `on_account` puts one in use; `on_accounts_open` asks - -- after them again as the panel opens. - accounts: ((harness: string, model: string) -> { Account }?)?, + -- as they change; for an agent with a login per model provider, its + -- provider's alone (`provider`, the model's). `on_account` puts one in + -- use; `on_accounts_open` asks after them again as the panel opens. + accounts: ((harness: string, model: string, provider: string?) -> { Account }?)?, + -- The model's provider's accounts, named (nil: the agent keeps one + -- login): the row is " account", and offers to add one, even with + -- none yet. + account_group: ((harness: string, provider: string?) -> AccountGroup?)?, on_account: ((harness: string, id: string) -> ())?, on_accounts_open: (() -> ())?, model: State, @@ -295,11 +309,15 @@ return ui.component(function(props: Props): Node props.effort:set(own_effort(m)) end) - -- The models as the dropdown's items, each in its agent's mark. + -- The models as the dropdown's items, each in its agent's mark. A model + -- with a provider (Pi's, OpenCode's, Hermes's: agents that reach models + -- through providers) has its name as the row's hint, always: which GPT-6 + -- Luna is which, and where one comes from even when it's the only one. local items = ui.computed(function(): { Dropdown.Item } local out: { Dropdown.Item } = {} local by_agent = agents:get() - for _, m in read(props.models) :: { Model } do + local models = read(props.models) :: { Model } + for _, m in models do local agent = by_agent[m.harness] table.insert(out, { value = m.value, @@ -307,6 +325,9 @@ return ui.component(function(props: Props): Node mark = if agent then agent.mark else nil, svg = if agent then agent.icon else nil, svg_seed = m.harness, + hint = if m.provider then m.provider.name else nil, + -- (Always: where a model comes from is part of which it is.) + hint_when_found = nil, }) end return out @@ -499,10 +520,32 @@ return ui.component(function(props: Props): Node } end - -- The chosen model's agent's accounts, and the one in use. + -- The chosen model's agent's accounts (its provider's, where the agent + -- keeps a login per provider), and the one in use. + local function provider_of(m: Model?): string? + return if m and m.provider then m.provider.id else nil + end local function accounts(): { Account } local m = current() - return (if m and props.accounts then props.accounts(m.harness, m.value) else nil) or {} + return (if m and props.accounts then props.accounts(m.harness, m.value, provider_of(m)) else nil) or {} + end + -- Those accounts' provider, named, and how to add one (nil: the agent + -- keeps one login). + local function group(): AccountGroup? + local m = current() + return if m and props.account_group then props.account_group(m.harness, provider_of(m)) else nil + end + -- Whether the row shows: an account to show, or one the provider can add. + local function has_account_row(): boolean + if #accounts() > 0 then + return true + end + local g = group() + return g ~= nil and g.add ~= nil + end + local function account_label(): string + local g = group() + return if g then locale.s("ds.model_picker.account_of", { name = g.name }) else locale.s("ds.model_picker.account") end local function account_by_id(id: string?): Account? for _, a in accounts() do @@ -555,11 +598,32 @@ return ui.component(function(props: Props): Node end return out end, - label = locale.t("ds.model_picker.account"), + label = account_label, search = false, width = 300, placement = { side = "right", align = "start", offset = 7 }, on_open = sync, + -- (Another of the model's provider's accounts, where Zeron can + -- sign in to it: "Add ChatGPT account".) + actions = { + { + label = function(): string + local g = group() + return if g and g.add then g.add else "" + end, + icon = "plus", + shown = function(): boolean + local g = group() + return g ~= nil and g.add ~= nil and g.on_add ~= nil + end, + on_click = function() + local g = group() + if g and g.on_add then + g.on_add() + end + end, + }, + }, trailing_item = function(item: Dropdown.Item): Node? return ui.show(function(): boolean local a = account_by_id(item.value) @@ -584,12 +648,16 @@ return ui.component(function(props: Props): Node trigger = function(menu: Dropdown.Menu): Node local row: ContainerProps = { id = "model-picker-account", - label = locale.t("ds.model_picker.account"), + label = account_label, bg = function() return if menu.open:get() then "$hover" else "#00000000" end, on_click = menu.toggle, - ui.text { locale.t("ds.model_picker.account"), text_size = "$font.size.md", color = "$text.primary", grow = 1 }, + ui.text { account_label, text_size = "$font.size.md", color = "$text.primary", grow = 1, min_w = 0, truncate = true }, + -- (None in use: none signed in to the model's provider.) + ui.show(function(): boolean + return in_use() == nil + end, ui.text { locale.t("ds.model_picker.no_account"), shrink = 0, text_size = "$font.size.md", color = "$text.tertiary" }), PrivateText { function(): string local a = in_use() @@ -702,9 +770,7 @@ return ui.component(function(props: Props): Node return out end) local foot: { Node } = { - ui.show(function(): boolean - return #accounts() > 0 - end, account_row()), + ui.show(has_account_row, account_row()), ui.each(owned, function(it: Owned): Node return option_row(it.option) end, { @@ -877,7 +943,7 @@ return ui.component(function(props: Props): Node extra_when = function(): boolean local m = current() return m ~= nil - and ((m.efforts ~= nil and #m.efforts > 0) or (m.fast == true and fast ~= nil) or #ordered(m) > 0 or #accounts() > 0) + and ((m.efforts ~= nil and #m.efforts > 0) or (m.fast == true and fast ~= nil) or #ordered(m) > 0 or has_account_row()) end, placement = props.placement, bottom_up = bottom_up, diff --git a/apps/zgx/ui/ds/motion.luau b/apps/zgx/ui/ds/motion.luau index 81cfae5e6..50cf6142a 100644 --- a/apps/zgx/ui/ds/motion.luau +++ b/apps/zgx/ui/ds/motion.luau @@ -39,17 +39,51 @@ function M.ms(ms: number): number return if M.reduced_now() then 0 else ms end +-- Where a tween or spring of `target` ends, at once: `target` itself, or, +-- for a boolean with `from` and `to` (a switch's knob: off at `from`, on at +-- `to`), the end it says. As `target` itself, a switch's knob stood at `x = +-- true`, the left, whatever it said, while its tweened track said on. +local function landed(target: any, opts: { from: any?, to: any? }): any + if opts.from == nil or opts.to == nil then + return target + end + -- (A state or a computed, tracked; a function's answer.) + local function now(): any + if type(target) == "function" then + return target() + elseif type(target) == "userdata" or type(target) == "table" then + local ok, getter = pcall(function() + return (target :: any).get + end) + if ok and type(getter) == "function" then + return (target :: any):get() + end + end + return target + end + if type(target) == "boolean" then + return if target then opts.to else opts.from + end + return ui.computed(function(): any + local v = now() + if type(v) == "boolean" then + return if v then opts.to else opts.from + end + return v + end) +end + -- A value that moves to where `target` goes (`ui.tween`), or, with motion --- reduced, `target` itself, so it lands at once: for a prop. Decided as +-- reduced, where it ends (`landed`), there at once: for a prop. Decided as -- the part is built (a tween's options are fixed when it's made), so the -- setting changed reaches what's built after it. function M.tween(target: any, opts: TweenOptions): any - return if M.reduced_now() then target else ui.tween(target, opts) + return if M.reduced_now() then landed(target, opts :: any) else ui.tween(target, opts) end -- The same for `ui.spring`. function M.spring(target: any, opts: SpringOptions): any - return if M.reduced_now() then target else ui.spring(target, opts) + return if M.reduced_now() then landed(target, opts :: any) else ui.spring(target, opts) end -- What of an animation is movement (it travels or grows), as opposed to a diff --git a/apps/zgx/ui/ds/provider_card.luau b/apps/zgx/ui/ds/provider_card.luau index 78667da80..959c15355 100644 --- a/apps/zgx/ui/ds/provider_card.luau +++ b/apps/zgx/ui/ds/provider_card.luau @@ -35,6 +35,7 @@ local skeleton = require("@self/skeleton") local TextField = require("@self/text_field") local Links = require("@self/links") local Dialog = require("@self/dialog").Dialog +local Select = require("@self/select") local RadioGroup = require("@self/radio") local PrivateText = require("@self/private_text") local locale = require("@self/locale") @@ -69,6 +70,30 @@ export type Account = { -- When each window starts over (seconds since the epoch), if known. session_resets: number?, week_resets: number?, + -- (A grouped card's:) whether it's the one in use in its group, and + -- whether it can be put in use. + active: boolean?, + switchable: boolean?, + -- An API key, not an account: no plan, no meters, its provider's mark + -- for a face (`provider`, the agent's id for it). + key: boolean?, + provider: string?, +} + +-- One model provider's accounts of an agent that keeps a login per +-- provider (Pi, OpenCode, Hermes): the provider (`name`), its accounts (one +-- in use: its `active`), who Zeron signs you in to for it (`login`) and who +-- issues the API key it adds (`key`) — neither: `hint` says how the agent +-- adds one — and whether its accounts are the agent's own to choose +-- (`read_only`, Hermes' pool). +export type AccountGroup = { + id: string, + name: string, + accounts: { Account }, + login: string?, + key: string?, + hint: string?, + read_only: boolean?, } -- When a window starts over, in this Mac's time, as the shipping app says @@ -157,6 +182,20 @@ function M.disc(inside: Node, tone: string?): Node } end +-- What the card knows of a provider an API key is for, by the agent's own +-- id for the provider: its mark (one set, one ink) and the shape its keys start +-- with (the field's placeholder). +local KEY_PROVIDERS: { [string]: { mark: string, shape: string } } = { + anthropic = { mark = "provider-anthropic", shape = "sk-ant-…" }, + openai = { mark = "provider-openai", shape = "sk-…" }, + ["openai-api"] = { mark = "provider-openai", shape = "sk-…" }, + openrouter = { mark = "provider-openrouter", shape = "sk-or-…" }, + google = { mark = "provider-gemini", shape = "AIza…" }, + gemini = { mark = "provider-gemini", shape = "AIza…" }, + xai = { mark = "provider-xai", shape = "xai-…" }, + deepseek = { mark = "provider-deepseek", shape = "sk-…" }, +} + -- What a card's page does with it (setup's step and Settings share the -- card): `settings`, whether the agent's settings open from it (Settings -- only, `on_settings`); `on_add`, what Add account starts (a sign-in); @@ -182,6 +221,9 @@ export type CardProps = { -- back, Claude's when it can't finish in the browser) or "failed". foot: (string | () -> string)?, enabled: State, + -- An agent nothing here switches or updates (Cloud's: on every Cloud + -- machine, its accounts alone managed here): no switch, no Update. + fixed: boolean?, -- The account in use, by its email. active: () -> string?, settings: boolean?, @@ -235,6 +277,26 @@ export type CardProps = { login_methods: (() -> { LoginMethod })?, on_sign_in_with: ((method: string) -> ())?, on_key: ((var: string, value: string) -> ())?, + -- An agent that keeps a login per model provider: its accounts by + -- provider, as they stand (`accounts` then only finds one by id). Each + -- group with accounts is headed by its provider, the one in use marked + -- in it alone, and ends in its own add row ("Add ChatGPT account"); + -- a provider with none yet is a Connect row at the card's foot. A + -- sign-in shows in the row of its provider (`login_for`), started by + -- `on_add_to`. + groups: (() -> { AccountGroup })?, + login_for: (() -> string?)?, + on_add_to: ((provider: string) -> ())?, + -- An API key for one of its providers, checked and kept by the agent's + -- device (a promise; rejecting with why not), whether keys can be typed + -- here (the agent is on this device: a key never travels), and a key + -- asked for from elsewhere (a provider id: its field opens). + on_add_key: ((provider: string, key: string, name: string?) -> any)?, + -- An API key's name changed (empty: its default): a promise. + on_rename: ((a: Account, name: string) -> any)?, + keys_here: (() -> boolean)?, + key_request: (() -> string?)?, + key_request_seen: (() -> ())?, } export type LoginMethod = { @@ -265,7 +327,7 @@ end -- An account's actions, behind the ⋯ at its end: switch to it, use a -- banked reset (Codex), or remove it. `account` is its row's state: each -- action takes the account as it stands. -local Actions = ui.component(function(p: { card: CardProps, account: State }): Node +local Actions = ui.component(function(p: { card: CardProps, account: State, rename: ((a: Account) -> ())? }): Node local c, account = p.card, p.account local open = ui.use_state(false) local trigger = IconButton { @@ -291,7 +353,25 @@ local Actions = ui.component(function(p: { card: CardProps, account: State 0 and word(a) ~= "using" @@ -334,7 +414,7 @@ end) -- the one in use marked, its two meters and its actions at the end. Every -- account row has the same shape; what Codex banks for one is the row -- after it. Read from its row's state, so it changes in place. -local function account(c: CardProps, row: State): Node +local function account(c: CardProps, row: State, group: { read_only: boolean?, rename: ((a: Account) -> ())? }?): Node -- (Its limits just started over: the data has its windows at 0 until a -- probe says more.) local function reset(): boolean @@ -386,19 +466,34 @@ local function account(c: CardProps, row: State): Node end return Settings.Row { label = email, - private_label = true, + -- (A key's name is no address: shown as it is.) + private_label = row:peek().key ~= true, description = detail, - -- (The face is the address's: a new one only if the address changes.) - lead = ui.presence(email, function(e: string): Node - return Avatar { seed = e, size = 32, label = locale.t("ds.provider_card.account") } - end), + -- (The face is the address's: a new one only if the address changes. + -- An API key has no face: its provider's mark, in the add rows' well.) + lead = if row:peek().key == true + then M.disc( + if KEY_PROVIDERS[row:peek().provider or ""] + then Mark { name = KEY_PROVIDERS[row:peek().provider or ""].mark :: any, size = 16, bare = true } + else Icon { name = "keyboard", size = 16 } + ) + else ui.presence(email, function(e: string): Node + return Avatar { seed = e, size = 32, label = locale.t("ds.provider_card.account") } + end), + -- (In a group, the one in use there: each group has its own.) badge = ui.show(function() + if group then + return row:get().active == true + end return c.active() == email() end, Badge { locale.t("ds.provider_card.in_use"), tone = "accent" }), control = ui.row { gap = "$space.3", items = "center", - ui.column { + -- (An API key has no plan, so no windows: no meters for it.) + ui.show(function(): boolean + return row:get().key ~= true + end, ui.column { gap = "$zeron.space.hair", -- (Labels alone where no reset is known, as the shipping app.) tooltip = Tooltip { @@ -408,8 +503,12 @@ local function account(c: CardProps, row: State): Node }, meter("ds.provider_card.session", session), meter("ds.provider_card.week", week), - }, - Actions { card = c, account = row }, + }), + -- (The agent's own to choose, Hermes' pool: nothing to do here — + -- its place kept, so the meters line up with every other card's.) + if group and group.read_only + then ui.div { w = ui.raw(24, "the actions button's width"), shrink = 0, aria_hidden = true } + else Actions { card = c, account = row, rename = if group then group.rename else nil }, }, } end @@ -902,6 +1001,447 @@ local function failed(provider: Provider, settle: (next: string) -> (), note: (( } end +-- ── An agent with a login per model provider ───────────────────────────── +-- +-- The same card as every other agent's: its accounts a row each (the same +-- row, rules and "In use"), then its add rows at the foot. Only the order +-- and the foot differ: a provider's accounts stand together (the plan line +-- says whose each is: "ChatGPT Plus", "Claude Max", "OpenRouter API key"), +-- each provider with its own one in use; and the foot has an add row per +-- provider Zeron signs in to ("Add ChatGPT account", "Add Claude account") +-- and one "Add API key" (its menu says for which provider, where there's a +-- choice). A sign-in under way, or a key being pasted, takes its add row's +-- place, as Claude Code's does. + +-- The foot's add row for one provider's sign-in, or that sign-in in its +-- place while it's under way (keyed by provider: each stands as the others +-- change). +local function login_row(c: CardProps, group: State, kind: () -> string): Node + local first = group:peek() + local id = first.id + local named: Provider = { id = id, name = first.login or first.name } + local function mine(): string + local k = kind() + return if k ~= "idle" and c.login_for and c.login_for() == id then k else "add" + end + return ui.column { + w_full = true, + id = `account-add-{c.provider.id}-{id}`, + rule(), + ui.presence(mine, function(k: string): Node + if k == "waiting" then + return waiting(named, c.settle, c.login_note, c) + elseif k == "code" then + return code_row(named, c.settle, c.on_code) + elseif k == "failed" then + return failed(named, c.settle, c.login_note, c) + end + return Settings.Row { + label = function(): string + return locale.s("ds.provider_card.add_named_account", { name = group:get().login or group:get().name }) + end, + lead = M.disc(Icon { name = "plus", size = 16 }), + on_click = function() + if c.on_add_to then + c.on_add_to(id) + end + end, + } + end, { w_full = true }), + } +end + + +-- Adding an API key, in a dialog, as the app's other dialogs ask: its title, +-- one quiet line, the provider (a select, each with its mark), the key +-- (masked, its reveal, where it's kept under it), Cancel and Save. Save waits for something typed; while the +-- provider checks the key it spins and the inputs hold still; a refused key +-- says why under the field and the dialog stays, the key as typed. The +-- typed key lives in the dialog alone and is cleared as it closes. +local function key_dialog(c: CardProps, open: State, choice: State, keyed: () -> { AccountGroup }): Node + return ui.component(function(): Node + local key = ui.use_state("") + local name = ui.use_state("") + local busy = ui.use_state(false) + local why = ui.use_state("") + local input = ui.ref() + -- Closed (saved, cancelled, dismissed): nothing typed is kept. + ui.effect(function() + if not open:get() then + key:set("") + name:set("") + why:set("") + busy:set(false) + end + end) + local function chosen(): AccountGroup? + for _, g in keyed() do + if g.id == choice:get() then + return g + end + end + return nil + end + local function named(): string + local g = chosen() + return if g then (g.key or g.name) else "" + end + local function about(): { mark: string, shape: string }? + return KEY_PROVIDERS[choice:get()] + end + local function focus_key() + ui.after(0, function() + local el = input.current + if el then + el:focus() + end + end) + end + local function save() + local value = string.gsub(key:peek(), "^%s*(.-)%s*$", "%1") + local provider = choice:peek() + if value == "" or provider == "" or busy:peek() or not c.on_add_key then + return + end + busy:set(true) + why:set("") + local called = string.gsub(name:peek(), "^%s*(.-)%s*$", "%1") + c.on_add_key(provider, value, if called == "" then nil else called):after(function() + key:set("") + busy:set(false) + open:set(false) + end, function(err: any) + busy:set(false) + local message = if type(err) == "table" then err.message else tostring(err) + why:set(if message == "offline" + then locale.s("ds.provider_card.key_offline") + elseif message == "remote" then locale.s("ds.provider_card.key_remote", { name = c.provider.name }) + else message or locale.s("ds.provider_card.key_failed")) + focus_key() + end) + end + local function options(): { any } + local out = {} + for _, g in keyed() do + local known = KEY_PROVIDERS[g.id] + table.insert(out, { value = g.id, label = g.key or g.name, mark = if known then known.mark else nil }) + end + return out + end + return Dialog { + open = open, + title = locale.t("ds.provider_card.key_title"), + -- (A key being checked is kept once it passes: the dialog waits.) + hold = function(): boolean + return busy:get() + end, + body = function(): string + return locale.s("ds.provider_card.key_body", { agent = c.provider.name, name = named() }) + end, + size = "md", + confirm = { + label = locale.t("ds.provider_card.save_key"), + keep_open = true, + busy = function(): boolean + return busy:get() + end, + disabled = function(): boolean + return string.match(key:get(), "%S") == nil + end, + on_click = save, + }, + build = function(): Node + return ui.column { + w_full = true, + id = `key-dialog-{c.provider.id}`, + gap = "$space.4", + Select { + value = choice, + label = locale.t("ds.provider_card.key_provider"), + options = options, + w_full = true, + disabled = function(): boolean + return busy:get() + end, + on_change = function() + why:set("") + focus_key() + end, + }, + TextField { + value = key, + label = locale.t("ds.provider_card.key_field"), + placeholder = function(): string + local a = about() + return if a then a.shape else "" + end, + password = true, + size = "md", + w_full = true, + autofocus = true, + input_ref = input, + hint = function(): string + return locale.s("ds.provider_card.key_kept", { agent = c.provider.name }) + end, + -- Why the key wasn't kept, in the provider's words. + error = function(): string? + local w = why:get() + return if w == "" then nil else w + end, + disabled = function(): boolean + return busy:get() + end, + on_key = function(e: any): boolean? + if e.key == "Enter" and not (e.shift or e.cmd or e.alt or e.ctrl) then + save() + return true + end + return nil + end, + }, + -- What to call it (it has no address of its own): left + -- blank, its provider and last four. + TextField { + value = name, + label = locale.t("ds.provider_card.key_name_optional"), + placeholder = locale.t("ds.provider_card.key_name_placeholder"), + size = "md", + w_full = true, + disabled = function(): boolean + return busy:get() + end, + on_key = function(e: any): boolean? + if e.key == "Enter" and not (e.shift or e.cmd or e.alt or e.ctrl) then + save() + return true + end + return nil + end, + }, + } + end, + } + end)() +end + +-- Renaming an API key, in the same dialog style: its name alone (no key +-- asked again), blank for its default. A refusal (a name holding part of +-- the key) says why under the field. +local function rename_dialog(c: CardProps, open: State, target: State): Node + return ui.component(function(): Node + local name = ui.use_state("") + local busy = ui.use_state(false) + local why = ui.use_state("") + ui.effect(function() + if open:get() then + -- (Its name, if it has one: an unnamed key's title is no name.) + local a = target:peek() :: any + name:set(if a and a.named then a.email else "") + why:set("") + else + busy:set(false) + end + end) + local function save() + local a = target:peek() + if not a or not a.id or busy:peek() or not c.on_rename then + return + end + busy:set(true) + why:set("") + c.on_rename(a, string.gsub(name:peek(), "^%s*(.-)%s*$", "%1")):after(function() + busy:set(false) + open:set(false) + end, function(err: any) + busy:set(false) + local message = if type(err) == "table" then err.message else tostring(err) + why:set(if message == "offline" then locale.s("ds.provider_card.key_offline") else message or locale.s("ds.provider_card.key_failed")) + end) + end + return Dialog { + open = open, + title = locale.t("ds.provider_card.rename_title"), + -- Which key: its provider, and its last four where its title has them. + body = function(): string + local a = target:get() :: any + if not a then + return "" + end + return if a.named then a.plan else `{a.plan} · {a.email}` + end, + size = "sm", + confirm = { + label = locale.t("ds.provider_card.save_key"), + keep_open = true, + busy = function(): boolean + return busy:get() + end, + on_click = save, + }, + build = function(): Node + return ui.column { + w_full = true, + id = `rename-dialog-{c.provider.id}`, + TextField { + value = name, + label = locale.t("ds.provider_card.key_name_label"), + placeholder = locale.t("ds.provider_card.key_name_placeholder"), + hint = locale.t("ds.provider_card.rename_hint"), + size = "md", + w_full = true, + autofocus = true, + select_on_focus = true, + error = function(): string? + local w = why:get() + return if w == "" then nil else w + end, + disabled = function(): boolean + return busy:get() + end, + on_key = function(e: any): boolean? + if e.key == "Enter" and not (e.shift or e.cmd or e.alt or e.ctrl) then + save() + return true + end + return nil + end, + }, + } + end, + } + end)() +end + +-- The foot's "Add API key" (none while another device is shown: a key is +-- typed on the device that runs the agent), opening the key dialog. +local function key_row_foot(c: CardProps, keyed: () -> { AccountGroup }, open_keys: (provider: string?) -> ()): Node + local function keys_here(): boolean + return c.keys_here == nil or c.keys_here() + end + return ui.show(function(): boolean + return keys_here() and #keyed() > 0 + end, ui.column { + w_full = true, + id = `account-add-key-{c.provider.id}`, + rule(), + Settings.Row { + label = locale.t("ds.provider_card.add_api_key"), + lead = M.disc(Icon { name = "plus", size = 16 }), + on_click = function() + open_keys(nil) + end, + }, + }) +end + +-- An agent with a login per model provider: its accounts, a provider's +-- together, then the foot's add rows. +local function grouped(c: CardProps, kind: () -> string): Node + return ui.component(function(): Node + local keys_open = ui.use_state(false) + local key_choice = ui.use_state("") + local renaming = ui.use_state(false) + local renamed = ui.use_state(nil :: Account?) + local function rename(a: Account) + renamed:set(a) + renaming:set(true) + end + local function groups(): { AccountGroup } + return if c.groups then c.groups() or {} else {} + end + local function keyed(): { AccountGroup } + local out = {} + for _, g in groups() do + if g.key then + table.insert(out, g) + end + end + return out + end + -- The key dialog, on `provider`, else on the first provider with no + -- key yet (else the first). + local function open_keys(provider: string?) + local list = keyed() + local want: string? = provider + if not want then + for _, g in list do + local has_key = false + for _, a in g.accounts do + if a.key then + has_key = true + end + end + if not has_key then + want = g.id + break + end + end + end + local found = false + for _, g in list do + if g.id == want then + found = true + end + end + key_choice:set(if found then want :: string elseif list[1] then list[1].id else "") + keys_open:set(true) + end + -- Every account, a provider's together, each knowing whether its + -- provider's are the agent's own to choose (Hermes' pool). + local placed = ui.computed(function(): { Account } + local out = {} + for _, g in groups() do + for _, a in g.accounts do + local one = table.clone(a) :: any + one.read_only = g.read_only == true + table.insert(out, one) + end + end + return out + end) + local logins = ui.computed(function(): { AccountGroup } + local out = {} + for _, g in groups() do + if g.login then + table.insert(out, g) + end + end + return out + end) + -- A key asked for from elsewhere (the model picker): the dialog, open + -- on its provider. + ui.effect(function() + local want = if c.key_request then c.key_request() else nil + if want and want ~= "" then + open_keys(want) + if c.key_request_seen then + c.key_request_seen() + end + end + end) + local function by_id(g: AccountGroup): string + return g.id + end + return ui.column { + w_full = true, + ui.each(placed, function(a: Account, _i: number, row: State): Node + return ui.column { + w_full = true, + id = `account-row-{a.id or key(a)}`, + rule(), + account(c, row, { read_only = (a :: any).read_only == true, rename = if c.on_rename then rename else nil }), + } + end, { key = key }), + ui.each(logins, function(_g: AccountGroup, _i: number, row: State): Node + return login_row(c, row, kind) + end, { key = by_id }), + key_row_foot(c, keyed, open_keys), + key_dialog(c, keys_open, key_choice, keyed), + rename_dialog(c, renaming, renamed), + } + end)() +end + -- An installed agent's card. function M.Card(c: CardProps): Node local provider = c.provider @@ -931,7 +1471,7 @@ function M.Card(c: CardProps): Node gap = "$space.3", items = "center", ui.show(function() - return latest() ~= nil or (c.updating ~= nil and c.updating()) + return not c.fixed and (latest() ~= nil or (c.updating ~= nil and c.updating())) end, Button { locale.t("ds.provider_card.update"), tone = "secondary", @@ -951,7 +1491,7 @@ function M.Card(c: CardProps): Node on_click = c.on_settings, } else nil, - Switch { value = c.enabled, label = locale.t("ds.provider_card.enabled", { name = provider.name }) :: any }, + if c.fixed then nil else Switch { value = c.enabled, label = locale.t("ds.provider_card.enabled", { name = provider.name }) :: any }, }, } -- Its accounts, a row each, keyed: one arriving or going is that row @@ -989,6 +1529,13 @@ function M.Card(c: CardProps): Node else function() return (given :: string?) or "idle" end + -- An agent with a login per model provider: its accounts, a provider's + -- together, and its add rows at the foot. + if c.groups then + return Settings.Group { + ui.column { w_full = true, head, grouped(c, kind) }, + } + end return Settings.Group { ui.column { w_full = true, head, list }, ui.presence(kind, foot, { w_full = true }), diff --git a/apps/zgx/ui/ds/reply_picture.luau b/apps/zgx/ui/ds/reply_picture.luau index 003addf8b..a0efcfab5 100644 --- a/apps/zgx/ui/ds/reply_picture.luau +++ b/apps/zgx/ui/ds/reply_picture.luau @@ -116,6 +116,8 @@ local function measures(): { [string]: number } INSET = n("zeron.prose.picture.tray.inset", 4), ROW = n("zeron.prose.picture.tray.row", 300), CONTROL = n("zeron.prose.picture.control.inset", 6), + THUMB_W = n("zeron.prose.picture.thumb.w", 240), + THUMB_H = n("zeron.prose.picture.thumb.h", 160), } end @@ -374,6 +376,9 @@ type FrameProps = { fixed: boolean, -- (A run's tile: its place.) place: (() -> Place)?, + -- A thumbnail (`Thumbs`): too small for the controls over it; its + -- menu and the lightbox have them. + thumb: boolean?, } local Frame = ui.component(function(props: FrameProps): Node @@ -404,7 +409,7 @@ local Frame = ui.component(function(props: FrameProps): Node return b.w >= 120 and b.h >= 72 end local function controls_up(): boolean - return ready() and roomy() and (hovered:get() or focused:get() > 0) + return not props.thumb and ready() and roomy() and (hovered:get() or focused:get() > 0) end local inner = m.R - m.CONTROL local function open() @@ -766,6 +771,87 @@ function M.Single(props: Props): Node end)({}) end +-- A thumbnail's size for a picture of `nw` by `nh` pixels: its own shape, +-- at most the theme's thumbnail (zeron.prose.picture.thumb), never larger +-- than it is; a screenshot's shape while its size isn't known. +function M.thumb_fit(nw: number?, nh: number?): (number, number) + local m = measures() + if not nw or not nh or nw <= 0 or nh <= 0 then + return math.min(m.THUMB_W, m.THUMB_H * m.PLACE), m.THUMB_H + end + local k = math.min(1, m.THUMB_W / nw, m.THUMB_H / nh) + return math.max(1, math.floor(nw * k)), math.max(1, math.floor(nh * k)) +end + +-- Pictures as small thumbnails in a row (wrapping), each its own shape and +-- opening in the lightbox among the others: a tool's result pictures, +-- under its row, where the full size would crowd the work. +function M.Thumbs(props: RunProps): Node + return ui.component(function(): Node + local pictures = props.pictures + local entries = ui.computed(props.items) + local function pick(failed: boolean): { Entry } + local out = {} + for _, e in entries:get() do + if (now_of(pictures, e.src).state == "failed") == failed then + table.insert(out, e) + end + end + return out + end + return ui.column { + class = "md-image tool-pictures", + w_full = true, + min_w = 0, + gap = "$space.2", + ui.each(ui.computed(function(): { Entry } + return pick(false) + end), function(e: Entry): Node + local function size(): (number, number) + local p = now_of(pictures, e.src) + return M.thumb_fit(size_of(if p.state == "ready" then p.src else nil)) + end + local function place(): Place + local w, h = size() + return { x = 0, y = 0, w = w, h = h, crop = "none" } + end + return Frame { + pictures = pictures, + entry = e, + group = props.group, + set = props.set, + fixed = true, + thumb = true, + place = place, + size = size, + crop = function(): Fit + local w, h = size() + return { w = w, h = h, crop = "none" } + end, + } + end, { + key = function(e: Entry): string + return e.src + end, + direction = "row", + flex_wrap = true, + items = "start", + gap = "$space.2", + }), + ui.each(ui.computed(function(): { Entry } + return pick(true) + end), function(e: Entry): Node + return Missing { pictures = pictures, entry = e, open_link = props.open_link, link_menu = props.link_menu } + end, { + key = function(e: Entry): string + return e.src + end, + gap = "$space.2", + }), + } + end)({}) +end + -- Pictures in a row, on a tray. function M.Run(props: RunProps): Node return ui.component(function(): Node diff --git a/apps/zgx/ui/ds/select.luau b/apps/zgx/ui/ds/select.luau index fa5e6c0e4..b5fb726f4 100644 --- a/apps/zgx/ui/ds/select.luau +++ b/apps/zgx/ui/ds/select.luau @@ -15,6 +15,7 @@ local motion = require("@self/motion") local Icon = require("@self/icon") +local Mark = require("@self/mark") local FadeText = require("@self/fade_text") local Menu = require("@self/menu") local control = require("@self/control") @@ -25,7 +26,9 @@ local locale = require("@self/locale") -- (An option's label, line and group may be messages, `ui.t`, in a list -- given as a table; a function's list reads them as strings, as a state -- holds no message. The placeholder, label, hint and name take messages.) -export type Option = { value: any, label: string | Message, icon: Icon.Name?, description: (string | Message)?, disabled: boolean?, group: (string | Message)? } +-- (`mark`: a ds.Mark's name in the icon's place, drawn bare in the text's +-- ink: a model provider's.) +export type Option = { value: any, label: string | Message, icon: Icon.Name?, mark: string?, description: (string | Message)?, disabled: boolean?, group: (string | Message)? } export type Props = { value: State, -- The choices: a list, or a function of one, followed as it changes @@ -86,7 +89,7 @@ return ui.component(function(props: Props): Node local list = options() local icons, tall, grouped = false, false, false for _, o in list do - icons = icons or o.icon ~= nil + icons = icons or o.icon ~= nil or o.mark ~= nil tall = tall or o.description ~= nil grouped = grouped or o.group ~= nil end @@ -149,6 +152,15 @@ return ui.component(function(props: Props): Node end return false end, + ui.presence(function(): string + local o = chosen() + return if o and o.mark then o.mark else "" + end, function(mark: string): Node + if mark == "" then + return ui.div {} + end + return ui.div { shrink = 0, y = -0.5, color = "$text.secondary", Mark { name = mark, size = control.ICON[size], bare = true } } + end), ui.show(function(): boolean local o = chosen() return o ~= nil and o.icon ~= nil @@ -187,7 +199,7 @@ return ui.component(function(props: Props): Node -- A glyph's box at the button's icon size, so the name after it starts -- where the button's does. - local function glyph(name: Icon.Name?, ink: string?): Node + local function glyph(name: Icon.Name?, ink: string?, mark: string?): Node local side = control.ICON[size] return ui.div { w = side, @@ -197,7 +209,7 @@ return ui.component(function(props: Props): Node items = "center", justify = "center", color = ink or "$text.secondary", - if name then Icon { name = name, size = side } else nil, + if mark then Mark { name = mark, size = side, bare = true } elseif name then Icon { name = name, size = side } else nil, } end @@ -218,7 +230,7 @@ return ui.component(function(props: Props): Node props.on_change(o.value) end end, - if has_icons then glyph(o.icon, if enabled then nil else "$text.disabled") else nil, + if has_icons then glyph(o.icon, if enabled then nil else "$text.disabled", o.mark) else nil, if o.description then ui.column { grow = 1, diff --git a/apps/zgx/ui/ds/switch.luau b/apps/zgx/ui/ds/switch.luau index 13ff83092..81a1da448 100644 --- a/apps/zgx/ui/ds/switch.luau +++ b/apps/zgx/ui/ds/switch.luau @@ -47,6 +47,8 @@ return function(props: Props): Node rounded = "$radius.full", bg = ui.tween(value, { from = "$zeron.switch.track", to = "$zeron.switch.on", duration = 180 }), ui.div { + -- (Its place, for a test: it travels by `x`.) + id = "switch-knob", absolute = true, left = INSET, top = INSET, diff --git a/apps/zgx/ui/ds/text_field.luau b/apps/zgx/ui/ds/text_field.luau index b4d3c4ebd..ea75f7db5 100644 --- a/apps/zgx/ui/ds/text_field.luau +++ b/apps/zgx/ui/ds/text_field.luau @@ -128,13 +128,15 @@ return ui.component(function(props: Props): Node end local function input(secure: boolean): Node - return ui.input(field.input({ + local node = ui.input(field.input({ ref = input_ref, value = value, -- (Named by its placeholder, as a plain or changing string, or a -- message.) label = props.label or props.name or (if type(props.placeholder) == "string" or type(props.placeholder) == "function" or control.is_message(props.placeholder) then props.placeholder else nil) or "", - placeholder = props.placeholder, + -- (A masked input masks its placeholder too: a password's is + -- drawn over it instead, below.) + placeholder = if secure then nil else props.placeholder, secure = secure, error = props.error, inputmode = props.inputmode, @@ -159,6 +161,42 @@ return ui.component(function(props: Props): Node return false end, }, size, focused)) + if not secure or props.placeholder == nil then + return node + end + -- A password's placeholder, plain (the shape of what goes there: + -- "sk-ant-…"), over the empty input, in the placeholder's ink. + return ui.row { + grow = 1, + min_w = 0, + h_full = true, + relative = true, + node, + ui.show(function(): boolean + return value:get() == "" + end, ui.row { + absolute = true, + left = 0, + top = 0, + bottom = 0, + items = "center", + pointer_events = "none", + aria_hidden = true, + ui.text { + function(): string + local ph: any = props.placeholder + if type(ph) == "function" then + return ph() + elseif type(ph) == "table" and ph.get then + return ph:get() + end + return control.text(ph) or "" + end, + text_size = control.TEXT[size], + color = "$zeron.field.placeholder", + }, + }), + } end local children: { any } = {} diff --git a/apps/zgx/ui/ds/tokens.luau b/apps/zgx/ui/ds/tokens.luau index b71d45c15..6d3c632a4 100644 --- a/apps/zgx/ui/ds/tokens.luau +++ b/apps/zgx/ui/ds/tokens.luau @@ -350,7 +350,8 @@ function M.setup() -- one's least tile; how long (as wide as tall, at least) and how -- wide (as tall, at most) before it's cut; a run's tray (its -- inset, so the corner is the picture's plus it, and its tallest - -- row); the controls' inset from the corner. + -- row); the controls' inset from the corner; a tool's result + -- picture's thumbnail (its widest and tallest). picture = { w = 660, h = 420, @@ -361,6 +362,7 @@ function M.setup() wide = 5, tray = { inset = 4, row = 300 }, control = { inset = 6 }, + thumb = { w = 240, h = 160 }, }, }, -- Reasoning effort, a colour a level, cool to warm as it rises: mid diff --git a/apps/zgx/ui/ds/transcript.luau b/apps/zgx/ui/ds/transcript.luau index 15659cf62..8606ca686 100644 --- a/apps/zgx/ui/ds/transcript.luau +++ b/apps/zgx/ui/ds/transcript.luau @@ -300,9 +300,11 @@ local function strip(m: Message, row: State, hovered: () -> boolean): N justify = if mine then "end" else "start", selectable = false, ui.presence(function(): string? - -- (Never while a reply is written: it has no time yet.) + -- (Never while a reply is written. A settled message shows it + -- with or without its time: a time missing, as on a platform + -- that couldn't read one, mustn't take Copy with it.) local now = row:get() - return if hovered() and now.at and not now.streaming then "shown" else nil + return if hovered() and (now.at or now.copy) and not now.streaming then "shown" else nil end, function(): Node return ui.row { class = "message-actions", @@ -659,6 +661,7 @@ local function blocks_of(list: () -> { Block }, m: Message, now: () -> Message, return Activity { key = `{m.id}:{b.id}`, open_subagent = if view then view.open_subagent else nil, + pictures = if view then view.shown_pictures else nil, -- (A long group builds only what's near the view, as a long -- reply does.) window = if view @@ -821,6 +824,7 @@ local function reply( Activity { key = m.id, open_subagent = if view then view.open_subagent else nil, + pictures = if view then view.shown_pictures else nil, thought = thought_of(m, now, draft), tools = function() return now().tools or {} @@ -1142,6 +1146,10 @@ local function Transcript(props: Props): Node -- taken meanwhile stays where it went. local function rise(prompt: Message?) ui.after(16, function() + -- (Scrolled meanwhile: the view is the reader's, see `wheeled`.) + if glides ~= turn then + return + end local row_el = prompt and tops[prompt.id] and tops[prompt.id]:peek() local list_el = list:peek() if not row_el or not list_el or row_el.y == nil or list_el.y == nil then @@ -1154,6 +1162,9 @@ local function Transcript(props: Props): Node duration = motion.ms(GLIDE_MS), ease = "outQuad", onComplete = function() + if glides ~= turn then + return + end -- Landed: the old reply lets go of the room it held -- (above the view, so nothing seen moves), and the -- offset says where the list now rests, a real place @@ -1440,6 +1451,18 @@ local function Transcript(props: Props): Node -- (Taken somewhere of their own: a place still to come back to is -- let go.) waiting = nil + -- A send's glide under way (or its prompt still to land, a steer's): + -- the scroll is theirs, so the glide stops where it is rather than + -- pulling the view back to the end. The old reply keeps the room it + -- held until it's out of view (`rested`), so nothing shown moves. + if gliding:peek() then + glides += 1 + if glide then + glide:pause() + glide = nil + end + gliding:set(false) + end return nil end -- When focus last came to something in the list (Tab, ⇧Tab to a row's @@ -1448,6 +1471,8 @@ local function Transcript(props: Props): Node -- While the width is changing (and a moment after): the reading row -- puts the place back as its lines rewrap, the frame they do. local resizing_until = 0 + -- When the view's size last changed. + local resized_at = -math.huge local function find_reading() reading = nil local el = list:peek() @@ -1529,9 +1554,32 @@ local function Transcript(props: Props): Node local function rested() remember() find_reading() - if not at_end:peek() and ui.now() >= resizing_until then + -- Resting away from the end: let go of it once no change of size is + -- under way, or at once if a person scrolled since the last one (a + -- scroll begun just after a resize is theirs; held, the next resize, + -- however much later, would pull the view back to the end). + if not at_end:peek() and (ui.now() >= resizing_until or wheeled_at >= resized_at) then end_held = false end + -- A send's glide a scroll stopped (`wheeled`): the old reply's held + -- room goes once that reply is out of view, where it moves nothing. + local h = held:peek() + if h.id ~= "" and not gliding:peek() then + local r = rows[h.id] + local row_el = r and r.outer:peek() + local el = list:peek() + local away_from_view = not row_el + or not el + or row_el.y == nil + or row_el.height == nil + or el.y == nil + or el.height == nil + or (row_el.y :: number) + (row_el.height :: number) <= (el.y :: number) + or (row_el.y :: number) >= (el.y :: number) + (el.height :: number) + if away_from_view then + held:set { id = "", h = 0 } + end + end end local rest = ui.debounced(offset, 150, { every = true }) -- (A view just made: its place told once it has stood 150 ms.) @@ -1990,7 +2038,8 @@ local function Transcript(props: Props): Node ui.after(48, settle) end if changed then - resizing_until = ui.now() + 300 + resized_at = ui.now() + resizing_until = resized_at + 300 -- At the end: on it still, every frame of the change. if end_held and not gliding:peek() then -- (Asked of the list itself, which lands it as it lays diff --git a/apps/zgx/ui/locales/en.json b/apps/zgx/ui/locales/en.json index d7a72fab7..bd46a6a85 100644 --- a/apps/zgx/ui/locales/en.json +++ b/apps/zgx/ui/locales/en.json @@ -871,6 +871,8 @@ "default": "Default", "reasoning": "REASONING", "account": "Account", + "account_of": "{name} account", + "no_account": "None", "model": "Model", "search_starred": "Search starred models…", "search_agent": "Search {agent} models…", @@ -882,7 +884,8 @@ "not_found": "No models found", "not_found_hint": "Nothing in {where} matches “{q}”", "where_starred": "starred models", - "where_models": "models" + "where_models": "models", + "add_key": "Add {name} API key" }, "effort_slider": { "reasoning": "Reasoning" @@ -969,7 +972,23 @@ "paste_key_hint": "{name} reads it as {var}. It's kept on this device and never shown again.", "key_name": "{var}", "get_key": "Get a key", - "save_key": "Save" + "save_key": "Save", + "add_named_account": "Add {name} account", + "add_api_key": "Add API key", + "key_offline": "Zeron's engine isn't answering — try again in a moment.", + "key_remote": "API keys are added on the computer that runs {name}.", + "key_failed": "The key couldn't be added — try again.", + "key_title": "Add API key", + "key_provider": "Provider", + "key_body": "{agent} uses this key for {name} models.", + "key_field": "API key", + "key_kept": "Stored on this Mac in {agent}'s settings.", + "key_name_label": "Name", + "key_name_placeholder": "Work, Personal…", + "rename": "Rename", + "rename_title": "Rename API key", + "rename_hint": "Leave it blank for its default name.", + "key_name_optional": "Name (optional)" }, "command_palette": { "scope": { @@ -1611,6 +1630,18 @@ "label": "{name}'s sign-in" }, "remove_row_description": "Chats that used it stay." + }, + "couldnt_switch": "Couldn't switch accounts", + "cloud": "Cloud", + "cloud_keys": { + "title": "API keys", + "section_description": "Instead of signing in, Cloud can use an API key. A key saved here becomes the account its agent uses on every Cloud machine, from its next turn.", + "anthropic": "Anthropic API key", + "openai": "OpenAI API key", + "description": "For {agent} on Cloud. Kept in Zeron's vault, never on this computer.", + "placeholder": "Paste a key", + "save": "Save", + "saved": "{agent} on Cloud now uses this key" } }, "devices": { @@ -3200,7 +3231,8 @@ "show": "Show in Finder", "dismiss": "Dismiss {name}", "saving": "Saving…" - } + }, + "dismiss_error": "Dismiss" }, "browser_api": { "empty": "Enter a website or localhost address.", @@ -3464,7 +3496,11 @@ }, "compose": { "title": "Put text in the message box", - "detail": "You still send it." + "detail": "It can add to what you've written or replace it. You still send it." + }, + "draft": { + "title": "Read what you type in the message box, and set it aside", + "detail": "It sees your words in any chat before you send them, and can take the draft away and put it back later. It never sends it." }, "network": { "title": "Connect to the internet", diff --git a/apps/zgx/ui/locales/zh-Hans.json b/apps/zgx/ui/locales/zh-Hans.json index 18bb0bf25..27d1fe97e 100644 --- a/apps/zgx/ui/locales/zh-Hans.json +++ b/apps/zgx/ui/locales/zh-Hans.json @@ -871,6 +871,8 @@ "default": "默认", "reasoning": "推理强度", "account": "账号", + "account_of": "{name} 账户", + "no_account": "无", "model": "模型", "search_starred": "搜索已加星标的模型…", "search_agent": "搜索 {agent} 模型…", @@ -882,7 +884,8 @@ "not_found": "未找到模型", "not_found_hint": "{where}中没有与“{q}”匹配的内容", "where_starred": "已加星标的模型", - "where_models": "模型" + "where_models": "模型", + "add_key": "添加 {name} API 密钥" }, "effort_slider": { "reasoning": "推理强度" @@ -969,7 +972,23 @@ "paste_key_hint": "{name} 以 {var} 读取它。它保存在此设备上,不会再次显示。", "key_name": "{var}", "get_key": "获取密钥", - "save_key": "保存" + "save_key": "保存", + "add_named_account": "添加 {name} 账户", + "add_api_key": "添加 API 密钥", + "key_offline": "Zeron 引擎没有响应——请稍后再试。", + "key_remote": "API 密钥需在运行 {name} 的电脑上添加。", + "key_failed": "无法添加该密钥——请重试。", + "key_title": "添加 API 密钥", + "key_provider": "提供方", + "key_body": "{agent} 会用这个密钥调用 {name} 的模型。", + "key_field": "API 密钥", + "key_kept": "保存在这台 Mac 上 {agent} 的设置中。", + "key_name_label": "名称", + "key_name_placeholder": "工作、个人…", + "rename": "重命名", + "rename_title": "重命名 API 密钥", + "rename_hint": "留空则使用默认名称。", + "key_name_optional": "名称(可选)" }, "command_palette": { "scope": { @@ -1611,6 +1630,18 @@ "label": "{name} 的登录" }, "remove_row_description": "使用过它的对话会保留。" + }, + "couldnt_switch": "无法切换账户", + "cloud": "云端", + "cloud_keys": { + "title": "API 密钥", + "section_description": "云端也可以使用 API 密钥,而不必登录。在此保存的密钥会成为该代理在每台云端机器上使用的账户,从下一轮开始生效。", + "anthropic": "Anthropic API 密钥", + "openai": "OpenAI API 密钥", + "description": "用于云端的 {agent}。保存在 Zeron 的密钥库中,不会存放在这台电脑上。", + "placeholder": "粘贴密钥", + "save": "保存", + "saved": "云端的 {agent} 现在使用此密钥" } }, "devices": { @@ -3200,7 +3231,8 @@ "show": "在访达中显示", "dismiss": "关闭 {name}", "saving": "正在保存…" - } + }, + "dismiss_error": "关闭" }, "browser_api": { "empty": "输入网站或 localhost 地址。", @@ -3464,7 +3496,11 @@ }, "compose": { "title": "在消息输入框中填写文本", - "detail": "仍由你来发送。" + "detail": "它可以补充或替换你写的内容,仍由你来发送。" + }, + "draft": { + "title": "读取你在消息输入框中输入的内容,并可暂存", + "detail": "它能在你发送前看到你在任意聊天中输入的文字,也能把草稿暂时取走、稍后放回。它不会替你发送。" }, "network": { "title": "连接互联网", diff --git a/apps/zgx/ui/picker_sources_fixture.luau b/apps/zgx/ui/picker_sources_fixture.luau new file mode 100644 index 000000000..e3f3821fc --- /dev/null +++ b/apps/zgx/ui/picker_sources_fixture.luau @@ -0,0 +1,53 @@ +-- A model picker on an agent reaching models through two providers (Pi +-- signed in to Codex and OpenCode, listing GPT-5.5 from each), for +-- tests/model_picker_sources.test.luau: namesakes, a model only one +-- provider has, a long name from both, and an agent with no providers. +-- The model chosen is `test_picker_model`; `test_picker_open` bumped opens +-- it. Here, beside app.luau, as a mounted script loads modules from its own +-- directory down. + +ui.theme.strict("warn") +local ds = require("@ds") +ds.setup() +local ModelPicker = require("@ds/model_picker") +local EffortSlider = require("@ds/effort_slider") + +local THREE: { EffortSlider.Level } = { + { value = "low", label = "Low" }, + { value = "medium", label = "Medium" }, + { value = "high", label = "High" }, +} +local CODEX = { id = "openai-codex", name = "Codex" } +local OPENCODE = { id = "opencode", name = "OpenCode" } +local LONG = "GPT-5.5 Codex Max Preview Extended Context" + +local MODELS: { ModelPicker.Model } = { + { value = "pi/openai-codex/gpt-5.5", label = "GPT-5.5", harness = "pi", provider = CODEX, efforts = THREE }, + { value = "pi/opencode/gpt-5.5", label = "GPT-5.5", harness = "pi", provider = OPENCODE, efforts = THREE }, + { value = "pi/openai-codex/gpt-5.5-mini", label = "GPT-5.5 mini", harness = "pi", provider = CODEX }, + { value = "pi/opencode/big-pickle", label = "Big Pickle", harness = "pi", provider = OPENCODE }, + { value = "pi/openai-codex/long", label = LONG, harness = "pi", provider = CODEX }, + { value = "pi/opencode/long", label = LONG, harness = "pi", provider = OPENCODE }, + { value = "claude/opus", label = "Opus", harness = "claude", efforts = THREE }, + -- The same name as Pi's, in another agent: its tab tells them apart. + { value = "claude/gpt-5.5", label = "GPT-5.5", harness = "claude" }, +} + +local HARNESSES: { ModelPicker.Harness } = { + { id = "pi", label = "Pi", mark = "pi" }, + { id = "claude", label = "Claude", mark = "claude" }, +} + +return ui.column { + w_full = true, + h_full = true, + p = "$space.4", + ModelPicker { + model = ui.state("test_picker_model", "pi/openai-codex/gpt-5.5" :: string?), + effort = ui.state("test_picker_effort", "medium" :: string?), + favorites = ui.state("test_picker_favorites", {} :: { [string]: boolean }), + open_with = ui.state("test_picker_open", 0), + harnesses = HARNESSES, + models = ui.state("test_picker_models", MODELS), + }, +} diff --git a/apps/zgx/ui/provider_groups_fixture.luau b/apps/zgx/ui/provider_groups_fixture.luau new file mode 100644 index 000000000..49a704f8f --- /dev/null +++ b/apps/zgx/ui/provider_groups_fixture.luau @@ -0,0 +1,367 @@ +-- Settings → Providers with agents that keep a login per model provider, +-- mounted on its own with agents made up here (no engine in a test host): +-- what tests/provider_groups.test.luau drives. Pi has two ChatGPT accounts +-- and a Claude one (signed in by Pi's own /login: Zeron can't add those) +-- and no Copilot yet; Hermes lists its own pool, read-only; Claude Code +-- keeps one login, as ever. The groups are published as the host words +-- them (src/agents.rs `provider_groups`), and account/agents' calls are +-- answered as it would: `sign_in_to` starts that provider's sign-in, +-- `switch` moves the one in use within its provider's group alone, +-- `add_key` takes a key starting "sk-good" and refuses any other. What +-- was asked, in order, is `groups_calls`. Here, beside app.luau, as a +-- mounted script loads modules from its own directory down. +-- +-- groups.copilot_lands the Copilot sign-in under way lands: its account +-- groups.remote the page shows another device's agents + +ui.theme.strict("warn") +local ds = require("@ds") +ds.setup() +-- Addresses plain to start: the tests read them. +ds.PrivateText.hidden:set(false) +-- Settings' host calls (the page's settings dialog, its toasts). +require("./settings_stub") +local agents = require("@account/agents") +local registry = require("@account/registry") :: any +registry.load = function() end +local providers = require("@app/screens/settings/providers") + +local function account(id: string, email: string, plan: string, provider: string?, active: boolean, switchable: boolean?): any + return { + id = id, + email = email, + plan = plan, + session = 0.2, + week = 0.4, + active = active, + switchable = switchable ~= false, + provider = provider, + } +end + +-- An API key's row: no plan, no windows. +local function key_account(a: any): any + a.key = true + a.session = 0 + a.week = 0 + return a +end + +local function agent(id: string, name: string, mark: string, accounts: { any }): any + return { + id = id, + name = name, + mark = mark, + installed = true, + can_install = true, + enabled = true, + version = "1.0.0", + installing = false, + login = "idle", + accounts = accounts, + } +end + +-- Each per-provider agent's providers, in the host's order (src/agents.rs +-- `provider_groups`): who Zeron signs you in to for each (`login`), who +-- issues the key it adds (`key`), and how the agent adds one where Zeron +-- can do neither (`hint`). +type Provider = { id: string, name: string, login: string?, key: string?, hint: string? } +local PROVIDERS: { [string]: { Provider } } = { + pi = { + { id = "openai-codex", name = "ChatGPT", login = "ChatGPT" }, + { id = "anthropic", name = "Anthropic", login = "Claude", key = "Anthropic" }, + { id = "github-copilot", name = "GitHub Copilot", login = "GitHub Copilot" }, + { id = "openai", name = "OpenAI", key = "OpenAI" }, + { id = "openrouter", name = "OpenRouter", key = "OpenRouter" }, + { id = "google", name = "Google Gemini", key = "Google Gemini" }, + { id = "xai", name = "xAI", key = "xAI" }, + { id = "deepseek", name = "DeepSeek", key = "DeepSeek" }, + { id = "kimi-coding", name = "Kimi" }, + }, + hermes = { + { id = "openai-codex", name = "ChatGPT", login = "ChatGPT" }, + { id = "nous", name = "Nous Portal", login = "Nous Portal" }, + { id = "xai-oauth", name = "xAI", login = "xAI" }, + { id = "anthropic", name = "Anthropic", key = "Anthropic" }, + { id = "openai-api", name = "OpenAI", key = "OpenAI" }, + { id = "openrouter", name = "OpenRouter", key = "OpenRouter" }, + { id = "gemini", name = "Google Gemini", key = "Google Gemini" }, + { id = "xai", name = "xAI", key = "xAI" }, + { id = "deepseek", name = "DeepSeek", key = "DeepSeek" }, + }, +} + +-- (Who each provider is, as the host names it in a row.) +local VENDOR_NAME = { anthropic = "Anthropic", openai = "OpenAI", ["openai-api"] = "OpenAI", openrouter = "OpenRouter", google = "Google Gemini", gemini = "Google Gemini", xai = "xAI", deepseek = "DeepSeek" } + +local model: { any } = { + agent("claude-code", "Claude Code", "claude", { + account("cl1", "bo@example.com", "Max", nil, true), + }), + agent("codex", "Codex", "openai", { + account("cx1", "ada@example.com", "Pro", nil, true), + account("cx2", "work@example.com", "Plus", nil, false), + }), + agent("pi", "Pi", "pi", { + account("o1", "ada@chatgpt.test", "ChatGPT Plus", "openai-codex", true), + account("c1", "ada@claude.test", "Claude Max", "anthropic", true), + account("o2", "work@chatgpt.test", "ChatGPT Pro", "openai-codex", false), + account("o3", "old@chatgpt.test", "ChatGPT Plus", "openai-codex", false), + account("k9", "kimi@example.test", "Kimi", "kimi-coding", true), + }), + agent("hermes", "Hermes", "hermes", { + account("h1", "first@chatgpt.test", "ChatGPT Pro", "openai-codex", true, false), + account("h2", "second@chatgpt.test", "ChatGPT Plus", "openai-codex", false, false), + -- (Seeded from OPENROUTER_API_KEY: never titled by that variable.) + key_account(account("h3", "API key ···9f3e", "OpenRouter · from environment", "openrouter", true, false)), + }), +} + +local function find(id: string): any + for _, a in model do + if a.id == id then + return a + end + end + return nil +end + +-- The groups as the host publishes them (src/agents.rs). +local function groups_of(a: any, accounts: { any }): { any }? + local list = PROVIDERS[a.id] + if not list then + return nil + end + local out = {} + for _, p in list do + local mine = {} + for _, acc in accounts do + if acc.provider == p.id then + table.insert(mine, acc) + end + end + if #mine > 0 or p.login or p.key then + table.insert(out, { + id = p.id, + name = p.name, + accounts = mine, + login = p.login, + key = p.key, + hint = if #mine > 0 then p.hint else nil, + read_only = a.id == "hermes", + }) + end + end + return out +end + +-- Whose agents show: this Mac's (nil), or another device's (`groups.remote`). +local target = ui.state("groups_target", nil :: string?) + +local function publish() + local list = {} + for _, a in model do + local item = table.clone(a) + local accounts = {} + for _, acc in a.accounts do + table.insert(accounts, table.clone(acc)) + end + item.accounts = accounts + item.groups = groups_of(a, accounts) + table.insert(list, item) + end + agents.now:set({ state = "ready", list = list, target = target:peek() } :: any) +end + +local said: { string } = {} +local calls = ui.state("groups_calls", "") +local function note(what: string) + table.insert(said, what) + calls:set(table.concat(said, ",")) +end + +local stub = agents :: any +stub.load = function() end +stub.target = function() end +stub.sign_in = function(id: string) + note(`sign_in:{id}`) + local a = find(id) + a.login = "waiting" + a.login_for = if PROVIDERS[id] then PROVIDERS[id][1].id else nil + publish() +end +stub.sign_in_to = function(id: string, provider: string) + note(`sign_in_to:{id}:{provider}`) + local a = find(id) + a.login = "waiting" + a.login_for = provider + publish() +end +stub.cancel = function(id: string) + note(`cancel:{id}`) + local a = find(id) + a.login = "idle" + a.login_for = nil + publish() +end +stub.dismiss = function(id: string) + local a = find(id) + a.login = "idle" + a.login_for = nil + publish() +end +-- A switch: o3's is refused, in the engine's words; any other taken. +stub.switch = function(id: string, account_id: string): any + note(`switch:{id}:{account_id}`) + if account_id == "o3" then + return { + after = function(_: any, _done: (any) -> (), failed: (any) -> ()) + failed({ message = "That saved login no longer exists — refresh and try again." }) + end, + } + end + local a = find(id) + local provider: string? = nil + for _, acc in a.accounts do + if acc.id == account_id then + provider = acc.provider + end + end + for _, acc in a.accounts do + if acc.provider == provider then + acc.active = acc.id == account_id + end + end + publish() + return { after = function(_: any, done: (any) -> ()) done(nil) end } +end +-- A key's name: an empty one its default; one holding "sk-" refused (as the +-- engine refuses a name that looks like a key). +stub.rename = function(id: string, account_id: string, name: string): any + note(`rename:{id}:{account_id}:{name}`) + local refused = string.find(name, "sk-", 1, true) ~= nil + if not refused then + for _, acc in find(id).accounts do + if acc.id == account_id then + local who = VENDOR_NAME[acc.provider] or acc.provider + local tail = string.sub(acc.id, -4) + if name == "" then + acc.email, acc.plan, acc.named = `API key ···{tail}`, who, false + else + acc.email, acc.plan, acc.named = name, `{who} · API key`, true + end + end + end + publish() + end + return { + after = function(_: any, done: (any) -> (), failed: (any) -> ()) + if refused then + failed({ message = "That looks like a key — give it a name instead." }) + else + done(nil) + end + end, + } +end +stub.remove = function(id: string, account_id: string) + note(`remove:{id}:{account_id}`) +end +stub.set_enabled = function() end +-- A key: one starting "sk-good" is taken (its row, by its last four); one +-- starting "sk-slow" is still being checked (for as long as the test +-- likes); anything else is refused in the provider's words. What was typed +-- is never noted: only that a key was added, and for which provider. +local VENDOR = { anthropic = "Anthropic", openai = "OpenAI", ["openai-api"] = "OpenAI", openrouter = "OpenRouter", google = "Google", gemini = "Google", xai = "xAI", deepseek = "DeepSeek" } +stub.add_key = function(id: string, provider: string, key: string, name: string?): any + if string.sub(key, 1, 7) == "sk-slow" then + note(`add_key:{id}:{provider}:checking`) + return { after = function() end } + end + local ok = string.sub(key, 1, 7) == "sk-good" + note(`add_key:{id}:{provider}:{if ok then "ok" else "refused"}`) + if ok then + local a = find(id) + local live = true + for _, acc in a.accounts do + if acc.provider == provider and acc.active then + live = false + end + end + local who = VENDOR_NAME[provider] or provider + local tail = string.sub(key, -4) + -- As the host words a key: its name over " · API key", or + -- "API key ···" over its provider. + local row = key_account(account(`key-{provider}-{tail}`, name or `API key ···{tail}`, if name then `{who} · API key` else who, provider, live)) + row.named = name ~= nil + table.insert(a.accounts, row) + publish() + end + return { + after = function(_: any, done: (any) -> (), failed: (any) -> ()) + if ok then + done(nil) + else + failed({ message = `{VENDOR[provider] or provider} didn't accept that key — check it and try again.` }) + end + end, + } +end + +ui.command { + id = "groups.copilot_lands", + title = "The Copilot sign-in lands", + run = function() + local pi = find("pi") + for _, acc in pi.accounts do + if acc.id == "g1" then + return + end + end + table.insert(pi.accounts, account("g1", "octo", "GitHub Copilot", "github-copilot", true)) + pi.login = "idle" + pi.login_for = nil + publish() + end, +} + +ui.command { + id = "groups.clear_keys", + title = "Forget the keys added here", + run = function() + for _, a in model do + local kept = {} + for _, acc in a.accounts do + if not (acc.key and string.sub(acc.id, 1, 4) == "key-") then + table.insert(kept, acc) + end + end + a.accounts = kept + end + publish() + end, +} +ui.command { + id = "groups.remote", + title = "Show another device's agents", + run = function() + target:set("box") + publish() + end, +} + +publish() + +return ui.column { + w_full = true, + h_full = true, + ds.toast.Host {}, + ui.scroll { + id = "page", + w_full = true, + h_full = true, + bg = "$zeron.window", + ui.column { w_full = true, px = "$space.6", py = "$space.6", providers.view() }, + }, +} diff --git a/apps/zgx/ui/screens/chat/completions.luau b/apps/zgx/ui/screens/chat/completions.luau index 50a41b64d..298c9738c 100644 --- a/apps/zgx/ui/screens/chat/completions.luau +++ b/apps/zgx/ui/screens/chat/completions.luau @@ -22,10 +22,30 @@ local route = require("@app/screens/shell/route") local mentions = require("@ds/composer_mentions") local prefs = require("@app/screens/settings/prefs") local Invocations = require("@app/screens/chat/invocations") +local store = require("@app/screens/chat/store") local ZeronCommands = require("@app/screens/chat/zeron_commands") local M = {} +-- The agent a composer's `/` and `$` ask: its chosen model's, as the catalog +-- shown lists it; else the chat's own (`session.agent`), for a chat whose +-- model the catalog doesn't name (none chosen, so the agent's default; or +-- one on another device). Without it such a chat listed Zeron's commands +-- alone. +function M.agent_of(chosen: string?, session: any): string? + if chosen then + for _, m in store.catalog:get().models do + if m.value == chosen then + return m.harness + end + end + end + if type(session) == "table" and type(session.agent) == "string" and session.agent ~= "" then + return session.agent + end + return nil +end + export type Bind = { key: string, text: State, diff --git a/apps/zgx/ui/screens/chat/composer.luau b/apps/zgx/ui/screens/chat/composer.luau index ad199879b..10038a95a 100644 --- a/apps/zgx/ui/screens/chat/composer.luau +++ b/apps/zgx/ui/screens/chat/composer.luau @@ -19,6 +19,7 @@ local ds = require("@ds") local Dictation = require("@app/screens/chat/dictation") local motion = require("@ds/motion") +local Placement = require("@app/screens/chat/composer_place") local T = require("@ds/transcript") local prefs = require("@app/screens/settings/prefs") local store = require("@app/screens/chat/store") @@ -117,6 +118,18 @@ local function equal(a: any, b: any): boolean end return a == b end +-- Whether two picks hold the same choices. +local function same_pick(a: { [string]: any }?, b: { [string]: any }?): boolean + if a == nil or b == nil then + return a == b + end + for k in DRAFTED do + if not equal(a[k], b[k]) then + return false + end + end + return true +end -- The tray open behind the composer (its todos, tasks or queue), kept -- across a reload. local TRAY = ui.state("chat_tray", nil :: ("todos" | "tasks" | "queue")?) @@ -130,9 +143,11 @@ local function Composer(): Node local function new_chat(): boolean return session_id:get() == nil end - -- (Set as it sends from a new chat: the move to the session that - -- follows slides, as the prompt glides; see `place`.) - local slide_next = false + -- (Set as it sends from a new chat, to the session it opens: the move + -- there slides and eases into its docked form, as the prompt glides; + -- see `place`. Kept until the route moves anywhere else, so neither + -- effect that sees the move depends on which of them runs first.) + local slide_to: string? = nil -- Its form (a new chat's, opened out; a session's): the place it shows -- at's, changing with its place (see `place`). local form_new = ui.state("chat_composer_form_new", session_id:peek() == nil) @@ -140,6 +155,7 @@ local function Composer(): Node -- Moved as it switches between them (ds.Composer's `snap`): its form and -- size there at once, not eased. local snap = ui.state("chat_composer_snap", 0) + local place_snap = ui.state("chat_composer_place_snap", true) -- Whether its model picker is open: the composer is held where it is -- while it is (the picker hangs from its chip; a new chat's composer, -- re-centring as its draft grows or shrinks, moved the chip and the @@ -730,15 +746,9 @@ local function Composer(): Node end) -- The agent the chat runs (its model's): whose completion settings the - -- composer follows. + -- composer follows (the chat's own when the catalog doesn't name it). local function agent(): string? - local chosen = model:get() - for _, m in store.catalog:get().models do - if m.value == chosen then - return m.harness - end - end - return nil + return Completions.agent_of(model:get(), if session_id:get() then open() else nil) end -- What each trigger lists, as the agent's settings have it: with -- "Separate / commands" off, `/` lists the skills after the commands @@ -907,7 +917,9 @@ local function Composer(): Node -- Sent with it: the session has it now; no pick left. if req.model or req.effort or req.fast ~= nil or req.options then local all = table.clone(shared.picks:peek()) - if all[id] == pick then + -- (By what it holds, not which table: a state's snapshot + -- read again needn't be the same table.) + if same_pick(all[id], pick) then all[id] = nil shared.picks:set(all) end @@ -1013,7 +1025,7 @@ local function Composer(): Node store.creating(req) store.open(chat_id) -- (Down with its prompt: the dock's one slide.) - slide_next = true + slide_to = chat_id route.open_session(chat_id) sessions .create({ id = chat_id, project = plan.project, branch = plan.branch, cloud = true }) @@ -1085,7 +1097,7 @@ local function Composer(): Node own_notice:set(nil) store.open(id) -- (Down with its prompt: the dock's one slide.) - slide_next = true + slide_to = id route.open_session(id) store.send(req):after(function() end, function(_e: any) end) end, function(e: any) @@ -1168,9 +1180,19 @@ local function Composer(): Node return asks.question:get() ~= nil or asks.approval:get() ~= nil or route.current:get().name == "settings" or route.current:get().name == "plugin" end, "main") + local composer_sizes = ui.state("chat_composer_sizes", nil :: ds.ComposerSizes?) local function composer(): Node return ds.Composer { dictation = dictation, + on_sizes = function(sizes: ds.ComposerSizes) + composer_sizes:set(sizes) + if sizes.context == snap:peek() and sizes.ready and not sizes.settling then + place_snap:set(false) + end + if math.abs(shared.dock_h:peek() - sizes.presented) > 0.01 then + shared.dock_h:set(sizes.presented) + end + end, -- Its measures, fold and open tray kept across a reload, so it -- is laid out as it was from the first frame. keep = "chat", @@ -1230,6 +1252,7 @@ local function Composer(): Node return store.catalog:get().models end, accounts = accounts.accounts, + account_group = accounts.account_group, on_account = accounts.on_account, on_accounts_open = accounts.on_accounts_open, -- What its context holds (the ring shows once a window is @@ -1450,40 +1473,14 @@ local function Composer(): Node shared.composer_gone() end end) - local dock = ui.ref() - -- How tall a new chat's composer is with nothing in it (what it's placed - -- by, so what's written in it doesn't move its top). - local rest_tall = ui.state("chat_composer_rest_tall", nil :: number?) - -- (A draft just deleted, it's empty while still easing back, and that - -- height would move its top: taken once that's over.) - local REST_SETTLE_MS = 500 - local had_draft = false - local rest_settles_at = 0 - ui.effect(function() - local tall = dock.height or 0 - if shared.text:get() ~= "" or #shared.cargo:get() > 0 or next(shared.quotes:get()) ~= nil then - had_draft = true - return - end - if had_draft then - had_draft = false - rest_settles_at = ui.now() + REST_SETTLE_MS - end - if tall <= 0 or not new_chat() then - return - end - local function take() - if math.abs((rest_tall:peek() or 0) - tall) >= 0.5 then - rest_tall:set(tall) - end - end - local left = rest_settles_at - ui.now() - if left > 0 and rest_tall:peek() ~= nil then - ui.after(left, take) - else - take() - end + local rest_tall = ui.computed(function(): number? + local sizes = composer_sizes:get() + return if sizes then sizes.rest else nil end) + local function presented_height(): number + local sizes = composer_sizes:get() + return if sizes then sizes.presented else shared.dock_h:get() + end -- Where it stands: mid-page on a new chat (centred under the title bar), -- else docked at the foot (0), as laid out now. local function target_y(): number @@ -1496,7 +1493,7 @@ local function Composer(): Node if h <= 0 then h = page_h:get() end - local tall = dock.height or 0 + local tall = presented_height() if tall <= 0 then tall = shared.dock_h:get() end @@ -1504,110 +1501,110 @@ local function Composer(): Node -- and grows down from there. Only a draft that would run off the -- page's foot moves it, up by as much.) local rest = rest_tall:get() or tall - local hero = h / 2 + Dock.hero_offset() - local docked = h - FOOT - rest / 2 - return math.min(hero - docked, rest - tall) + return Placement.dock_offset(h, rest, tall, FOOT, Dock.hero_offset()) end -- Moving between a new chat and a session: its own send from a new chat - -- slides it down with the prompt (`slide_next`); any other move (another + -- slides it down with the prompt (`slide_to`); any other move (another -- chat opened, a new chat) puts it there at once, in its new form and -- size, no fade, no slide, nothing growing (and as that size is -- measured, it follows at once too). In the page, as it grows or the window resizes, it -- moves there as the dock's spring did. Motion reduced, it's there. local GLIDE = { duration = 260, ease = "out(3)" } - -- How long after a switch its place follows its size at once (the - -- form's size, there at once too (`snap`), is measured a frame later). - local SNAP_MS = 400 - -- (Kept state, as this file's others: the composer is made in a plain - -- function, not a component.) + -- Snap until this context has valid metrics and its destination has + -- been laid out. A deferred acknowledgement replaces elapsed deadlines. local place = ui.state("chat_composer_place", 0) - -- (Held where it is while its model picker is open: `model_open`.) local was_new: boolean? = nil - -- (Its model picker open on a new chat: how far its top gives way so its - -- chip stays, the picker hanging from it, as what's written grows.) local hold = ui.state("chat_composer_hold", 0) local held_tall: number? = nil - local gliding: any = nil - local snap_until = 0 + local gliding, holding: any = nil, nil + local glide_goal: number? = nil + local function cancel_glide() + if gliding then gliding:cancel(); gliding = nil end + glide_goal = nil + end + local function cancel_hold() + if holding then holding:cancel(); holding = nil end + end local function glide_to(y: number) - if gliding then - gliding:cancel() - gliding = nil - end - if motion.reduced_now() or ui.now() < snap_until or math.abs(place:peek() - y) < 0.5 then + local immediate = motion.reduced() or place_snap:get() + if not immediate and gliding and glide_goal == y then return end + cancel_glide() + if immediate or math.abs(place:peek() - y) < 0.5 then place:set(y) return end + glide_goal = y gliding = anime.animate(place, { value = y, duration = GLIDE.duration, ease = GLIDE.ease }) end - -- Made again (as the window opens on its last session, the composer is - -- built twice), a glide begun here must not land after: `place` is kept, - -- and it would put a session's composer where a new chat's stood. ui.on_cleanup(function() - if gliding then - gliding:cancel() - gliding = nil - end + cancel_glide() + cancel_hold() end) ui.effect(function() local y = target_y() local nc = new_chat() - local switched = was_new ~= nil and nc ~= was_new and not slide_next + local switched = was_new ~= nil and nc ~= was_new was_new = nc - slide_next = false - if switched then - snap_until = ui.now() + SNAP_MS - snap:set(snap:peek() + 1) + -- (A send's move: out of the new chat, to the session it opened. Its + -- form and size ease there as it slides, not snapped.) + local sent = switched and not nc and slide_to ~= nil + if switched and nc then + slide_to = nil end - form_new:set(nc) - -- On a new chat its place is the layout's (see the row below), so the - -- page resizing moves it with the page; this is only where a send - -- slides from. - if nc and not switched then - if gliding then - gliding:cancel() - gliding = nil - end + if switched and not sent then + ui.batch(function() + place_snap:set(true) + form_new:set(nc) + snap:set(snap:peek() + 1) + end) + elseif sent then + ui.batch(function() + place_snap:set(false) + form_new:set(nc) + end) + else + form_new:set(nc) + end + -- New chats are placed by layout; this coordinate only remembers + -- where a send's page transition starts. + if nc then + cancel_glide() place:set(y) - local tall = dock.height or 0 + local tall = presented_height() if model_open:get() then + cancel_hold() held_tall = held_tall or tall hold:set(held_tall - tall) elseif held_tall then held_tall = nil - anime.animate(hold, { value = 0, duration = GLIDE.duration, ease = GLIDE.ease }) + cancel_hold() + if motion.reduced() then hold:set(0) + else holding = anime.animate(hold, { value = 0, duration = GLIDE.duration, ease = GLIDE.ease }) end end return end + cancel_hold() held_tall = nil hold:set(0) glide_to(y) end) - -- (Moving to another chat, as the focus moves between a split's - -- panes, is shown for something else too: its draft, and its size for - -- it, there at once rather than growing or shrinking into it.) + -- Split focus can change the draft without changing page mode. Every + -- such context owns its snap; only an intentional new-chat send glides. local chat_was: string? = route.chat:peek().session ui.effect(function() local now = route.chat:get().session if now ~= chat_was then chat_was = now - snap_until = ui.now() + SNAP_MS - snap:set(snap:peek() + 1) - end - end) - -- (The sidebar opening or closing moves the page's edges (a new - -- chat's page goes to the window's edges as it closes): its place - -- follows the page as it moves, at once, rather than easing after it on - -- a clock of its own, which drew a small loop as the two went their own - -- ways.) - local shell_view = require("@app/screens/shell/view") - local fit = require("@app/screens/shell/fit") - local sidebar_was = not shell_view.collapsed:peek() and fit.current:peek().sidebar - ui.effect(function() - local now = not shell_view.collapsed:get() and fit.current:get().sidebar - if now ~= sidebar_was then - sidebar_was = now - snap_until = ui.now() + SNAP_MS + -- (The session a send opened: the page's move glides, no snap.) + if slide_to ~= nil and now == slide_to then + place_snap:set(false) + return + end + slide_to = nil + ui.batch(function() + place_snap:set(true) + snap:set(snap:peek() + 1) + end) end end) -- Over the whole pane, the pointer passing through it to the page @@ -1657,21 +1654,15 @@ local function Composer(): Node if not new_chat() then return place:get() end - local tall = dock.height or 0 + local tall = presented_height() if tall <= 0 then tall = shared.dock_h:get() end local rest = rest_tall:get() or tall - local at = Dock.hero_offset() - rest / 2 - -- (Only a draft that would run off the page's foot moves it.) - local h = page.height or 0 - if h > 0 then - at = math.min(at, h / 2 - FOOT - tall) - end + local at = Placement.new_offset(page.height or 0, rest, tall, FOOT, Dock.hero_offset()) return at + hold:get() end, ui.div { - ref = dock, id = "chat-composer", hook = "chat.composer", -- (Over the page, not in it: the session it sends to, as the @@ -1685,11 +1676,7 @@ local function Composer(): Node end), DOCK ), - on_resize = function(size: { w: number, h: number }) - if size.h >= 1 and math.abs(shared.dock_h:peek() - size.h) > 0.01 then - shared.dock_h:set(size.h) - end - end, + -- Files carried over the composer itself: the chat's drop, -- as over the page under it. on_file_hover = composer_zone.on_file_hover, diff --git a/apps/zgx/ui/screens/chat/composer_place.luau b/apps/zgx/ui/screens/chat/composer_place.luau new file mode 100644 index 000000000..61bab871d --- /dev/null +++ b/apps/zgx/ui/screens/chat/composer_place.luau @@ -0,0 +1,13 @@ +-- Placement only: dimensions come from the composer's size contract. +local M = {} + +function M.new_offset(page: number, rest: number, presented: number, foot: number, hero_offset: number): number + local centered = hero_offset - rest / 2 + return if page > 0 then math.min(centered, page / 2 - foot - presented) else centered +end + +function M.dock_offset(page: number, rest: number, presented: number, foot: number, hero_offset: number): number + return page / 2 + M.new_offset(page, rest, presented, foot, hero_offset) + presented - (page - foot) +end + +return M diff --git a/apps/zgx/ui/screens/chat/lane_tab.luau b/apps/zgx/ui/screens/chat/lane_tab.luau index 36569988a..9dae81e70 100644 --- a/apps/zgx/ui/screens/chat/lane_tab.luau +++ b/apps/zgx/ui/screens/chat/lane_tab.luau @@ -611,13 +611,7 @@ local function composer(chat: string, view: any, name: string, focus: State string?): any ui.effect(function() agents.watch_device(account_key(device())) end) + local function listed(harness: string): { any }? + local on = agents.on_device:get()[account_key(device())] + return on and on[harness] + end return { - accounts = function(harness: string, model: string): { any }? - local on = agents.on_device:get()[account_key(device())] - local list = on and on[harness] - if not list then + accounts = function(harness: string, model: string, provider: string?): { any }? + local all = listed(harness) + if not all then return nil end + local list = all + if provider and per_provider(harness, all) then + list = {} + for _, a in all do + if a.provider == provider then + table.insert(list, a) + end + end + end local out = table.create(#list) for i, a in list do out[i] = { @@ -1045,6 +1147,49 @@ function M.model_accounts(device: () -> string?): any end return out end, + -- The model's provider, named, and adding one of its accounts: Settings + -- → Providers, on the composer's device, its sign-in under way there. + account_group = function(harness: string, provider: string?): any + if not provider or not per_provider(harness, listed(harness)) then + return nil + end + local offer = (agents.logins:get()[harness] or {})[provider] + local name = if offer then offer.name else nil + for _, a in listed(harness) or {} do + if not name and a.provider == provider then + name = a.group + end + end + if not name then + return nil + end + local key = account_key(device()) + -- Another account: a sign-in, on the composer's device; else an + -- API key, typed in Settings — on this Mac alone (a key never + -- travels to another device). + if offer and offer.login then + return { + name = name, + add = locale.s("ds.provider_card.add_named_account", { name = offer.login }), + on_add = function() + agents.target(if key == "" then nil else key) + route.settings("providers") + agents.sign_in_to(harness, provider) + end, + } + elseif offer and offer.key and key == "" then + return { + name = name, + add = locale.s("ds.model_picker.add_key", { name = offer.key }), + on_add = function() + agents.target(nil) + route.settings("providers") + agents.key_request:set(`{harness}:{provider}`) + end, + } + end + return { name = name } + end, on_account = function(harness: string, id: string) agents.switch_on(account_key(device()), harness, id):after(function() end, function() toast.show { title = locale.s("chat.composer.account_not_switched"), tone = "warning" } diff --git a/apps/zgx/ui/screens/chat/store.luau b/apps/zgx/ui/screens/chat/store.luau index a04ef2378..c33324d30 100644 --- a/apps/zgx/ui/screens/chat/store.luau +++ b/apps/zgx/ui/screens/chat/store.luau @@ -57,6 +57,9 @@ export type Session = { -- Its folder on that device. cwd: string?, harness: string?, + -- The agent its config records (nil until that's known): whose `/` list + -- its composer reads when the catalog doesn't name its model. + agent: string?, model: string?, -- Its model's name: its catalog's, else its id (chat.rs `session_value`). model_label: string?, diff --git a/apps/zgx/ui/screens/onboarding/providers.luau b/apps/zgx/ui/screens/onboarding/providers.luau index f96451d94..903f45ba9 100644 --- a/apps/zgx/ui/screens/onboarding/providers.luau +++ b/apps/zgx/ui/screens/onboarding/providers.luau @@ -19,6 +19,7 @@ local ds = require("@ds") local agents = require("@account/agents") +local toast = require("@ds/toast") local state = require("./state") local Onboarding = ds.Onboarding @@ -113,13 +114,43 @@ local function card(row: State): Node on_add = function() agents.sign_in(id) end, + -- An agent with a login per model provider: its accounts by provider, + -- each group adding its own. + groups = if first.groups + then function() + return (row:get().groups or {}) :: any + end + else nil, + login_for = function(): string? + return row:get().login_for + end, + on_add_to = function(provider: string) + agents.sign_in_to(id, provider) + end, + -- API keys: typed on this Mac for this Mac's agents only. + on_add_key = function(provider: string, key: string, name: string?): any + return agents.add_key(id, provider, key, name) + end, + on_rename = function(acc, name: string): any + return agents.rename(id, acc.id, name) + end, + keys_here = function(): boolean + return agents.now:get().target == nil + end, + key_request = function(): string? + local agent, provider = string.match(agents.key_request:get(), "^([^:]+):(.+)$") + return if agent == id then provider else nil + end, + key_request_seen = function() + agents.key_request:set("") + end, on_code = function(code: string) agents.complete(id, code) end, settle = function(next: string) local login = row:peek().login if next == "waiting" then - agents.sign_in(id) + agents.retry(row:peek()) elseif login == "waiting" or login == "code" then agents.cancel(id) else @@ -128,7 +159,15 @@ local function card(row: State): Node end, on_switch = function(acc) if acc.id then - agents.switch(id, acc.id) + -- (Refused or out of reach: said, never swallowed.) + agents.switch(id, acc.id):after(function() end, function(err: any) + local message = if type(err) == "table" then err.message else nil + toast.show { + title = ui.t("settings.providers.couldnt_switch"):get(), + body = if message == "offline" then nil else message, + tone = "danger", + } + end) end end, on_remove = function(acc) diff --git a/apps/zgx/ui/screens/panel/browser.luau b/apps/zgx/ui/screens/panel/browser.luau index d204c8c90..6289bada6 100644 --- a/apps/zgx/ui/screens/panel/browser.luau +++ b/apps/zgx/ui/screens/panel/browser.luau @@ -433,6 +433,32 @@ Page = ui.component(function(props: Props): Node -- Annotation mode, as the bar's toggle shows it. local mode = ui.use_state(annotating:peek()[id] == true) + -- This navigation, as the page tells it: whether its own document came + -- (committed: the page's content, not the host's error page), whether + -- its process ended after, and whether its failure was dismissed. Each + -- starts over with the next navigation (a reload, Try again). + -- A failure after the page committed is no page missing: the page drew, + -- and it's what to show (a 429 or 5xx page, Google's "unusual traffic" + -- check: WebView2 calls a page with an error status a failed + -- navigation; WebKit a load interrupted once the page was in). + local committed = ui.use_state(false) + local crashed = ui.use_state(false) + local dismissed = ui.use_state(false) + -- The page that didn't load, over where it would be (`trouble`). + local function failed(): boolean + if not has_page(web) or web.error == nil or dismissed:get() then + return false + end + return crashed:get() or not committed:get() + end + local function dismiss(): boolean + if not failed() then + return false + end + dismissed:set(true) + return true + end + -- Made with an address and no page yet (a saved tab, a link opened): -- the page loads. (A reload finds the page where it was: nothing moves.) -- A new tab with a home page set opens on it (once: the start page is @@ -556,7 +582,7 @@ Page = ui.component(function(props: Props): Node end end local function start_annotating() - if not has_page(web) or web.error then + if not has_page(web) or failed() then if mode:peek() then mode:set(false) end @@ -969,6 +995,11 @@ Page = ui.component(function(props: Props): Node return true end if e.key == "Escape" then + -- (Nothing typed to take back: the failure over the page + -- dismissed, as from anywhere else in the tab.) + if address:peek() == last_url and dismiss() then + return true + end -- (Back to the page's address, as a browser's.) suggestions.quiet(last_url) address:set(last_url) @@ -1064,7 +1095,7 @@ Page = ui.component(function(props: Props): Node tooltip = ui.t("panel.browser.annotate_tooltip", { key = ui.shortcut_text(if shell_keys then shell_keys.combo("panel.annotate") else "cmd+shift+i") }):get(), tooltip_side = "bottom", disabled = function(): boolean - return not can_leave() or web.error ~= nil + return not can_leave() or failed() end, on_change = function(on: boolean) if on then @@ -1533,7 +1564,21 @@ Page = ui.component(function(props: Props): Node on_state(value.state) end end, + on_error = function(url: string, _why: string) + -- (The page's process ended: no navigation's, and nothing left + -- drawn, committed or not.) + if url == "" then + crashed:set(true) + end + end, on_navigate = function(e: any) + if type(e) == "table" and e.kind == "started" then + committed:set(false) + crashed:set(false) + dismissed:set(false) + elseif type(e) == "table" and e.kind == "committed" then + committed:set(true) + end -- Another page: its picker is gone with the last, so the mode -- ends (the shipping app's; its marks come back by restore). if type(e) == "table" and e.kind == "committed" and annotating:peek()[id] then @@ -1572,9 +1617,7 @@ Page = ui.component(function(props: Props): Node or string.find(l, "internet connection", 1, true) ~= nil or string.find(l, "not connected", 1, true) ~= nil end - local trouble = ui.show(function(): boolean - return has_page(web) and web.error ~= nil - end, ui.column { + local trouble = ui.show(failed, ui.column { absolute = true, left = 0, right = 0, @@ -1623,6 +1666,14 @@ Page = ui.component(function(props: Props): Node web:reload() end, }, + -- What the page drew anyway, under (Escape too): until the + -- next navigation. + secondary = { + label = ui.t("panel.browser.dismiss_error") :: any, + on_click = function() + dismiss() + end, + }, } end, { w_full = true, grow = 1, min_h = 0 }), }) @@ -1634,6 +1685,14 @@ Page = ui.component(function(props: Props): Node w_full = true, grow = 1, min_h = 0, + -- A bare Escape nothing in the tab took (the error's buttons, the + -- bar's): the failure dismissed, the page under it shown. + on_key = function(e: any): boolean? + if e.key == "Escape" and not (e.shift or e.cmd or e.alt or e.ctrl) and dismiss() then + return true + end + return nil + end, bar, problem_line, find_bar, diff --git a/apps/zgx/ui/screens/plugins/init.luau b/apps/zgx/ui/screens/plugins/init.luau index 7d3cbb4b4..372587175 100644 --- a/apps/zgx/ui/screens/plugins/init.luau +++ b/apps/zgx/ui/screens/plugins/init.luau @@ -17,6 +17,8 @@ -- zeron.device { id, name } where you're working -- zeron.devices { { id, name, here } } your devices -- zeron.appearance "light" | "dark" +-- zeron.draft { session?, text, attachments = { { kind, name } } } +-- the composer's draft ("draft") -- - **What records are made from**, for the host alone (no plugin reads -- these; each reads its own `plugin..records`, holding only what it -- was allowed, src/plugins/records.rs): @@ -43,7 +45,6 @@ local store = require("@app/screens/settings/store") local PrivateText = require("@ds/private_text") local state = require("@app/screens/plugins/state") local page = require("@app/screens/plugins/page") -local chat = require("@app/screens/chat") local ChatShared = require("@app/screens/chat/shared") local Cargo = require("@ds/composer_cargo") @@ -166,6 +167,128 @@ ui.effect(function() put(out.appearance, if kind == "light" or kind == "high-contrast-light" then "light" else "dark") end) +-- What a draft carries, as plugins are told it: each chip's kind and name +-- alone, never a file's path. +local function attachments_of(cargo: { any }): { any } + local list = {} + for _, item in cargo do + table.insert(list, { kind = tostring(item.kind or "file"), name = tostring(item.name or "") }) + end + return list +end + +-- The composer's draft, for plugins allowed "draft" (`zeron.draft()`): the +-- chat it's for (nil, a new chat), its words, and what it carries. +-- Written only while a plugin that's on may read it: otherwise no key +-- typed copies the draft (a long one, every key) for no one. +local draft_out = ui.shared("zeron.draft", nil :: any) +local draft_read = ui.computed(function(): boolean + for _, it in state.now:get().list or {} do + if it.status == "on" and table.find(it.permissions or {}, "draft") then + return true + end + end + return false +end) +ui.effect(function() + if not draft_read:get() then + if draft_out:peek() ~= nil then + put(draft_out, nil) + end + return + end + local key = ChatShared.showing_now() + put(draft_out, { + session = if key ~= "" then key else ui.null, + text = ChatShared.text:get(), + attachments = attachments_of(ChatShared.cargo:get()), + }) +end) + +-- The drafts plugins took (`zeron.take_draft`), each plugin's by its own +-- keys, kept whole here so a plugin never holds its files' paths. Kept for +-- the run, as chats' drafts are; a reload of the scripts keeps them. +-- Each plugin is told what it keeps (`plugin..drafts`): by key, the +-- chat it was taken from, its words, what it carries and when. +local DRAFTS_KEPT = 16 +local shelves = ui.shared("plugins.drafts", {} :: { [string]: { [string]: any } }) +local shelves_told: { [string]: boolean } = {} +ui.effect(function() + local all = shelves:get() + for plugin in all do + shelves_told[plugin] = true + end + for plugin in shelves_told do + local told: { [string]: any } = {} + for key, d in all[plugin] or {} do + told[key] = { + session = d.session or ui.null, + text = d.text, + attachments = attachments_of(d.cargo), + at = d.at, + } + end + ui.shared(`plugin.{plugin}.drafts`, {} :: any):set(told) + end +end) + +-- A plugin's ask of the draft (the host checked "draft" and that it's +-- take, put, swap or drop with a key). +local function draft_asked(plugin: string, op: string, key: string) + local all = table.clone(shelves:peek()) + local mine = table.clone(all[plugin] or {}) + -- (Room for one more, unless it goes where that key kept one.) + local count = 0 + for _ in mine do + count += 1 + end + local full = mine[key] == nil and count >= DRAFTS_KEPT + local function kept_now(d: any, from: string): any + return { text = d.text, cargo = d.cargo, quotes = d.quotes, session = if from ~= "" then from else nil, at = os.time() } + end + if op == "take" then + if full then + return + end + local from = ChatShared.showing() + local d = ChatShared.lift() + if d == nil then + return + end + mine[key] = kept_now(d, from) + elseif op == "swap" then + -- The draft shown and what `key` kept, traded: either may be + -- nothing, so one call sets a draft aside, brings it back, or both. + local was = mine[key] + local from = ChatShared.showing() + if full then + return + end + local d = ChatShared.lift() + if d == nil and was == nil then + return + end + if was ~= nil then + ChatShared.lay(was) + end + mine[key] = if d ~= nil then kept_now(d, from) else nil + elseif op == "put" then + local d = mine[key] + if d == nil then + return + end + mine[key] = nil + ChatShared.lay(d) + elseif op == "drop" then + if mine[key] == nil then + return + end + mine[key] = nil + end + all[plugin] = if next(mine) ~= nil then mine else nil + shelves:set(all) +end + -- What a failed plugin's notice offers (a toast's action: `ds/toast`). ds.toast.action("plugins.open_folder", function(id: string) state.open_folder(id) @@ -185,8 +308,26 @@ local function run(r: any) elseif type(to) == "table" and type(to.settings) == "string" and to.settings ~= "account" then route.settings(to.settings) end - elseif r.kind == "compose" and type(r.value) == "string" then - chat.store.insert(string.sub(r.value, 1, 20000)) + elseif r.kind == "compose" and (type(r.value) == "string" or (type(r.value) == "table" and type(r.value.text) == "string")) then + -- `zeron.compose(text, { replace, session })` (the host checked + -- "compose"; its words alone come as a string): the words put in a + -- chat's draft, the one shown unless it names another ("" a new + -- chat's), in place of its words (its chips stay) or after them, on + -- a line of their own. Unsent: the person sends it. Shown, the + -- composer takes the keys. + local v = if type(r.value) == "string" then { text = r.value } else r.value + local words = string.sub(v.text, 1, 20000) + local shown = ChatShared.showing() + local key = if type(v.session) == "string" and #v.session <= 200 then v.session else shown + if v.replace ~= true then + local now = ChatShared.peek_text_of(key) + local sep = if now == "" or string.sub(now, -1) == "\n" then "" else "\n" + words = now .. sep .. words + end + ChatShared.set_draft_of(key, "text", words) + if key == shown then + ChatShared.focus:add(1) + end elseif r.kind == "compose_comment" and type(r.value) == "table" and type(r.title) == "string" then -- A plugin's review comment on a file or a diff (the host checked -- "compose"): a comment chip on the session's draft, as the files @@ -207,6 +348,13 @@ local function run(r: any) session = if type(c.session) == "string" then c.session else nil, } end + elseif r.kind == "draft" and type(r.value) == "table" and type(r.title) == "string" and r.title ~= "" then + -- A plugin taking the draft, putting one back, swapping the two, or + -- letting one go. + local op, key = r.value.op, r.value.key + if type(op) == "string" and type(key) == "string" then + draft_asked(r.title, op, key) + end elseif r.kind == "panel_tab" and type(r.value) == "table" then -- A plugin's tab in a chat's panel (the host checked "panel.tabs"). local ok, Panel = pcall(require, "@app/screens/panel") diff --git a/apps/zgx/ui/screens/plugins/words.luau b/apps/zgx/ui/screens/plugins/words.luau index 911f70bd6..3e18ba196 100644 --- a/apps/zgx/ui/screens/plugins/words.luau +++ b/apps/zgx/ui/screens/plugins/words.luau @@ -298,6 +298,9 @@ function M.permission(item: any, permission: string): Line return line(false, "map-arrow-right", "plugins.words.permission.navigate.title") elseif permission == "compose" then return line(false, "chat-round-line", "plugins.words.permission.compose.title", "plugins.words.permission.compose.detail") + elseif permission == "draft" then + -- (What you type, read as you type it: said plainly.) + return line(false, "pen", "plugins.words.permission.draft.title", "plugins.words.permission.draft.detail") elseif permission == "network" then -- The places it names (any site, with "*"), those on this device or -- your network said so, and risky then. diff --git a/apps/zgx/ui/screens/settings/chimes.luau b/apps/zgx/ui/screens/settings/chimes.luau index 65f5cb1a8..6b8447374 100644 --- a/apps/zgx/ui/screens/settings/chimes.luau +++ b/apps/zgx/ui/screens/settings/chimes.luau @@ -1,9 +1,19 @@ -- The sessions' chimes, as the shipping app plays them (crates/ui --- shell.rs, its one session detector): a chat turning done, waiting on you, --- or failed plays its sound, if Settings → Notifications has it on. A --- chat's first appearance only sets where it stands (a launch, a sync, a --- hot reload never ring), and what it was is kept in state, so a reload --- picks up where it was. +-- shell.rs, its one session detector; crates/engine desktop_notify's +-- `ping_since`): a chat waiting on you, or failed, plays its sound as its +-- status turns so; a turn finished plays "done", if Settings → +-- Notifications has it on. A chat's first appearance only sets where it +-- stands (a launch, a sync, a hot reload never ring), and what it was is +-- kept in state, so a reload picks up where it was. +-- +-- "Finished" is the turn mark moving (`turn`, the session's +-- `lastCompletedTurn`), never the status "done": that's only activity you +-- haven't seen, and your own message makes it too (issue #1437). Nor does +-- every move ring: one published with the next turn already running is +-- your message carrying it on (a steer, a queued message taken), and a +-- send that replaces the agent's runtime marks the old turn's end a moment +-- before your turn starts, so a finish waits `SETTLE` to stand; a turn +-- going on (or asking, or failing) meanwhile takes it with it. -- -- And the window's focus, told to the engine (`SetViewportFocus`), which -- holds its banners while Zeron is the app in front if Notifications says @@ -16,39 +26,120 @@ local prefs = require("@app/screens/settings/prefs") local M = {} --- Each chat's status as last seen, by id ("" for idle). -local seen = ui.state("settings_chimes_seen", {} :: { [string]: string }) +type Seen = { status: string, turn: string? } --- What a status turning on plays. +-- Each chat as last seen, by id: its status ("" for idle) and finished turn. +local seen = ui.state("settings_chimes_seen_turns", {} :: { [string]: Seen }) + +-- Finishes waiting to stand, by chat: the turn, and when it rings +-- (`ui.now()`, ms). +local settling = ui.state("settings_chimes_settling", {} :: { [string]: { turn: string, at: number } }) + +-- How long a finish waits to stand before it rings (the engine's banners' +-- `DONE_SETTLE`). +local SETTLE = 2000 + +-- What a status turning on plays. ("done" isn't one: see above.) local SOUND: { [string]: string } = { - done = "done", input = "request", failed = "attention", } +-- A turn going on, or asking, or failing: nothing has finished. +local function busy(status: string): boolean + return status == "working" or status == "waiting" or status == "input" or status == "failed" +end + +-- One chime for many at once: the most urgent. +local function louder(ring: string?, sound: string): string + if ring == nil or sound == "attention" or (sound == "request" and ring == "done") then + return sound + end + return ring +end + +local function play(ring: string?) + if ring and prefs.chimes(ring) then + host.invoke("sound.play", ring) + end +end + ui.effect(function() local now = sessions.now:get() if now.state ~= "ready" then return end local before = seen:peek() - local after: { [string]: string } = {} + local after: { [string]: Seen } = {} + local waits = table.clone(settling:peek()) + local moved = false local ring: string? = nil for _, c in now.chats do local status = c.status or "" - after[c.id] = status local was = before[c.id] - if was ~= nil and was ~= status and SOUND[status] then - -- (One chime for many at once: the most urgent.) - local sound = SOUND[status] - if ring == nil or sound == "attention" or (sound == "request" and ring == "done") then - ring = sound + -- (A session row gone for a while, a host restarting, keeps the turn + -- last seen: its coming back is no finish.) + after[c.id] = { status = status, turn = c.turn or (was and was.turn) } + if busy(status) and waits[c.id] then + waits[c.id] = nil + moved = true + end + if was ~= nil then + if was.status ~= status and SOUND[status] then + ring = louder(ring, SOUND[status]) + end + if c.turn ~= nil and c.turn ~= was.turn and c.turn_fresh ~= false and not busy(status) then + waits[c.id] = { turn = c.turn, at = ui.now() + SETTLE } + moved = true end end end + -- (A chat gone takes its finish with it.) + for id in waits do + if after[id] == nil then + waits[id] = nil + moved = true + end + end seen:set(after) - if ring and prefs.chimes(ring) then - host.invoke("sound.play", ring) + if moved then + settling:set(waits) + end + play(ring) +end) + +-- The finishes due by `upto` have stood: they ring, once each moment (one +-- chime for many). (The timer that calls this is the deadline: its clock +-- needn't be `ui.now()`'s, so that's never asked again here.) +local function stand(upto: number) + local waits = settling:peek() + local left = {} + local ring: string? = nil + for id, w in waits do + if w.at <= upto then + local now = seen:peek()[id] + if now and now.turn == w.turn and not busy(now.status) then + ring = louder(ring, "done") + end + else + left[id] = w + end + end + settling:set(left) + play(ring) +end +ui.effect(function() + local soonest: number? = nil + for _, w in settling:get() do + soonest = if soonest then math.min(soonest, w.at) else w.at + end + -- (A timer made in an effect belongs to its run: a new finish, or one + -- taken, sets it again.) + if soonest then + local upto: number = soonest + ui.after(math.max(0, upto - ui.now()), function() + stand(upto) + end) end end) diff --git a/apps/zgx/ui/screens/settings/devices.luau b/apps/zgx/ui/screens/settings/devices.luau index 9a88ef06c..06637b28c 100644 --- a/apps/zgx/ui/screens/settings/devices.luau +++ b/apps/zgx/ui/screens/settings/devices.luau @@ -169,7 +169,9 @@ local icon_of = M.icon -- choosing one calls `choose` with its id. Built once: its options follow -- the devices as they come, go and are renamed, and the choice follows -- `shown`. -function M.picker(shown: () -> string?, choose: (id: string) -> ()): Node +-- (`extra`: more choices after the computers, each `{ value, label, icon }`: +-- Providers' Cloud, whose accounts every Cloud machine uses.) +function M.picker(shown: () -> string?, choose: (id: string) -> (), extra: (() -> { any })?): Node local function computers(): { sessions.Device } return sessions.computers(sessions.devices:get(), true) end @@ -181,9 +183,12 @@ function M.picker(shown: () -> string?, choose: (id: string) -> ()): Node end return "" end + local function extras(): { any } + return if extra then extra() else {} + end return ui.show( function(): boolean - return #computers() > 1 + return #computers() > 1 or #extras() > 0 end, ui.component(function(): Node local chosen = ui.use_state(shown() or here()) @@ -208,6 +213,9 @@ function M.picker(shown: () -> string?, choose: (id: string) -> ()): Node description = if not d.here and d.online == false then ui.t("settings.devices.offline") else nil, }) end + for _, e in extras() do + table.insert(options, e) + end return options end, on_change = choose, diff --git a/apps/zgx/ui/screens/settings/prefs.luau b/apps/zgx/ui/screens/settings/prefs.luau index c44009f70..bf950b800 100644 --- a/apps/zgx/ui/screens/settings/prefs.luau +++ b/apps/zgx/ui/screens/settings/prefs.luau @@ -107,18 +107,26 @@ end -- Each agent's completion in the composer (Zeron's Settings → Providers, -- settings/completion.rs): "Use $ for skills" (`$` opens the skills; off, -- it's ordinary text) and "Separate / commands" (skills kept out of the `/` --- menu; off, `/` lists them with the commands). Both on unless turned off, --- kept by agent id. +-- menu; off, `/` lists them with the commands). Each its agent's default +-- unless changed, kept by agent id. M.skill_completion = ui.persist("settings_skill_completion", {} :: { [string]: { dollar: boolean?, separate: boolean? } }) export type Completion = { dollar: boolean, separate: boolean } +-- "Separate / commands" unless changed: on, but off for Codex, whose skills +-- aren't among its commands (Claude Code's are), so `/` lists its skills +-- beside `/compact` and `/review` as Claude Code's lists its own. +local function separate_default(harness: string?): boolean + return harness ~= "codex" +end + -- An agent's completion settings (`get`: followed as they change). function M.completion(harness: string?): Completion local one = if harness then M.skill_completion:get()[harness] else nil + local separate = if one and one.separate ~= nil then one.separate else separate_default(harness) return { dollar = not (one and one.dollar == false), - separate = not (one and one.separate == false), + separate = separate, } end @@ -130,7 +138,7 @@ function M.set_completion(harness: string, key: "dollar" | "separate", on: boole if key == "dollar" then one.dollar = if on then nil else false else - one.separate = if on then nil else false + one.separate = if on == separate_default(harness) then nil else on end all[harness] = if one.dollar == nil and one.separate == nil then nil else one M.skill_completion:set(all) diff --git a/apps/zgx/ui/screens/settings/providers.luau b/apps/zgx/ui/screens/settings/providers.luau index d86b0708c..d1e13d9a3 100644 --- a/apps/zgx/ui/screens/settings/providers.luau +++ b/apps/zgx/ui/screens/settings/providers.luau @@ -23,6 +23,7 @@ local prefs = require("@app/screens/settings/prefs") local registry = require("@account/registry") local add_agent = require("@app/screens/settings/add_agent") local sign_in_terminal = require("@app/screens/settings/sign_in_terminal") +local cloud = require("@account/cloud") local M = {} @@ -108,6 +109,20 @@ local function here(): string? end return nil end +-- Cloud, as one choice after the computers (never its machines): the +-- accounts every Cloud machine uses, kept by the vault, which the engine +-- answers for (crates/engine cloud_accounts: Claude Code and Codex, their +-- logins and API keys). Offered while Cloud is on. +local CLOUD = "cloud" +local function on_cloud(): boolean + return now().target == CLOUD +end +local function cloud_choice(): { any } + if cloud.on() or on_cloud() then + return { { value = CLOUD, label = ui.t("settings.providers.cloud"):get(), icon = "cloud" } } + end + return {} +end -- The device shown: the engine's target, else this one. local function shown_device(): string? return now().target or here() @@ -115,6 +130,9 @@ end -- (In the locale shown: read where it's drawn.) local function device_name(): string local id = shown_device() + if id == CLOUD then + return ui.t("settings.providers.cloud"):get() + end for _, d in computers() do if d.id == id then return if d.here then ui.t("settings.providers.this_mac"):get() else d.name @@ -124,8 +142,11 @@ local function device_name(): string end local function choose_device(id: string) agents.target(if id == here() then nil else id) - -- (The registry as that device sees it: what it has added, its builds.) - registry.load() + -- (The registry as that device sees it: what it has added, its builds. + -- Cloud runs only Zeron's own.) + if id ~= CLOUD then + registry.load() + end end -- Which of the page's views shows: the agents, the registry ("add"), or @@ -152,7 +173,8 @@ local function kind(): string if s == "looking" or s == "unavailable" then return s end - return "found" + -- (Cloud's page is another: its accounts, its keys, nothing to add.) + return if now().target == "cloud" then "cloud" else "found" end -- Which agent's settings are open (none: ""). @@ -223,6 +245,9 @@ local function card(row: State): Node -- no accounts, and signs in its own way. (Its updates come as any -- agent's: the engine's update coordinator, the registry its feed.) local from_registry = (first :: any).registry == true + -- Cloud's (made for it: the cards are keyed by the device shown): on + -- every Cloud machine, its accounts alone managed here. + local cloud_card = on_cloud() -- The switch follows the engine; a flip goes to it, and its answer -- comes back in the row. local on = ui.use_state(first.enabled) @@ -234,7 +259,7 @@ local function card(row: State): Node if flipped ~= said then on:set(said) end - elseif flipped ~= said then + elseif flipped ~= said and not cloud_card then agents.set_enabled(id, flipped) end end) @@ -250,6 +275,7 @@ local function card(row: State): Node return (row:get() :: any).updating == true end, sign_in_only = from_registry, + fixed = cloud_card, login_note = function(): string? return (row:get() :: any).login_note end, @@ -329,7 +355,7 @@ local function card(row: State): Node end return nil end, - settings = true, + settings = not cloud_card, on_settings = function() load_subagents() open_settings:set(id) @@ -337,13 +363,43 @@ local function card(row: State): Node on_add = function() agents.sign_in(id) end, + -- An agent with a login per model provider: its accounts by provider, + -- each group adding its own. + groups = if first.groups + then function() + return (row:get().groups or {}) :: any + end + else nil, + login_for = function(): string? + return row:get().login_for + end, + on_add_to = function(provider: string) + agents.sign_in_to(id, provider) + end, + -- API keys: typed on this Mac for this Mac's agents only. + on_add_key = function(provider: string, key: string, name: string?): any + return agents.add_key(id, provider, key, name) + end, + on_rename = function(acc, name: string): any + return agents.rename(id, acc.id, name) + end, + keys_here = function(): boolean + return agents.now:get().target == nil + end, + key_request = function(): string? + local agent, provider = string.match(agents.key_request:get(), "^([^:]+):(.+)$") + return if agent == id then provider else nil + end, + key_request_seen = function() + agents.key_request:set("") + end, on_code = function(code: string) agents.complete(id, code) end, settle = function(next: string) local login = row:peek().login if next == "waiting" then - agents.sign_in(id) + agents.retry(row:peek()) elseif login == "waiting" or login == "code" then agents.cancel(id) else @@ -352,7 +408,17 @@ local function card(row: State): Node end, on_switch = function(acc) if acc.id then - agents.switch(id, acc.id) + -- (Refused or out of reach: said, never swallowed.) + agents.switch(id, acc.id):after(function() end, function(err: any) + local message = if type(err) == "table" then err.message else nil + toast.show { + title = ui.t("settings.providers.couldnt_switch"):get(), + body = if message == "offline" + then ui.t("settings.providers.cant_reach", { device = device_name() }):get() + else message, + tone = "danger", + } + end) end end, on_remove = function(acc) @@ -381,7 +447,13 @@ local function cards(): Node gap = "$space.4", ui.each(ui.computed(installed), function(_a: agents.Agent, _i: number, row: State): Node return card(row) - end, { key = by_id }), + end, { + -- (By the device shown too: a card is made for its device, + -- Cloud's unlike a computer's.) + key = function(a: agents.Agent): string + return `{now().target or ""}|{a.id}` + end, + }), } ) end @@ -450,6 +522,85 @@ local function more(): Node ) end +-- Cloud's API keys: Anthropic's for Claude Code, OpenAI's for Codex, kept +-- by the vault. A key saved becomes its agent's account in use, every Cloud +-- machine's from its next turn (as signing in does). +local CLOUD_KEYS = { + { provider = "anthropic-key", agent = "Claude Code", label = "settings.providers.cloud_keys.anthropic" }, + { provider = "openai-key", agent = "Codex", label = "settings.providers.cloud_keys.openai" }, +} +local function cloud_key_row(k: { provider: string, agent: string, label: string }): Node + return ui.component(function(): Node + local value = ui.use_state("") + local busy = ui.use_state(false) + local problem = ui.use_state("") + local function save() + local key = value:peek() + if busy:peek() or key == "" then + return + end + busy:set(true) + problem:set("") + host.call("agents.cloud_key", { provider = k.provider, key = key, device = cloud.device() or "" }):after(function() + busy:set(false) + value:set("") + toast.show { title = ui.t("settings.providers.cloud_keys.saved", { agent = k.agent }):get(), tone = "success" } + end, function(err: any) + busy:set(false) + problem:set(if type(err) == "table" and err.message then tostring(err.message) else tostring(err)) + end) + end + return ds.Settings.Row { + label = ui.t(k.label), + description = function(): string + local p = problem:get() + return if p ~= "" then p else ui.t("settings.providers.cloud_keys.description", { agent = k.agent }):get() + end, + control = ui.row { + gap = "$space.2", + items = "center", + ds.TextField { + value = value, + password = true, + w = 220, + size = "sm", + name = ui.t(k.label), + placeholder = ui.t("settings.providers.cloud_keys.placeholder"), + on_commit = function() + save() + end, + }, + ds.Button { + ui.t("settings.providers.cloud_keys.save"), + tone = "secondary", + size = "sm", + busy = function(): boolean + return busy:get() + end, + disabled = function(): boolean + return value:get() == "" + end, + on_click = save, + }, + }, + } + end)({}) +end +local function cloud_keys(): Node + return ds.Settings.Section { + title = ui.t("settings.providers.cloud_keys.title"), + description = ui.t("settings.providers.cloud_keys.section_description"), + ds.Settings.Group { + ui.column { + w_full = true, + cloud_key_row(CLOUD_KEYS[1]), + ds.Settings.Rule(), + cloud_key_row(CLOUD_KEYS[2]), + }, + }, + } +end + local function body(k: string): Node if k == "looking" then return ds.ProviderCard.Loading() @@ -458,6 +609,9 @@ local function body(k: string): Node return device_name() end, agents.load) end + if k == "cloud" then + return ui.column { w_full = true, gap = "$space.6", cards(), cloud_keys() } + end return ui.column { w_full = true, gap = "$space.6", cards(), more() } end @@ -727,7 +881,7 @@ local function agents_page(): Node -- Agents are per device: which one's (a choice once there's more -- than this one). -- (The same choice as Plugins': screens/settings/devices.) - trail = devices_page.picker(shown_device, choose_device), + trail = devices_page.picker(shown_device, choose_device, cloud_choice), -- (At the top right, on the title's line, as Plugins' is.) trail_top = true, ui.presence(kind, body, { w_full = true, enter = { opacity = { 0, 1 }, duration = 120 }, exit = { opacity = 0, duration = 60 }, mode = "wait" }), @@ -752,6 +906,10 @@ function M.view(): Node -- (Once a visit: a hot reload doesn't ask again.) The page opens on the -- agents; the registry is looked at too, for what it has to add. visits.once("providers", function() + -- (Whether Cloud is on, for its choice.) + if cloud.now:peek().phase == "unknown" then + cloud.load() + end agents.load() registry.load() if view:peek() ~= "agents" then diff --git a/apps/zgx/ui/screens/shell/route.luau b/apps/zgx/ui/screens/shell/route.luau index defcc9e20..0a9aa2eb2 100644 --- a/apps/zgx/ui/screens/shell/route.luau +++ b/apps/zgx/ui/screens/shell/route.luau @@ -35,7 +35,8 @@ -- ({ project }; `take_project()` reads and clears); -- otherwise the composer keeps the one last -- picked on the new-chat page --- route.settings(page?) to settings (a page's id; "general" first) +-- route.settings(page?) to settings (a page's id; else the one shown +-- last, General at first) -- route.leave_settings() back where the chats were -- route.plugin_page(plugin, page) to a plugin's page (`plugin`, `page`: -- ids); the chats stay as they were under it @@ -506,6 +507,18 @@ ui.effect(function() end end) +local settings_page = ui.persist("shell_settings_page", nil :: string?) +ui.effect(function() + local r = here() + local page: string = r.params.page + if r.name ~= "settings" or page == "profile" then + return + end + if settings_page:peek() ~= page then + settings_page:set(page) + end +end) + -- A device asked of the next new chat (a device's "+" in the sidebar): -- held until its composer takes it (`take_device`), so it lands whether -- the composer is there already or arrives with the move home. (A named @@ -645,12 +658,18 @@ function M.choose_project(id: string?) chosen:set(id) end --- To settings (a page's id; the one open, else General). Its pages take --- one step of the history between them (one replaces another), so a step --- back from any of them is back to the chats. +local function reopened(): string + local list: any = (require :: any)("@app/screens/shell/settings") + local shown = settings_page:peek() + return if shown and list.page(shown) then shown else "general" +end + +-- To settings (a page's id; the one open, else the one shown last, else +-- General). Its pages take one step of the history between them (one +-- replaces another), so a step back from any of them is back to the chats. function M.settings(page: string?) local r = at() - local to = page or (if r.name == "settings" then r.params.page else nil) or "general" + local to = page or (if r.name == "settings" then r.params.page else nil) or reopened() if r.name == "settings" then if r.params.page ~= to then go("settings", { page = to }, true) diff --git a/apps/zgx/ui/settings_stub.luau b/apps/zgx/ui/settings_stub.luau index e68bd3ff8..3d0e4b6e7 100644 --- a/apps/zgx/ui/settings_stub.luau +++ b/apps/zgx/ui/settings_stub.luau @@ -432,6 +432,21 @@ end -- a switch of device shows whose. local agents = require("@account/agents") local function agents_of(target: string?): any + -- Cloud (the engine answers for it from the vault): Claude Code and + -- Codex, always installed; Codex with an account, so on. + if target == "cloud" then + local function one(id: string, name: string, mark: string, accounts: { any }): any + return { id = id, name = name, mark = mark, installed = true, can_install = false, enabled = #accounts > 0, version = nil, installing = false, login = "idle", accounts = accounts } + end + return { + state = "ready", + target = target, + list = { + one("claude-code", "Claude Code", "claude", {}), + one("codex", "Codex", "openai", { { id = "c1", email = "ada@example.com", plan = "Pro", session = 0.1, week = 0.2, active = true } }), + }, + } + end local name = if target then "Codex" else "Claude Code" local id = if target then "codex" else "claude-code" return { diff --git a/apps/zgx/ui/templates/zeron-v2/.base.json b/apps/zgx/ui/templates/zeron-v2/.base.json index f5c8ab150..a29cc3f9f 100644 --- a/apps/zgx/ui/templates/zeron-v2/.base.json +++ b/apps/zgx/ui/templates/zeron-v2/.base.json @@ -1,9 +1,9 @@ { "ds/sidebar.luau": "f2abf7b60b5f4d00", - "ds/tokens.luau": "83e41ed0602c275b", - "screens/chat/composer.luau": "cfbf96c226fc0b51", - "screens/chat/lane_tab.luau": "c2ed6de76649c4b6", - "screens/panel/init.luau": "7fcc64426fb6411d", + "ds/tokens.luau": "296d1ea72675de0c", + "screens/chat/composer.luau": "9c0c79de53eae373", + "screens/chat/lane_tab.luau": "12c199c168515f49", + "screens/panel/init.luau": "3d5e0c712c4dda56", "screens/shell/init.luau": "c7b26c3a1ccf9a32", "screens/shell/page.luau": "c1debbce640a5d45", "screens/shell/view.luau": "95dec891b31add1d" diff --git a/apps/zgx/ui/templates/zeron-v2/ds/tokens.luau b/apps/zgx/ui/templates/zeron-v2/ds/tokens.luau index 1f2fb0fc5..bd07e416a 100644 --- a/apps/zgx/ui/templates/zeron-v2/ds/tokens.luau +++ b/apps/zgx/ui/templates/zeron-v2/ds/tokens.luau @@ -295,7 +295,8 @@ function M.setup() -- one's least tile; how long (as wide as tall, at least) and how -- wide (as tall, at most) before it's cut; a run's tray (its -- inset, so the corner is the picture's plus it, and its tallest - -- row); the controls' inset from the corner. + -- row); the controls' inset from the corner; a tool's result + -- picture's thumbnail (its widest and tallest). picture = { w = 660, h = 420, @@ -306,6 +307,7 @@ function M.setup() wide = 5, tray = { inset = 4, row = 300 }, control = { inset = 6 }, + thumb = { w = 240, h = 160 }, }, }, -- Reasoning effort, a colour a level, cool to warm as it rises: mid diff --git a/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau b/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau index 2b312826e..d6cf62303 100644 --- a/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau +++ b/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau @@ -19,6 +19,7 @@ local ds = require("@ds") local Dictation = require("@app/screens/chat/dictation") local motion = require("@ds/motion") +local Placement = require("@app/screens/chat/composer_place") local T = require("@ds/transcript") local Quote = require("@ds/quote") local Comments = require("@app/screens/chat/comments") @@ -37,12 +38,11 @@ local Where = require("@app/screens/chat/where") local DropOverlay = require("@ds/drop_overlay") local mentions = require("@ds/composer_mentions") local Invocations = require("@app/screens/chat/invocations") +local Completions = require("@app/screens/chat/completions") local ZeronCommands = require("@app/screens/chat/zeron_commands") -- (Loaded with the chat page: captures land on its composer.) local Appshots = require("@app/screens/chat/appshots") --- The title bar's height (Zeron's): a new chat centres under it. -local TITLE_H = 38 -- Zeron's dock spring (ω ≈ 27). local DOCK: SpringOptions = { stiffness = 730, damping = 54 } -- Its gap to the window's foot, docked. Its width, rising and docked: the @@ -118,6 +118,18 @@ local function equal(a: any, b: any): boolean end return a == b end +-- Whether two picks hold the same choices. +local function same_pick(a: { [string]: any }?, b: { [string]: any }?): boolean + if a == nil or b == nil then + return a == b + end + for k in DRAFTED do + if not equal(a[k], b[k]) then + return false + end + end + return true +end -- The tray open behind the composer (its todos, tasks or queue), kept -- across a reload. local TRAY = ui.state("chat_tray", nil :: ("todos" | "tasks" | "queue")?) @@ -131,9 +143,11 @@ local function Composer(): Node local function new_chat(): boolean return session_id:get() == nil end - -- (Set as it sends from a new chat: the move to the session that - -- follows slides, as the prompt glides; see `place`.) - local slide_next = false + -- (Set as it sends from a new chat, to the session it opens: the move + -- there slides and eases into its docked form, as the prompt glides; + -- see `place`. Kept until the route moves anywhere else, so neither + -- effect that sees the move depends on which of them runs first.) + local slide_to: string? = nil -- Its form (a new chat's, opened out; a session's): the place it shows -- at's, changing with its place (see `place`). local form_new = ui.state("chat_composer_form_new", session_id:peek() == nil) @@ -141,6 +155,7 @@ local function Composer(): Node -- Moved as it switches between them (ds.Composer's `snap`): its form and -- size there at once, not eased. local snap = ui.state("chat_composer_snap", 0) + local place_snap = ui.state("chat_composer_place_snap", true) -- Whether its model picker is open: the composer is held where it is -- while it is (the picker hangs from its chip; a new chat's composer, -- re-centring as its draft grows or shrinks, moved the chip and the @@ -641,15 +656,9 @@ local function Composer(): Node -- `$` offer nothing yet.) local mention_sources = ui.state("chat_mentions", { ["/"] = {}, ["$"] = {} } :: any) -- The agent the chat runs (its model's): whose completion settings the - -- composer follows. + -- composer follows (the chat's own when the catalog doesn't name it). local function agent(): string? - local chosen = model:get() - for _, m in store.catalog:get().models do - if m.value == chosen then - return m.harness - end - end - return nil + return Completions.agent_of(model:get(), if session_id:get() then open() else nil) end -- What each trigger lists, as the agent's settings have it: with -- "Separate / commands" off, `/` lists the skills after the commands @@ -917,7 +926,9 @@ local function Composer(): Node -- Sent with it: the session has it now; no pick left. if req.model or req.effort or req.fast ~= nil or req.options then local all = table.clone(shared.picks:peek()) - if all[id] == pick then + -- (By what it holds, not which table: a state's snapshot + -- read again needn't be the same table.) + if same_pick(all[id], pick) then all[id] = nil shared.picks:set(all) end @@ -1010,7 +1021,7 @@ local function Composer(): Node store.creating(req) store.open(chat_id) -- (Down with its prompt: the dock's one slide.) - slide_next = true + slide_to = chat_id route.open_session(chat_id) sessions .create({ id = chat_id, project = plan.project, branch = plan.branch, cloud = true }) @@ -1082,7 +1093,7 @@ local function Composer(): Node own_notice:set(nil) store.open(id) -- (Down with its prompt: the dock's one slide.) - slide_next = true + slide_to = id route.open_session(id) store.send(req):after(function() end, function(_e: any) end) end, function(e: any) @@ -1165,9 +1176,19 @@ local function Composer(): Node return question:get() ~= nil or approval:get() ~= nil or route.current:get().name == "settings" or route.current:get().name == "plugin" end, "main") + local composer_sizes = ui.state("chat_composer_sizes", nil :: ds.ComposerSizes?) local function composer(): Node return ds.Composer { dictation = dictation, + on_sizes = function(sizes: ds.ComposerSizes) + composer_sizes:set(sizes) + if sizes.context == snap:peek() and sizes.ready and not sizes.settling then + place_snap:set(false) + end + if math.abs(shared.dock_h:peek() - sizes.presented) > 0.01 then + shared.dock_h:set(sizes.presented) + end + end, -- Its measures, fold and open tray kept across a reload, so it -- is laid out as it was from the first frame. keep = "chat", @@ -1226,6 +1247,7 @@ local function Composer(): Node return store.catalog:get().models end, accounts = accounts.accounts, + account_group = accounts.account_group, on_account = accounts.on_account, on_accounts_open = accounts.on_accounts_open, -- What its context holds (the ring shows once a window is @@ -1485,40 +1507,14 @@ local function Composer(): Node shared.composer_gone() end end) - local dock = ui.ref() - -- How tall a new chat's composer is with nothing in it (what it's placed - -- by, so what's written in it doesn't move its top). - local rest_tall = ui.state("chat_composer_rest_tall", nil :: number?) - -- (A draft just deleted, it's empty while still easing back, and that - -- height would move its top: taken once that's over.) - local REST_SETTLE_MS = 500 - local had_draft = false - local rest_settles_at = 0 - ui.effect(function() - local tall = dock.height or 0 - if shared.text:get() ~= "" or #shared.cargo:get() > 0 or next(shared.quotes:get()) ~= nil then - had_draft = true - return - end - if had_draft then - had_draft = false - rest_settles_at = ui.now() + REST_SETTLE_MS - end - if tall <= 0 or not new_chat() then - return - end - local function take() - if math.abs((rest_tall:peek() or 0) - tall) >= 0.5 then - rest_tall:set(tall) - end - end - local left = rest_settles_at - ui.now() - if left > 0 and rest_tall:peek() ~= nil then - ui.after(left, take) - else - take() - end + local rest_tall = ui.computed(function(): number? + local sizes = composer_sizes:get() + return if sizes then sizes.rest else nil end) + local function presented_height(): number + local sizes = composer_sizes:get() + return if sizes then sizes.presented else shared.dock_h:get() + end -- Where it stands: mid-page on a new chat (centred under the title bar), -- else docked at the foot (0), as laid out now. local function target_y(): number @@ -1531,7 +1527,7 @@ local function Composer(): Node if h <= 0 then h = page_h:get() end - local tall = dock.height or 0 + local tall = presented_height() if tall <= 0 then tall = shared.dock_h:get() end @@ -1539,85 +1535,112 @@ local function Composer(): Node -- and grows down from there. Only a draft that would run off the -- page's foot moves it, up by as much.) local rest = rest_tall:get() or tall - local hero = TITLE_H + (h - TITLE_H - 96) / 2 - local docked = h - FOOT - rest / 2 - return math.min(hero - docked, rest - tall) + return Placement.dock_offset(h, rest, tall, FOOT, Dock.hero_offset()) end -- Moving between a new chat and a session: its own send from a new chat - -- slides it down with the prompt (`slide_next`); any other move (another + -- slides it down with the prompt (`slide_to`); any other move (another -- chat opened, a new chat) puts it there at once, in its new form and -- size, no fade, no slide, nothing growing (and as that size is -- measured, it follows at once too). In the page, as it grows or the window resizes, it -- moves there as the dock's spring did. Motion reduced, it's there. local GLIDE = { duration = 260, ease = "out(3)" } - -- How long after a switch its place follows its size at once (the - -- form's size, there at once too (`snap`), is measured a frame later). - local SNAP_MS = 400 - -- (Kept state, as this file's others: the composer is made in a plain - -- function, not a component.) + -- Snap until this context has valid metrics and its destination has + -- been laid out. A deferred acknowledgement replaces elapsed deadlines. local place = ui.state("chat_composer_place", 0) - -- (Held where it is while its model picker is open: `model_open`.) local was_new: boolean? = nil - -- (Its model picker open on a new chat: how far its top gives way so its - -- chip stays, the picker hanging from it, as what's written grows.) local hold = ui.state("chat_composer_hold", 0) local held_tall: number? = nil - local gliding: any = nil - local snap_until = 0 + local gliding, holding: any = nil, nil + local glide_goal: number? = nil + local function cancel_glide() + if gliding then gliding:cancel(); gliding = nil end + glide_goal = nil + end + local function cancel_hold() + if holding then holding:cancel(); holding = nil end + end local function glide_to(y: number) - if gliding then - gliding:cancel() - gliding = nil - end - if motion.reduced_now() or ui.now() < snap_until or math.abs(place:peek() - y) < 0.5 then + local immediate = motion.reduced() or place_snap:get() + if not immediate and gliding and glide_goal == y then return end + cancel_glide() + if immediate or math.abs(place:peek() - y) < 0.5 then place:set(y) return end + glide_goal = y gliding = anime.animate(place, { value = y, duration = GLIDE.duration, ease = GLIDE.ease }) end - -- Made again (as the window opens on its last session, the composer is - -- built twice), a glide begun here must not land after: `place` is kept, - -- and it would put a session's composer where a new chat's stood. ui.on_cleanup(function() - if gliding then - gliding:cancel() - gliding = nil - end + cancel_glide() + cancel_hold() end) ui.effect(function() local y = target_y() local nc = new_chat() - local switched = was_new ~= nil and nc ~= was_new and not slide_next + local switched = was_new ~= nil and nc ~= was_new was_new = nc - slide_next = false - if switched then - snap_until = ui.now() + SNAP_MS - snap:set(snap:peek() + 1) + -- (A send's move: out of the new chat, to the session it opened. Its + -- form and size ease there as it slides, not snapped.) + local sent = switched and not nc and slide_to ~= nil + if switched and nc then + slide_to = nil end - form_new:set(nc) - -- On a new chat its place is the layout's (see the row below), so the - -- page resizing moves it with the page; this is only where a send - -- slides from. - if nc and not switched then - if gliding then - gliding:cancel() - gliding = nil - end + if switched and not sent then + ui.batch(function() + place_snap:set(true) + form_new:set(nc) + snap:set(snap:peek() + 1) + end) + elseif sent then + ui.batch(function() + place_snap:set(false) + form_new:set(nc) + end) + else + form_new:set(nc) + end + -- New chats are placed by layout; this coordinate only remembers + -- where a send's page transition starts. + if nc then + cancel_glide() place:set(y) - local tall = dock.height or 0 + local tall = presented_height() if model_open:get() then + cancel_hold() held_tall = held_tall or tall hold:set(held_tall - tall) elseif held_tall then held_tall = nil - anime.animate(hold, { value = 0, duration = GLIDE.duration, ease = GLIDE.ease }) + cancel_hold() + if motion.reduced() then hold:set(0) + else holding = anime.animate(hold, { value = 0, duration = GLIDE.duration, ease = GLIDE.ease }) end end return end + cancel_hold() held_tall = nil hold:set(0) glide_to(y) end) + -- Split focus can change the draft without changing page mode. Every + -- such context owns its snap; only an intentional new-chat send glides. + local chat_was: string? = route.chat:peek().session + ui.effect(function() + local now = route.chat:get().session + if now ~= chat_was then + chat_was = now + -- (The session a send opened: the page's move glides, no snap.) + if slide_to ~= nil and now == slide_to then + place_snap:set(false) + return + end + slide_to = nil + ui.batch(function() + place_snap:set(true) + snap:set(snap:peek() + 1) + end) + end + end) -- Over the whole pane, the pointer passing through it to the page -- (its wheel too) but for the composer itself. (Under settings the shell -- hides the chat frame, its state kept: nothing here is made again.) @@ -1663,21 +1686,15 @@ local function Composer(): Node if not new_chat() then return place:get() end - local tall = dock.height or 0 + local tall = presented_height() if tall <= 0 then tall = shared.dock_h:get() end local rest = rest_tall:get() or tall - local at = TITLE_H / 2 - 48 - rest / 2 - -- (Only a draft that would run off the page's foot moves it.) - local h = page.height or 0 - if h > 0 then - at = math.min(at, h / 2 - FOOT - tall) - end + local at = Placement.new_offset(page.height or 0, rest, tall, FOOT, Dock.hero_offset()) return at + hold:get() end, ui.div { - ref = dock, id = "chat-composer", hook = "chat.composer", -- (Over the page, not in it: the session it sends to, as the @@ -1691,11 +1708,7 @@ local function Composer(): Node end), DOCK ), - on_resize = function(size: { w: number, h: number }) - if math.abs(shared.dock_h:peek() - size.h) > 0.01 then - shared.dock_h:set(size.h) - end - end, + -- Files carried over the composer itself: the chat's drop, -- as over the page under it. on_file_hover = composer_zone.on_file_hover, diff --git a/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau b/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau index 6cf7ff770..f4e3e08bf 100644 --- a/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau +++ b/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau @@ -414,13 +414,7 @@ local function composer(chat: string, view: any, name: string, focus: State boolean, ms: number?): boolean + for _ = 1, math.ceil((ms or 5000) / 50) do + if ok() then + return true + end + app:wait('"never shown, only waited past"', { timeout_ms = 50 }) + end + return ok() +end + +local function panel(): any + local app = mount("panel_fixture.luau") + app:resize(900, 640) + app:frames(10) + expect(app:error()).to_be_nil() + expect(app:wait("#panel-empty", { timeout_ms = 15000 })).to_be(true) + app:click("#panel-open-browser") + expect(app:wait(FIELD, { timeout_ms = 15000 })).to_be(true) + return app +end + +local function calls(app: any): string + return app:state("test_web_calls") or "" +end + +-- To google.com/sorry, the page loaded (the field shows its address). +local URL = "https://www.google.com/sorry/index" +local function go(app: any): string + app:click("#outside") + app:frames(2) + app:type(FIELD, URL) + app:key("Enter") + app:frames(10) + expect(eventually(app, function(): boolean + return app:tree(FIELD):find(`="{string.sub(URL, 1, 36)}`, 1, true) ~= nil + end)).to_be(true) + app:frames(5) + return app:state("test_web_last_id") +end + +-- The page moving on, as the host tells it (`started`, `committed`). +local function navigate(app: any, kind: string) + app:set_state("test_web_nav_kind", kind) + app:command("test.web_navigate") + app:frames(5) +end + +-- The load failing, as the host has it: the error on the page's state. +local function fail(app: any, id: string, why: string) + app:set_state(`test_web_error_{id}`, why) + app:frames(10) +end + +-- The page under the overlay is the fixture's stand-in (`page `). +local function page_shown(app: any): boolean + return app:has("#stub-web") +end + +test("browser load error: a page that never came shows the failure, Try again and Dismiss", function() + local app = panel() + local id = go(app) + navigate(app, "started") + fail(app, id, "A server with the specified hostname could not be found.") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) + expect(app:has(RETRY)).to_be(true) + expect(app:has(DISMISS)).to_be(true) + expect(app:tree('role:checkbox "Annotate"')).to_contain("disabled") +end) + +test("browser load error: Dismiss hides the failure and the page stays", function() + local app = panel() + local id = go(app) + navigate(app, "started") + fail(app, id, "The page could not be loaded.") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) + app:click(DISMISS) + app:frames(10) + expect(app:has(FAILED)).to_be(false) + expect(app:has(RETRY)).to_be(false) + expect(page_shown(app)).to_be(true) + expect(app:has(`"page {URL}"`)).to_be(true) + -- Only this navigation's: the next one's failure shows again. + navigate(app, "started") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) +end) + +test("browser load error: Escape dismisses", function() + local app = panel() + local id = go(app) + navigate(app, "started") + fail(app, id, "The page could not be loaded.") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) + -- (From the address field, nothing typed in it to take back.) + app:click(FIELD) + app:frames(2) + app:key("Escape") + app:frames(10) + expect(app:has(FAILED)).to_be(false) + expect(page_shown(app)).to_be(true) +end) + +test("browser load error: Escape from the failure's own buttons dismisses", function() + local app = panel() + local id = go(app) + navigate(app, "started") + fail(app, id, "The page could not be loaded.") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) + -- (Tab from the field: past the bar's ⋯ to Try again.) + app:click(FIELD) + app:frames(2) + for _ = 1, 4 do + if app:tree(RETRY):find("focused", 1, true) then + break + end + app:key("Tab") + app:frames(2) + end + expect(app:tree(RETRY)).to_contain("focused") + app:key("Escape") + app:frames(10) + expect(app:has(FAILED)).to_be(false) + expect(page_shown(app)).to_be(true) + expect(calls(app)).never.to_contain("reload") +end) + +test("browser load error: Try again reloads the page", function() + local app = panel() + local id = go(app) + navigate(app, "started") + fail(app, id, "Could not connect to the server.") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) + app:click(RETRY) + app:frames(5) + expect(calls(app)).to_contain("reload") +end) + +test("browser load error: a page that came and drew, with an error status, shows no failure", function() + local app = panel() + local id = go(app) + -- WebView2: the server's own page (a 429) committed, then the + -- navigation reported failed, in the default words. + navigate(app, "started") + navigate(app, "committed") + fail(app, id, "The page could not be loaded.") + expect(app:has(FAILED)).to_be(false) + expect(app:has(RETRY)).to_be(false) + expect(page_shown(app)).to_be(true) + -- (And the page's controls are the page's: annotate isn't held off.) + expect(app:tree('role:checkbox "Annotate"')).never.to_contain("disabled") + -- A reload that never commits is a failure again. + navigate(app, "started") + expect(app:wait(FAILED, { timeout_ms = 3000 })).to_be(true) +end) + +test("browser load error: no network still says offline, with Dismiss", function() + local app = panel() + local id = go(app) + navigate(app, "started") + fail(app, id, "The internet connection appears to be offline.") + expect(app:wait("\"You're offline\"", { timeout_ms = 3000 })).to_be(true) + expect(app:has(RETRY)).to_be(true) + expect(app:has(DISMISS)).to_be(true) +end) diff --git a/apps/zgx/ui/tests/chat_draft_lift.test.luau b/apps/zgx/ui/tests/chat_draft_lift.test.luau new file mode 100644 index 000000000..1c17c1924 --- /dev/null +++ b/apps/zgx/ui/tests/chat_draft_lift.test.luau @@ -0,0 +1,60 @@ +-- A plugin allowed "draft" takes the composer's draft whole and puts it back +-- (`zeron.take_draft`, `put_draft`, `swap_draft`: screens/plugins keeps it +-- between, through screens/chat/shared's `lift` and `lay`). Taken, the +-- composer is clear; put back in another chat, its words and its chips are +-- as they were and go with the message; put back over words already there, +-- they follow those. + +local function open(app: any, chat: string) + app:command(`go_{chat}`) + app:frames(30) +end + +test("a draft taken in one chat is put back in another whole, chips and all", function() + local app = mount("chat_fixture.luau") + app:resize(900, 700) + open(app, "s2") + app:type('role:textbox "Message"', "Wrong chat prompt") + app:command("mention_s1") + app:frames(10) + app:command("draft_lift") + app:frames(10) + expect(app:state("test_lifted")).to_be("Wrong chat prompt|1") + -- Taken: nothing left on this chat's draft. + expect(app:has('#chat-composer >> role:button "Long chat"')).to_be(false) + expect(app:has('#chat-composer >> ~"Wrong chat prompt"')).to_be(false) + -- Put back in another chat, and sent from there. + open(app, "s3") + app:command("draft_lay") + app:frames(30) + expect(app:has('#chat-composer >> ~"Wrong chat prompt"')).to_be(true) + app:key("Enter") + app:frames(30) + expect(app:state("calls")).to_contain("send:s3:Wrong chat prompt\n\nChats attached:\n- [Long chat](zeron-chat:s1)") + expect(app:error()).to_be(nil) +end) + +test("an empty draft isn't taken", function() + local app = mount("chat_fixture.luau") + app:resize(900, 700) + open(app, "s2") + app:command("draft_lift") + app:frames(10) + expect(app:state("test_lifted")).to_be("nothing") +end) + +test("a draft put back over words already there follows them", function() + local app = mount("chat_fixture.luau") + app:resize(900, 700) + open(app, "s2") + app:type('role:textbox "Message"', "Second") + app:command("draft_lift") + app:frames(10) + app:type('role:textbox "Message"', "First") + app:command("draft_lay") + app:frames(30) + app:key("Enter") + app:frames(30) + expect(app:state("calls")).to_contain("send:s2:First\n\nSecond") + expect(app:error()).to_be(nil) +end) diff --git a/apps/zgx/ui/tests/chat_in_place.test.luau b/apps/zgx/ui/tests/chat_in_place.test.luau index e9a495c75..241dcefaa 100644 --- a/apps/zgx/ui/tests/chat_in_place.test.luau +++ b/apps/zgx/ui/tests/chat_in_place.test.luau @@ -708,6 +708,21 @@ test("a move to another agent shows its seam over the prompt that moved it", fun expect(app:count('"Codex"')).to_be(1) end) +test("a settled reply with no time still shows Copy under the pointer", function() + -- (Windows gave every message no time, and the strip went with it.) + local app = mount("chat_fixture.luau") + app:resize(900, 700) + open(app, "s1") + app:command("reply_without_time") + settle(app) + app:hover('~"Answered with no clock"') + settle(app) + expect(app:count('role:button "Copy message"')).to_be(1) + app:click('role:button "Copy message"') + settle(app) + expect(app:error()).to_be(nil) +end) + test("a reply being written shows no time or Copy, even under the pointer", function() local app = mount("chat_fixture.luau") app:resize(900, 700) diff --git a/apps/zgx/ui/tests/chat_invocations.test.luau b/apps/zgx/ui/tests/chat_invocations.test.luau index 37cf51072..de13445f2 100644 --- a/apps/zgx/ui/tests/chat_invocations.test.luau +++ b/apps/zgx/ui/tests/chat_invocations.test.luau @@ -66,6 +66,34 @@ test("`$` lists the skills; with the agent's `$` off it's plain text, and with ` app:set_state(PREFS, {}) end) +test("a Codex chat whose model the catalog doesn't name lists Codex's commands and skills in `/`, then Zeron's", function() + local app = mount("chat_fixture.luau") + app:resize(900, 700) + app:command("codex_model_less") + app:command("go_s3") + settle(app) + app:type("role:textbox", "/") + settle(app) + -- Its own agent asked (not none, which left Zeron's commands alone). + expect(app:state("calls")).to_contain("invocations:codex:s3") + expect(app:has('role:option "/review"')).to_be(true) + expect(app:has('role:option "/compact"')).to_be(true) + -- Codex's skills aren't among its commands: `/` lists them by default. + expect(app:has('role:option "Code Review"')).to_be(true) + expect(app:has('role:option "/settings"')).to_be(true) + -- Its "Separate / commands" turned on keeps them for `$`. + app:key("Escape") + app:fill("role:textbox", "") + settle(app) + app:set_state(PREFS, { codex = { separate = true } }) + settle(app) + app:type("role:textbox", "/") + settle(app) + expect(app:has('role:option "/review"')).to_be(true) + expect(app:has('role:option "Code Review"')).to_be(false) + app:set_state(PREFS, {}) +end) + test("a command picked lands as its token and is sent as its reference; one typed by hand stays words", function() local app = chat() app:type("role:textbox", "/rev") diff --git a/apps/zgx/ui/tests/chimes.test.luau b/apps/zgx/ui/tests/chimes.test.luau new file mode 100644 index 000000000..2b4716acb --- /dev/null +++ b/apps/zgx/ui/tests/chimes.test.luau @@ -0,0 +1,114 @@ +-- The session chimes (screens/settings/chimes, issue #1437): "done" rings +-- when a turn finishes (its `turn` mark moving and standing a moment), never +-- for a chat turning "done" alone, which is only activity you haven't seen +-- and your own send makes too. Questions and failures ring at once. + +local function chat(id: string, status: string?, turn: string?, fresh: boolean?): any + return { + id = id, + title = id, + device = "here", + status = status, + updated = 0, + created = 0, + turn = turn, + turn_fresh = if fresh == nil then true else fresh, + } +end + +local function publish(app: any, chats: { any }) + app:set_state("sessions", { + state = "ready", + devices = {}, + projects = {}, + chats = chats, + archived = {}, + places = { pinned = {}, sections = {} }, + places_ready = true, + }) + app:frames(2) +end + +local function played(app: any): { string } + local out = {} + for _, c in (app:state("settings_stub_calls") :: any) or {} do + local sound = string.match(c, "^sound%.play:(.+)$") + if sound then + table.insert(out, sound) + end + end + return out +end + +-- Long enough for a finish to stand (chimes' SETTLE, 2 s). +local function settle(app: any) + app:wait("#never-shown", { timeout_ms = 2400 }) + app:frames(3) +end + +local function open(chats: { any }): any + local app = mount("chimes_fixture.luau") + publish(app, chats) + return app +end + +test("chimes: your own send never rings done", function() + local app = open({ chat("a", nil, "t1") }) + -- The send lands: your message makes the chat unseen ("done") before the + -- live row says it's working; the turn mark hasn't moved. + publish(app, { chat("a", "done", "t1") }) + publish(app, { chat("a", "working", "t1") }) + -- A steer, or a queued message taken, as a turn ends: the end is + -- published with the next turn already running. + publish(app, { chat("a", "working", "t2") }) + -- A send that replaces the runtime: the old turn's end lands idle, then + -- your turn starts a moment later. + publish(app, { chat("a", "done", "t3") }) + publish(app, { chat("a", "working", "t3") }) + settle(app) + expect(#played(app)).to_be(0) + + -- The turn your message started finishing: that rings, once. + publish(app, { chat("a", "done", "t4") }) + expect(#played(app)).to_be(0) + settle(app) + expect(table.concat(played(app), ",")).to_be("done") + settle(app) + expect(#played(app)).to_be(1) +end) + +test("chimes: a chat's first turn finishing rings done", function() + local app = open({ chat("new", "working", nil) }) + publish(app, { chat("new", "done", "t1") }) + settle(app) + expect(table.concat(played(app), ",")).to_be("done") +end) + +test("chimes: an old row coming back, or a session row returning, never rings", function() + local app = open({ chat("a", nil, "t1") }) + -- A sync brings back an end published long ago. + publish(app, { chat("a", "done", "t2", false) }) + -- The row goes away (a host restarting) and comes back as it was. + publish(app, { chat("a", nil, nil) }) + publish(app, { chat("a", nil, "t2") }) + settle(app) + expect(#played(app)).to_be(0) +end) + +test("chimes: questions and failures ring at once", function() + local app = open({ chat("q", "working", "t1"), chat("f", "working", "t1") }) + publish(app, { chat("q", "input", "t1"), chat("f", "working", "t1") }) + expect(table.concat(played(app), ",")).to_be("request") + publish(app, { chat("q", "input", "t1"), chat("f", "failed", "t1") }) + expect(table.concat(played(app), ",")).to_be("request,attention") +end) + +test("chimes: Task completed off keeps done quiet, the rest still ring", function() + local app = open({ chat("a", "working", "t1") }) + app:set_state("settings_sound_done", false) + publish(app, { chat("a", "done", "t2") }) + settle(app) + expect(#played(app)).to_be(0) + publish(app, { chat("a", "input", "t2") }) + expect(table.concat(played(app), ",")).to_be("request") +end) diff --git a/apps/zgx/ui/tests/composer_layout.test.luau b/apps/zgx/ui/tests/composer_layout.test.luau new file mode 100644 index 000000000..16daa89e8 --- /dev/null +++ b/apps/zgx/ui/tests/composer_layout.test.luau @@ -0,0 +1,179 @@ +local Layout = require("@ds/composer_layout") + +local function input(overrides: { [string]: any }?): Layout.Input + local p = { + width = 660, + sample = { unwrapped_width = 0, wrapped_height = 22, line_height = 22 }, + trailing_width = 64, + control_corner = 25, + header_height = 0, + header_gap = 12, + expanded = false, + cargo = false, + asking = false, + dictating = false, + multiline = false, + } :: any + for k, v in overrides or {} do + p[k] = v + end + return p +end + +test("composer geometry: compact destination and measured controls", function() + local g = Layout.calculate(input(), false) + expect(g.mode).to_be("compact") + expect(g.height).to_be(49) + expect(g.natural_height).to_be(49) + expect(g.text).to_equal({ left = 45.5, right = 81.5, top = 12.5, width = 531, height = 22 }) + expect(g.controls.leading).to_equal({ left = 9.5, bottom = 9.5, height = 28 }) + expect(g.controls.trailing).to_equal({ right = 9.5, bottom = 7.5, height = 32 }) + local more_controls = Layout.calculate(input({ trailing_width = 100 }), false) + expect(more_controls.text.width).to_be(495) + expect(more_controls.text.left).to_be(g.text.left) + local unknown_controls = Layout.calculate(input({ trailing_width = 0 }), false) + expect(unknown_controls).to_equal(g) +end) + +test("composer geometry: expansion and contraction have distinct exact boundaries", function() + local p = input() + p.sample = { unwrapped_width = 531, wrapped_height = 22, line_height = 22 } + expect(Layout.calculate(p, false).expanded).to_be(false) + p.sample.unwrapped_width = 531.01 + local opened = Layout.calculate(p, false) + expect(opened.expanded).to_be(true) + expect(opened.next_text_expanded).to_be(true) + p.sample.unwrapped_width = 500 + expect(Layout.calculate(p, opened.next_text_expanded).expanded).to_be(true) + expect(Layout.calculate(p, false).expanded).to_be(false) + p.sample.unwrapped_width = 499 + local closed = Layout.calculate(p, true) + expect(closed.expanded).to_be(false) + expect(closed.next_text_expanded).to_be(false) +end) + +test("composer geometry: forced modes preserve explicit text history", function() + for _, flag in { "expanded", "cargo", "asking", "dictating" } do + local p = input({ [flag] = true }) + local g = Layout.calculate(p, false) + expect(g.expanded).to_be(true) + expect(g.next_text_expanded).to_be(false) + ;(p :: any)[flag] = false + expect(Layout.calculate(p, g.next_text_expanded).mode).to_be("compact") + end + local lines = Layout.calculate(input({ multiline = true }), false) + expect(lines.expanded).to_be(true) + expect(lines.next_text_expanded).to_be(true) +end) + +test("composer geometry: missing measurements and unknown width are explicit", function() + local p = input() + p.sample = nil + expect(Layout.calculate(p, false).mode).to_be("compact") + expect(Layout.calculate(p, true).mode).to_be("expanded") + p.width = 0 + local unknown = Layout.calculate(p, true) + expect(unknown.mode).to_be("compact") + expect(unknown.next_text_expanded).to_be(true) + expect(unknown.text.width).to_be(0) + p.expanded = true + expect(Layout.calculate(p, false).mode).to_be("expanded") + expect(Layout.measurement(0)).to_equal({ left = 16, width = 0 }) + expect(Layout.measurement(660)).to_equal({ left = 16, width = 626 }) +end) + +test("composer geometry: natural height is distinct from minimum and maximum", function() + local p = input({ expanded = true }) + local small = Layout.calculate(p, false) + expect(small.height).to_be(120) + expect(small.natural_height < small.height).to_be(true) + expect(small.text.height).to_be(56) + p.sample = { unwrapped_width = 40, wrapped_height = 500, line_height = 22 } + local capped = Layout.calculate(p, false) + expect(capped.height).to_be(304) + expect(capped.text.height).to_be(240) + expect(capped.natural_height > capped.height).to_be(true) + p.sample.wrapped_height = 700 + local more = Layout.calculate(p, false) + expect(more.height).to_be(capped.height) + expect(more.text).to_equal(capped.text) + expect(more.natural_height > capped.natural_height).to_be(true) +end) + +test("composer geometry: cargo and questions place text below the measured header", function() + for _, flag in { "cargo", "asking" } do + local p = input({ [flag] = true, header_height = 90 }) + local g = Layout.calculate(p, false) + expect(g.header_height).to_be(90) + expect(g.text.top).to_be(102) + expect(g.height).to_be(206) + expect(g.text.height).to_be(56) + expect(g.controls.leading.bottom).to_be(11) + p.header_height = 30 + local smaller = Layout.calculate(p, false) + expect(smaller.text.top).to_be(42) + expect(smaller.height).to_be(146) + p.header_gap = 20 + local spaced = Layout.calculate(p, false) + expect(spaced.text.top - smaller.text.top).to_be(8) + expect(spaced.height - smaller.height).to_be(8) + end + local stale = Layout.calculate(input({ expanded = true, header_height = 90 }), false) + expect(stale.header_height).to_be(0) + expect(stale.text.top).to_be(16) + expect(stale.height).to_be(120) +end) + +test("composer geometry: resolved theme corners keep controls and action space aligned", function() + local normal = Layout.calculate(input({ expanded = true }), false) + local rounder = Layout.calculate(input({ expanded = true, control_corner = 35 }), false) + expect(rounder.controls.leading.bottom).to_be(21) + expect(rounder.controls.trailing.bottom).to_be(19) + expect(rounder.controls.voice.bottom).to_be(21) + expect(rounder.height).to_be(130) + expect(rounder.text).to_equal(normal.text) + expect(rounder.tray_inset).to_be(22) +end) + +test("composer geometry: calculation is deterministic and leaves inputs untouched", function() + local p = input({ cargo = true, header_height = 90 }) + table.freeze(p.sample :: any) + table.freeze(p) + local a = Layout.calculate(p, false) + local b = Layout.calculate(p, false) + expect(a).to_equal(b) + expect(p.cargo).to_be(true) + expect(p.header_height).to_be(90) + -- Mutating a returned rectangle cannot change a later calculation. + a.text.top = -100 + expect(Layout.calculate(p, false)).to_equal(b) +end) + +test("composer geometry: a draft past the cap is estimated, and lays out as measured", function() + -- Fewer hard lines than fill the box: measured. One more newline each. + expect(Layout.estimate("", 22)).to_be(nil) + expect(Layout.estimate(string.rep("line\n", 9), 22)).to_be(nil) + local est = Layout.estimate(string.rep("line\n", 5000), 22) :: Layout.Sample + expect(est).never.to_be(nil) + -- The same estimate however long: a keystroke past the cap changes nothing. + expect(Layout.estimate(string.rep("line\n", 12), 22)).to_equal(est) + -- Laid out as the exact measure of the long draft would be: open, capped. + local estimated = Layout.calculate(input({ sample = est, multiline = true }), false) + local measured = Layout.calculate(input({ + sample = { unwrapped_width = 900, wrapped_height = 5000 * 22, line_height = 22 }, + multiline = true, + }), false) + expect(estimated.height).to_be(measured.height) + expect(Layout.same_target(estimated, measured)).to_be(true) + -- A smaller line height needs more lines to reach the cap. + expect(Layout.estimate(string.rep("line\n", 12), 14)).to_be(nil) +end) + +test("composer geometry: a target differs only where a view or the motion reads it", function() + local a = Layout.calculate(input(), false) + -- Wider: the widths layout applies itself, nothing bound. + expect(Layout.same_target(a, Layout.calculate(input({ width = 900 }), false))).to_be(true) + expect(Layout.same_target(a, Layout.calculate(input({ trailing_width = 100 }), false))).to_be(false) + expect(Layout.same_target(a, Layout.calculate(input({ expanded = true }), false))).to_be(false) + expect(Layout.same_target(a, Layout.calculate(input({ control_corner = 30 }), false))).to_be(false) +end) diff --git a/apps/zgx/ui/tests/composer_motion.test.luau b/apps/zgx/ui/tests/composer_motion.test.luau new file mode 100644 index 000000000..01ce51899 --- /dev/null +++ b/apps/zgx/ui/tests/composer_motion.test.luau @@ -0,0 +1,74 @@ +local Layout = require("@ds/composer_layout") +local Motion = require("@ds/composer_motion") + +local function geometry(height: number, header: number?, corner: number?) + return Layout.calculate({ + width = 660, sample = { unwrapped_width = 40, wrapped_height = height, line_height = 22 }, + trailing_width = 64, control_corner = corner or 25, + header_height = header or 0, header_gap = 12, + expanded = false, cargo = (header or 0) > 0, asking = false, dictating = false, + multiline = height > 22, + }, false) +end + +test("composer transition: width changes once after a full expanded line fits", function() + local a, b = geometry(22), geometry(220) + local changes, last = 0, a.text.width + local previous = Motion.frame(a, b, 0) + for i = 0, 100 do + local g = Motion.frame(a, b, i / 100) + expect(g.text.width == a.text.width or g.text.width == b.text.width).to_be(true) + if g.text.width ~= last then + changes += 1 + -- A discrete width change must not also jump the vertical field. + expect(math.abs(g.text.top - previous.text.top) < 1).to_be(true) + expect(math.abs(g.text.height - previous.text.height) < 5).to_be(true) + end + last = g.text.width + previous = g + expect(g.text.height >= 22).to_be(true) + expect(g.text.top >= 0).to_be(true) + expect(g.text.top + g.text.height <= g.height - Layout.BORDER * 2 + 0.001).to_be(true) + if g.expanded then + expect(g.text.top + g.text.height < g.height - g.controls.trailing.bottom - g.controls.trailing.height).to_be(true) + end + end + expect(changes).to_be(1) + expect(Motion.frame(a, b, 1)).to_equal(b) +end) + +test("composer transition: headers and rounder controls remain inside a valid frame", function() + local a, b = geometry(22), geometry(500, 90, 45) + for _, pair in { { a, b }, { b, a } } do + for i = 0, 100 do + local g = Motion.frame(pair[1], pair[2], i / 100) + expect(g.header_height <= g.text.top + 0.001).to_be(true) + expect(g.text.height >= 22).to_be(true) + expect(g.text.top + g.text.height <= g.height - 2 + 0.001).to_be(true) + if not g.expanded then + expect(g.controls.leading.left + 28 < g.text.left).to_be(true) + end + end + end +end) + +test("composer transition: interrupted height and anchors start at the presented geometry", function() + local shown = Motion.frame(geometry(22), geometry(500, 90), 0.3) + local g = Motion.frame(shown, geometry(100, 30), 0) + expect(g.height).to_be(shown.height) + expect(g.header_height).to_be(shown.header_height) + expect(g.controls.leading.bottom).to_be(shown.controls.leading.bottom) + expect(g.controls.trailing.bottom).to_be(shown.controls.trailing.bottom) +end) + +test("composer transition: changes above the cap do not change the visual destination", function() + local a, b = geometry(500), geometry(900) + expect(a.natural_height == b.natural_height).to_be(false) + expect(Motion.same_destination(a, b)).to_be(true) + local constraints = table.clone(a) + constraints.line_height = 24 + constraints.compact_text = { left = 45.5, right = 100 } + expect(Motion.same_destination(a, constraints)).to_be(true) + expect(Motion.same_destination(a, geometry(100))).to_be(false) + expect(Motion.same_destination(a, geometry(500, 30))).to_be(false) +end) diff --git a/apps/zgx/ui/tests/lanes_in_place.test.luau b/apps/zgx/ui/tests/lanes_in_place.test.luau index 28f1fac22..3d7cf7f0e 100644 --- a/apps/zgx/ui/tests/lanes_in_place.test.luau +++ b/apps/zgx/ui/tests/lanes_in_place.test.luau @@ -234,8 +234,22 @@ test("a message that didn't go says so above the side chat's composer, never ove app:type('.side-chat-tab >> role:textbox', "lost words") app:key("Enter") -- An alert of the composer's deck: in its pill, opened to read. - app:wait('.side-chat-tab >> role:button "Open Alerts"', { timeout_ms = 3000 }) - app:click('.side-chat-tab >> role:button "Open Alerts"') + local alerts = '.side-chat-tab >> role:button "Open Alerts"' + -- The presence node exists on its first, transparent enter frame. + -- Advance the test clock until it shows before trying to press it. + local shown = false + for _ = 1, 180 do -- At most the same three seconds, at 60 Hz. + app:frames(1) + if app:has(alerts) then + local first = app:tree(alerts):match("[^\n]+") or "" + if not first:find(" hidden", 1, true) then + shown = true + break + end + end + end + expect(shown).to_be(true) + app:click(alerts) app:frames(30) expect(app:has('.side-chat-tab >> "Your message didn\'t send"')).to_be(true) -- Above the composer's box, not a toast over it. diff --git a/apps/zgx/ui/tests/model_accounts.test.luau b/apps/zgx/ui/tests/model_accounts.test.luau index 15d878a6e..a79be2447 100644 --- a/apps/zgx/ui/tests/model_accounts.test.luau +++ b/apps/zgx/ui/tests/model_accounts.test.luau @@ -91,6 +91,33 @@ test("a chat on another computer reads that computer's accounts", function() expect(app:state("calls")).to_contain("switch_on:box:claude-code:b2") end) +-- A chat on a Cloud machine: its accounts are Cloud's, the vault's (as +-- Settings → Providers shows them under Cloud), never the machine's own, +-- which isn't asked (it would be woken). +test("a chat on a Cloud machine reads and switches Cloud's accounts", function() + local app = with_accounts({ + [""] = { ["claude-code"] = accounts() }, + cloud = { + ["claude-code"] = { + { id = "v1", email = "team@example.test", plan = "Max", active = true, can_switch = true, windows = { window("Week", 0.4) } }, + { id = "v2", email = "spare@example.test", plan = "Pro", active = false, can_switch = true, windows = {} }, + }, + }, + }) + app:set_state("chat_device", "cloud-f60cde46") + app:frames(10) + expect(app:state("calls")).to_contain("watch_device:cloud") + expect(string.find(app:state("calls"), "watch_device:cloud-f60cde46", 1, true)).to_be(nil) + app:click('role:button "Model"') + app:frames(30) + expect(app:tree("#model-picker-account")).to_contain("team@example.test") + app:click("#model-picker-account") + app:frames(30) + app:click('~"spare@example.test"') + app:frames(30) + expect(app:state("calls")).to_contain("switch_on:cloud:claude-code:v2") +end) + test("a computer whose accounts haven't come has neither, and is asked", function() local app = with_accounts(here(accounts())) app:set_state("chat_device", "somewhere-else") @@ -168,3 +195,34 @@ test("an agent with no accounts has neither", function() app:frames(30) expect(app:has("#model-picker-account")).to_be(false) end) + +-- A line's box (x, y, w, h) in the tree: the first line holding `find`. +local function box_of(app: any, find: string): { y: number, h: number }? + for line in app:tree():gmatch("[^\n]+") do + if line:find(find, 1, true) then + local _, y, _, h = line:match("(%-?[%d%.]+),(%-?[%d%.]+) ([%d%.]+)x([%d%.]+)") + if y then + return { y = tonumber(y) :: number, h = tonumber(h) :: number } + end + end + end + return nil +end + +test("an agent Zeron can't add an account to ends its list at its last account", function() + -- (Claude Code: no "Add … account" action, so no rule and no gap under + -- the last row.) + local app = with_accounts(here(accounts())) + app:click('role:button "Model"') + app:frames(30) + app:click("#model-picker-account") + app:frames(30) + local list = box_of(app, ' listbox "Account"') :: any + local last = box_of(app, ' option "work@example.test') :: any + expect(list).never.to_be_nil() + expect(last).never.to_be_nil() + -- The list's foot is the last row's, give or take the list's own inset. + local under = (list.y + list.h) - (last.y + last.h) + expect(under <= 8).to_be(true) + expect(app:error()).to_be(nil) +end) diff --git a/apps/zgx/ui/tests/model_accounts_providers.test.luau b/apps/zgx/ui/tests/model_accounts_providers.test.luau new file mode 100644 index 000000000..88660d93b --- /dev/null +++ b/apps/zgx/ui/tests/model_accounts_providers.test.luau @@ -0,0 +1,156 @@ +-- The model picker's Account row for an agent that keeps a login per model +-- provider (Pi, OpenCode, Hermes): it is the chosen model's provider's +-- account — "ChatGPT account" for a ChatGPT model, "Claude account" for a +-- Claude one — listing and switching that provider's accounts alone, so +-- switching ChatGPT accounts never touches the Claude one. A provider with +-- no account yet that Zeron can sign in to says None and offers to add one; +-- one Zeron can't add to offers nothing more; a provider with neither has +-- no row. On ui/chat_fixture.luau, its composer reading `agents.on_device` +-- and `agents.logins` as the host publishes them (src/agents.rs). + +local function window(label: string, used: number): any + return { label = label, used = used } +end + +local EFFORT = { { value = "low", label = "Low" }, { value = "high", label = "High" } } +local function provider(id: string, name: string): any + return { id = id, name = name } +end + +local CATALOG = { + state = "ready", + harnesses = { { id = "claude-code", label = "Claude", mark = "claude" }, { id = "pi", label = "Pi", mark = "pi" } }, + models = { + { value = "opus", label = "Opus", harness = "claude-code", efforts = EFFORT, effort = "high" }, + { value = "pi/openai-codex/gpt-6", label = "GPT-6", harness = "pi", provider = provider("openai-codex", "Codex") }, + { value = "pi/anthropic/opus-5", label = "Opus 5", harness = "pi", provider = provider("anthropic", "Anthropic") }, + { value = "pi/github-copilot/gpt-6", label = "GPT-6", harness = "pi", provider = provider("github-copilot", "Copilot") }, + { value = "pi/openrouter/kimi", label = "Kimi", harness = "pi", provider = provider("openrouter", "OpenRouter") }, + { value = "pi/groq/llama", label = "Llama", harness = "pi", provider = provider("groq", "Groq") }, + }, +} + +local function pi_accounts(): { any } + return { + { id = "o1", email = "ada@chatgpt.test", plan = "ChatGPT Plus", active = true, can_switch = true, provider = "openai-codex", group = "ChatGPT", windows = { window("5h", 0.3) } }, + { id = "c1", email = "ada@claude.test", plan = "Claude Max", active = true, can_switch = true, provider = "anthropic", group = "Anthropic", windows = { window("Week", 0.6) } }, + { id = "o2", email = "work@chatgpt.test", plan = "ChatGPT Pro", active = false, can_switch = true, provider = "openai-codex", group = "ChatGPT", windows = { window("5h", 0.05) } }, + } +end + +local LOGINS = { + pi = { + ["openai-codex"] = { name = "ChatGPT", login = "ChatGPT" }, + anthropic = { name = "Anthropic", login = "Claude", key = "Anthropic" }, + ["github-copilot"] = { name = "GitHub Copilot", login = "GitHub Copilot" }, + openrouter = { name = "OpenRouter", key = "OpenRouter" }, + }, +} + +local function with_model(model: string): any + local app = mount("chat_fixture.luau") + app:resize(900, 700) + app:frames(30) + app:set_state("private_text_hidden", false) + app:set_state("chat.catalog", CATALOG) + app:set_state("agents.logins", LOGINS) + app:set_state("agents.on_device", { [""] = { pi = pi_accounts() } }) + app:set_state("chat_model", model) + app:frames(10) + return app +end + +local function open_panel(app: any) + app:click('role:button "Model"') + app:frames(30) +end + +test("a ChatGPT model's row is its ChatGPT account, and lists ChatGPT's alone", function() + local app = with_model("pi/openai-codex/gpt-6") + expect(app:has("#model-picker-usage")).to_be(true) + open_panel(app) + local row = app:tree("#model-picker-account") + expect(row).to_contain("ChatGPT account") + expect(row).to_contain("ada@chatgpt.test") + expect(row).to_contain("30%") + app:click("#model-picker-account") + app:frames(30) + local all = app:tree() + expect(all).to_contain("work@chatgpt.test") + expect(string.find(all, "ada@claude.test", 1, true)).to_be(nil) + -- Another ChatGPT account, added from here. + expect(app:has('"Add ChatGPT account"')).to_be(true) + app:click('~"work@chatgpt.test"') + app:frames(30) + expect(app:state("calls")).to_contain("switch_on::pi:o2") +end) + +test("a Claude model's row is its Anthropic account; switching ChatGPT never touched it", function() + local app = with_model("pi/anthropic/opus-5") + open_panel(app) + local row = app:tree("#model-picker-account") + expect(row).to_contain("Anthropic account") + expect(row).to_contain("ada@claude.test") + expect(row).to_contain("60%") + app:click("#model-picker-account") + app:frames(30) + local all = app:tree() + expect(string.find(all, "work@chatgpt.test", 1, true)).to_be(nil) + -- Another Claude sign-in, from here. + expect(app:has('"Add Claude account"')).to_be(true) +end) + +test("a provider Zeron adds keys for offers its key, on this Mac", function() + local app = with_model("pi/openrouter/kimi") + open_panel(app) + local row = app:tree("#model-picker-account") + expect(row).to_contain("OpenRouter account") + expect(row).to_contain("None") + app:click("#model-picker-account") + app:frames(30) + app:click('"Add OpenRouter API key"') + app:frames(30) + expect(app:state("calls")).to_contain("target:") + expect(app:state("agents_key_request")).to_be("pi:openrouter") +end) + +test("a provider with no account yet says None and offers to add one", function() + local app = with_model("pi/github-copilot/gpt-6") + -- (Nothing in use: no ring.) + expect(app:has("#model-picker-usage")).to_be(false) + open_panel(app) + local row = app:tree("#model-picker-account") + expect(row).to_contain("GitHub Copilot account") + expect(row).to_contain("None") + app:click("#model-picker-account") + app:frames(30) + app:click('"Add GitHub Copilot account"') + app:frames(30) + local calls = app:state("calls") + expect(calls).to_contain("target:") + expect(calls).to_contain("sign_in_to:pi:github-copilot") +end) + +test("a provider with no account and nothing Zeron adds has no row", function() + local app = with_model("pi/groq/llama") + expect(app:has("#model-picker-usage")).to_be(false) + open_panel(app) + expect(app:has("#model-picker-account")).to_be(false) +end) + +test("an agent with one login keeps its plain Account row", function() + local app = with_model("opus") + app:set_state("agents.on_device", { + [""] = { + ["claude-code"] = { + { id = "a1", email = "wing@example.test", plan = "Max", active = true, can_switch = true, windows = { window("5h", 0.34) } }, + }, + }, + }) + app:frames(10) + open_panel(app) + local row = app:tree("#model-picker-account") + expect(row).to_contain("Account") + expect(string.find(row, "ChatGPT", 1, true)).to_be(nil) + expect(row).to_contain("wing@example.test") +end) diff --git a/apps/zgx/ui/tests/model_picker_sources.test.luau b/apps/zgx/ui/tests/model_picker_sources.test.luau new file mode 100644 index 000000000..e6f262033 --- /dev/null +++ b/apps/zgx/ui/tests/model_picker_sources.test.luau @@ -0,0 +1,231 @@ +-- A model's provider beside its name, on every row of an agent that names +-- one (Pi signed in to Codex and OpenCode lists GPT-5.5 from each; Pi with +-- Codex alone still says Codex): quiet, on the name's line, the name fading +-- first when the row runs short. An agent that names no providers says +-- nothing more. On the picker in ui/picker_sources_fixture.luau. + +local function settle(app: any) + app:frames(30) +end + +-- Opened out on the chosen model's agent (Pi). +local function open(app: any) + app:click('role:button "Model"') + settle(app) + app:click(".folded") + settle(app) +end + +-- A text's box (x, y, w, h) inside a row: the row's first line holding it. +local function box(app: any, row: string, text: string): { x: number, y: number, w: number, h: number }? + local inside = false + for line in app:tree():gmatch("[^\n]+") do + if line:find(` option "{row}"`, 1, true) then + inside = true + elseif inside and line:find(" option ", 1, true) then + return nil + elseif inside and line:find(` text "{text}"`, 1, true) then + local x, y, w, h = line:match("(%-?[%d%.]+),(%-?[%d%.]+) ([%d%.]+)x([%d%.]+)") + return { x = tonumber(x) :: number, y = tonumber(y) :: number, w = tonumber(w) :: number, h = tonumber(h) :: number } + end + end + return nil +end +local function row_box(app: any, row: string): { x: number, w: number } + for line in app:tree():gmatch("[^\n]+") do + if line:find(` option "{row}"`, 1, true) then + local x, _, w = line:match("(%-?[%d%.]+),(%-?[%d%.]+) ([%d%.]+)x") + return { x = tonumber(x) :: number, w = tonumber(w) :: number } + end + end + return { x = -1, w = -1 } +end + +local LONG = "GPT-5.5 Codex Max Preview Extended Context" + +test("every model an agent names a provider for says it, and only those", function() + local app = mount("picker_sources_fixture.luau") + app:resize(600, 700) + settle(app) + open(app) + -- Pi's GPT-5.5 from each provider: each says which. + expect(app:has('role:option "GPT-5.5 Codex" >> "Codex"')).to_be(true) + expect(app:has('role:option "GPT-5.5 OpenCode" >> "OpenCode"')).to_be(true) + -- A name one provider has says its provider too: Pi reaches several. + expect(app:has('role:option "GPT-5.5 mini Codex" >> "Codex"')).to_be(true) + expect(app:has('role:option "Big Pickle OpenCode" >> "OpenCode"')).to_be(true) + -- Quiet words of the name's size, on its line, the row's gap after it. + local name = box(app, "GPT-5.5 Codex", "GPT-5.5") :: any + local hint = box(app, "GPT-5.5 Codex", "Codex") :: any + expect(name).never.to_be_nil() + expect(hint).never.to_be_nil() + expect(hint.y).to_be(name.y) + expect(hint.h).to_be(name.h) + expect(hint.x - (name.x + name.w)).to_be(8) + + -- An agent with no providers: none, though its GPT-5.5 shares Pi's name + -- (its tab already says whose it is). + app:click('role:tab "Claude"') + settle(app) + expect(app:has('role:option "GPT-5.5"')).to_be(true) + expect(app:has('role:option "Opus"')).to_be(true) + + -- Starred, a row reads as it does on its agent's tab. + app:set_state("test_picker_favorites", { ["pi/openai-codex/gpt-5.5"] = true, ["pi/opencode/big-pickle"] = true }) + app:click('role:tab "Starred"') + settle(app) + expect(app:has('role:option "GPT-5.5 Codex" >> "Codex"')).to_be(true) + expect(app:has('role:option "Big Pickle OpenCode" >> "OpenCode"')).to_be(true) + + -- OpenCode signed out (its models gone from the catalog), in place: Pi + -- has one provider now, and its rows still say it. + local models = app:state("test_picker_models") :: { any } + local kept = {} + for _, m in models do + if not (m.provider and m.provider.id == "opencode") then + table.insert(kept, m) + end + end + app:set_state("test_picker_models", kept) + settle(app) + expect(app:has('role:option "GPT-5.5 Codex" >> "Codex"')).to_be(true) + expect(app:has('role:option ~"OpenCode"')).to_be(false) + expect(app:error()).to_be(nil) +end) + +test("a search finds models by their provider, and says it on each row", function() + local app = mount("picker_sources_fixture.luau") + app:resize(600, 700) + settle(app) + open(app) + app:type('role:textbox "Search"', "opencode") + settle(app) + -- OpenCode's: each row says what it was found by. + expect(app:has('role:option "GPT-5.5 OpenCode" >> "OpenCode"')).to_be(true) + expect(app:has('role:option "Big Pickle OpenCode" >> "OpenCode"')).to_be(true) + expect(app:has(`role:option "{LONG} OpenCode"`)).to_be(true) + -- Codex's are gone. + expect(app:has('role:option ~"GPT-5.5 mini"')).to_be(false) + expect(app:has('role:option "GPT-5.5 Codex"')).to_be(false) + expect(app:has(`role:option "{LONG} Codex"`)).to_be(false) + + -- A name and a provider read together. + app:fill('role:textbox "Search"', "gpt-5.5 codex") + settle(app) + expect(app:has('role:option "GPT-5.5 Codex"')).to_be(true) + expect(app:has('role:option "GPT-5.5 OpenCode"')).to_be(false) + + -- Found by its name, a row says what it did: its provider, as every + -- row of an agent with several does. + app:fill('role:textbox "Search"', "pickle") + settle(app) + expect(app:has('role:option "Big Pickle OpenCode" >> "OpenCode"')).to_be(true) + + -- A provider is found from a word's start, not inside one ("pen" is + -- in OpenCode, but starts none of its words); "code" starts its second. + app:fill('role:textbox "Search"', "pen") + settle(app) + expect(app:count("role:option")).to_be(0) + app:fill('role:textbox "Search"', "code") + settle(app) + expect(app:has('role:option "Big Pickle OpenCode"')).to_be(true) + + -- An agent with no providers is searched by name alone. + app:click('role:tab "Claude"') + app:fill('role:textbox "Search"', "codex") + settle(app) + expect(app:count("role:option")).to_be(0) + expect(app:error()).to_be(nil) +end) + +test("a line past its row fades at its right edge, and glides to its end while highlighted", function() + local app = mount("picker_sources_fixture.luau") + app:resize(600, 700) + settle(app) + open(app) + local row = `{LONG} Codex` + local function ends(): (number, number) + local r = row_box(app, row) + local hint = box(app, row, "Codex") :: any + return hint.x + hint.w, r.x + r.w + end + -- At rest the line runs past the row: its end (the provider) is out of + -- sight under the fade, not squeezed in. + local hint_end, row_end = ends() + expect(hint_end > row_end).to_be(true) + -- Highlighted, it glides left until its end shows. + app:hover(`role:option "{row}"`) + app:frames(240) + hint_end, row_end = ends() + expect(hint_end <= row_end).to_be(true) + -- Off it, it's back where it started. + app:hover('role:option "GPT-5.5 Codex"') + app:frames(30) + hint_end, row_end = ends() + expect(hint_end > row_end).to_be(true) + -- With motion reduced it stays put. + app:set_state("motion_reduce", true) + app:hover(`role:option "{row}"`) + app:frames(240) + hint_end, row_end = ends() + expect(hint_end > row_end).to_be(true) + -- A short row that fits never moves. + local short = box(app, "GPT-5.5 Codex", "Codex") :: any + app:set_state("motion_reduce", false) + app:hover('role:option "GPT-5.5 Codex"') + app:frames(240) + expect((box(app, "GPT-5.5 Codex", "Codex") :: any).x).to_be(short.x) + expect(app:error()).to_be(nil) +end) + +test("the keys pick a namesake by its provider", function() + local app = mount("picker_sources_fixture.luau") + app:resize(600, 700) + settle(app) + open(app) + app:type('role:textbox "Search"', "opencode") + settle(app) + -- The first found, OpenCode's GPT-5.5, highlighted: Enter picks it. + app:key("Enter") + settle(app) + expect(app:state("test_picker_model")).to_be("pi/opencode/gpt-5.5") + -- Opened again, folded onto it: its row says which it is. + if not app:has('role:option ~"GPT-5.5"') then + app:click('role:button "Model"') + settle(app) + end + expect(app:has('role:option "GPT-5.5 OpenCode" >> "OpenCode"')).to_be(true) + -- Down from it, then Enter: the next row (Pi's list order). + app:click(".folded") + settle(app) + app:key("ArrowDown") + app:key("Enter") + settle(app) + expect(app:state("test_picker_model")).to_be("pi/openai-codex/gpt-5.5-mini") + expect(app:error()).to_be(nil) +end) + +test("a row gains its provider in place as the catalog names it", function() + local app = mount("picker_sources_fixture.luau") + app:resize(600, 700) + -- An older engine's catalog first: no providers. + local models = app:state("test_picker_models") :: { any } + local bare = {} + for _, m in models do + local c = table.clone(m) + c.provider = nil + table.insert(bare, c) + end + app:set_state("test_picker_models", bare) + settle(app) + open(app) + expect(app:has('role:option "GPT-5.5"')).to_be(true) + expect(app:has('role:option ~"GPT-5.5" >> "Codex"')).to_be(false) + -- Then one naming them, the panel open: every row says its provider. + app:set_state("test_picker_models", models) + settle(app) + expect(app:has('role:option "GPT-5.5 Codex" >> "Codex"')).to_be(true) + expect(app:has('role:option "GPT-5.5 OpenCode" >> "OpenCode"')).to_be(true) + expect(app:has('role:option "Big Pickle OpenCode" >> "OpenCode"')).to_be(true) + expect(app:error()).to_be(nil) +end) diff --git a/apps/zgx/ui/tests/plugin_compose_replace.test.luau b/apps/zgx/ui/tests/plugin_compose_replace.test.luau new file mode 100644 index 000000000..e91e12e8a --- /dev/null +++ b/apps/zgx/ui/tests/plugin_compose_replace.test.luau @@ -0,0 +1,54 @@ +-- What a plugin allowed "compose" puts in a chat's draft +-- (`zeron.compose(text, opts)`, handed on by screens/plugins as the host +-- asks it): after what's there, or in place of its words with its chips +-- kept (`replace`), in the chat shown or another (`session`), never sent. +-- On the shell in ui/shell_fixture.luau, the host's asks made here. + +local seq = 0 +local function ask(app: any, value: any) + seq += 1 + app:set_state("plugins.request", { { seq = 1000 + seq, kind = "compose", title = "", value = value } }) + app:frames(10) +end + +local function open(): any + seq = 0 + local app = mount("shell_fixture.luau") + app:resize(1400, 800) + app:set_state("shell_fixture.plugins", true) + app:frames(30) + app:click('#shell-sidebar >> role:button "Fix the build"') + app:frames(30) + return app +end + +local BOX = "#chat-composer >> role:textbox" + +test("a plugin's words replace the draft's, or follow them on a line of their own", function() + local app = open() + app:type(BOX, "fix teh bulid pls") + app:frames(5) + ask(app, { text = "Please fix the build.", replace = true }) + expect(app:text(BOX)).to_be("Please fix the build.") + ask(app, { text = "It fails on main." }) + expect(app:text(BOX)).to_be("Please fix the build.\nIt fails on main.") + -- Words alone, as ever: after what's there. + ask(app, "Thanks.") + expect(app:text(BOX)).to_be("Please fix the build.\nIt fails on main.\nThanks.") + -- Nothing sent. + expect(app:state("calls")).never.to_contain("send:a1") +end) + +test("a plugin's words go in another chat's draft, which shows them when it's opened", function() + local app = open() + app:type(BOX, "here, untouched") + app:frames(5) + ask(app, { text = "for the docs", replace = true, session = "a2" }) + expect(app:text(BOX)).to_be("here, untouched") + app:click('#shell-sidebar >> role:button "Write the docs"') + app:frames(30) + expect(app:text(BOX)).to_be("for the docs") + app:click('#shell-sidebar >> role:button "Fix the build"') + app:frames(30) + expect(app:text(BOX)).to_be("here, untouched") +end) diff --git a/apps/zgx/ui/tests/plugin_draft_read.test.luau b/apps/zgx/ui/tests/plugin_draft_read.test.luau new file mode 100644 index 000000000..76e9bc044 --- /dev/null +++ b/apps/zgx/ui/tests/plugin_draft_read.test.luau @@ -0,0 +1,49 @@ +-- The composer's draft as plugins read it (`zeron.draft`, "draft"): written +-- only while a plugin that's on may read it, so with none no key typed +-- copies the draft for no one; with one, it follows what's typed, its chat +-- and its chips by kind and name. On the shell in ui/shell_fixture.luau. + +local function open(): any + local app = mount("shell_fixture.luau") + app:resize(1400, 800) + app:set_state("shell_fixture.plugins", true) + app:frames(30) + app:click('#shell-sidebar >> role:button "Fix the build"') + app:frames(30) + return app +end + +local function with_plugin(app: any, status: string) + app:set_state("plugins", { + state = "ready", + list = { { id = "stash", name = "Stash", status = status, permissions = { "ui.add", "draft" }, allowed = { "ui.add", "draft" } } }, + }) + app:frames(5) +end + +test("with no plugin that reads the draft, typing publishes nothing", function() + local app = open() + app:type("#chat-composer >> role:textbox", "a private thought") + app:frames(5) + expect(app:state("zeron.draft")).to_be_nil() + -- One that's off reads nothing either. + with_plugin(app, "off") + app:type("#chat-composer >> role:textbox", "still private") + app:frames(5) + expect(app:state("zeron.draft")).to_be_nil() +end) + +test("with a plugin on that reads the draft, it follows what's typed, and goes with the plugin", function() + local app = open() + with_plugin(app, "on") + app:type("#chat-composer >> role:textbox", "first words") + app:frames(5) + local d = app:state("zeron.draft") + expect(d).never.to_be_nil() + expect(d.text).to_be("first words") + expect(type(d.session)).to_be("string") + expect(#d.attachments).to_be(0) + -- Turned off: nothing kept out for it. + with_plugin(app, "off") + expect(app:state("zeron.draft")).to_be_nil() +end) diff --git a/apps/zgx/ui/tests/provider_groups.test.luau b/apps/zgx/ui/tests/provider_groups.test.luau new file mode 100644 index 000000000..bcebda263 --- /dev/null +++ b/apps/zgx/ui/tests/provider_groups.test.luau @@ -0,0 +1,309 @@ +-- Settings → Providers for an agent that keeps a login per model provider +-- (Pi, OpenCode, Hermes): the same card as Claude Code's and Codex's — a +-- row per account (a provider's together, its plan line saying whose), the +-- one in use marked per provider, and every add row at the foot ("Add +-- ChatGPT account", "Add Claude account", …, "Add API key"). A sign-in or a +-- key takes its add row's place; a key is typed on this Mac only and never +-- shown again; a switch moves the one in use within its provider alone; +-- Hermes' own pool has no actions. On ui/provider_groups_fixture.luau. + +local PAGE = "#page" +local KEY = "sk-good-ZEROTESTsecret-WXYZ" + +local function settle(app: any) + app:frames(30) +end + +local function open(): any + local app = mount("provider_groups_fixture.luau") + app:resize(900, 2600) + settle(app) + return app +end + +local function shows(app: any, scope: string, text: string): boolean + return app:has(scope) and string.find(app:tree(scope), text, 1, true) ~= nil +end + +-- Whether the key dialog is open (a closed one stays in the tree, hidden, +-- as it leaves: a test host's frames pass no time). +local function key_dialog_open(app: any): boolean + local line = app:tree():match('[^\n]*dialog "Add API key"[^\n]*') + return line ~= nil and line:find(" hidden", 1, true) == nil +end + +-- A node's line in the tree (`kind "label"` under `scope`), shown (not +-- leaving, hidden): nil if there's none. +local function line_of(app: any, scope: string, kind: string, label: string): string? + for line in (if scope == "" then app:tree() else app:tree(scope)):gmatch("[^\n]+") do + if line:find(` {kind} "{label}"`, 1, true) and not line:find(" hidden", 1, true) then + return line + end + end + return nil +end + +local function in_use(app: any, row: string): boolean + return shows(app, `#account-row-{row}`, "In use") +end + +-- The rows' ids under `scope`, top to bottom (`#account-row-`, +-- `#account-add-…`). +local function order(app: any, scope: string): { string } + local out = {} + for line in app:tree(scope):gmatch("[^\n]+") do + local id = line:match("#account%-row%-([%w%-]+)") or line:match("#(account%-add%-[%w%-]+)") + if id then + table.insert(out, id) + end + end + return out +end + +test("a per-provider agent's card is Claude Code's card: its accounts, a provider's together, then every add row", function() + local app = open() + local pi = order(app, PAGE) + -- (From Pi's first row on.) + local from = table.find(pi, "o1") :: number + local rows = table.move(pi, from, from + 10, 1, {}) + expect(table.concat(rows, ",")).to_be( + "o1,o2,o3,c1,k9,account-add-pi-openai-codex,account-add-pi-anthropic,account-add-pi-github-copilot,account-add-key-pi,h1,h2" + ) + -- Whose each is, on its plan line, as any account's plan. + expect(shows(app, "#account-row-o1", "ChatGPT Plus")).to_be(true) + expect(shows(app, "#account-row-c1", "Claude Max")).to_be(true) + -- One in use per provider. + expect(in_use(app, "o1")).to_be(true) + expect(in_use(app, "o2")).to_be(false) + expect(in_use(app, "c1")).to_be(true) + expect(app:has('#account-add-pi-openai-codex >> role:button "Add ChatGPT account"')).to_be(true) + expect(app:has('#account-add-pi-anthropic >> role:button "Add Claude account"')).to_be(true) + expect(app:has('#account-add-key-pi >> role:button "Add API key"')).to_be(true) + -- No section chrome, no CLI hints. + expect(string.find(app:tree(PAGE), "2 accounts", 1, true)).to_be(nil) + expect(app:has("#account-group-pi-openai-codex")).to_be(false) + expect(string.find(app:tree(PAGE), "/login", 1, true)).to_be(nil) +end) + +test("an add row's sign-in takes its place, the others standing", function() + local app = open() + app:click('#account-add-pi-openai-codex >> role:button "Add ChatGPT account"') + settle(app) + expect(app:state("groups_calls")).to_contain("sign_in_to:pi:openai-codex") + expect(shows(app, "#account-add-pi-openai-codex", "Signing in to ChatGPT")).to_be(true) + expect(app:has('#account-add-pi-anthropic >> role:button "Add Claude account"')).to_be(true) + app:click('#account-add-pi-openai-codex >> role:button "Cancel"') + settle(app) + expect(app:state("groups_calls")).to_contain("cancel:pi") + expect(app:has('#account-add-pi-openai-codex >> role:button "Add ChatGPT account"')).to_be(true) +end) + +test("a provider's first account joins the list, in use for its provider alone", function() + local app = open() + app:click('#account-add-pi-github-copilot >> role:button "Add GitHub Copilot account"') + settle(app) + expect(app:state("groups_calls")).to_contain("sign_in_to:pi:github-copilot") + expect(shows(app, "#account-add-pi-github-copilot", "Signing in to GitHub Copilot")).to_be(true) + app:command("groups.copilot_lands") + settle(app) + expect(shows(app, "#account-row-g1", "octo")).to_be(true) + expect(in_use(app, "g1")).to_be(true) + expect(in_use(app, "o1")).to_be(true) + expect(in_use(app, "c1")).to_be(true) + expect(app:has('#account-add-pi-github-copilot >> role:button "Add GitHub Copilot account"')).to_be(true) +end) + +test("Add API key opens a dialog: a provider select, the key; Save waits for a key; a refused key says why and stays", function() + local app = open() + app:click('#account-add-key-pi >> role:button "Add API key"') + settle(app) + local dialog = "#key-dialog-pi" + expect(key_dialog_open(app)).to_be(true) + -- The first provider Pi has no key for yet, chosen. + expect(shows(app, dialog .. ' >> role:button "Provider"', "Anthropic")).to_be(true) + expect(shows(app, 'role:dialog "Add API key"', "Pi uses this key for Anthropic models.")).to_be(true) + -- Nothing typed: Save waits. + expect((line_of(app, 'role:dialog "Add API key"', "button", "Save") or ""):find("disabled", 1, true) ~= nil).to_be(true) + -- Every provider Pi takes a key for, in the select. + app:click(dialog .. ' >> role:button "Provider"') + settle(app) + for _, name in { "Anthropic", "OpenAI", "OpenRouter", "Google Gemini", "xAI", "DeepSeek" } do + expect(app:has(`role:menuitem "{name}"`)).to_be(true) + end + app:key("Escape") + settle(app) + local field = dialog .. ' >> role:textbox "API key"' + app:type(field, "sk-bad-0000") + app:click('role:button "Save"') + settle(app) + expect(app:state("groups_calls")).to_contain("add_key:pi:anthropic:refused") + expect(key_dialog_open(app)).to_be(true) + expect(shows(app, dialog, "Anthropic didn't accept that key")).to_be(true) +end) + +test("while a key is checked, Save spins and the inputs hold still", function() + local app = open() + app:click('#account-add-key-pi >> role:button "Add API key"') + settle(app) + app:type('#key-dialog-pi >> role:textbox "API key"', "sk-slow-0000") + app:key("Enter") + settle(app) + expect(app:state("groups_calls")).to_contain("add_key:pi:anthropic:checking") + expect(key_dialog_open(app)).to_be(true) + -- (The provider holds still while its key is checked.) + expect((line_of(app, "#key-dialog-pi", "button", "Provider") or ""):find("disabled", 1, true) ~= nil).to_be(true) + -- Nothing closes it meanwhile: the key it's checking is kept if it + -- passes. Cancel waits; Escape too. + expect((line_of(app, 'role:dialog "Add API key"', "button", "Cancel") or ""):find("disabled", 1, true) ~= nil).to_be(true) + app:key("Escape") + settle(app) + expect(key_dialog_open(app)).to_be(true) +end) + +test("a key that's taken closes the dialog and lists by its default name, the key itself nowhere", function() + local app = open() + app:click('#account-add-key-pi >> role:button "Add API key"') + settle(app) + app:click('#key-dialog-pi >> role:button "Provider"') + settle(app) + app:click('role:menuitem "OpenRouter"') + settle(app) + app:type('#key-dialog-pi >> role:textbox "API key"', KEY) + app:key("Enter") + app:frames(60) + expect(app:state("groups_calls")).to_contain("add_key:pi:openrouter:ok") + expect(key_dialog_open(app)).to_be(false) + local row = "#account-row-key-openrouter-WXYZ" + -- Unnamed: "API key" and its last four, over its provider. + expect(shows(app, row, "API key ···WXYZ")).to_be(true) + expect(shows(app, row, "OpenRouter")).to_be(true) + expect(shows(app, row, "OpenRouter · API key")).to_be(false) + -- Its face is its provider's mark, not a person's: logins keep theirs. + expect(shows(app, row, '"Account"')).to_be(false) + expect(shows(app, "#account-row-o1", '"Account"')).to_be(true) + expect(in_use(app, "key-openrouter-WXYZ")).to_be(true) + -- (A key has no plan: no meters on its row.) + expect(shows(app, row, "Session")).to_be(false) + expect(string.find(app:tree(), "ZEROTESTsecret", 1, true)).to_be(nil) + expect(string.find(app:state("groups_calls"), "ZEROTEST", 1, true)).to_be(nil) + -- Opened again: nothing typed is kept. + app:click('#account-add-key-pi >> role:button "Add API key"') + settle(app) + expect(string.find(app:tree(), "ZEROTESTsecret", 1, true)).to_be(nil) +end) + +test("a key named as it's added, a second of one provider its own row, and a rename with no key asked", function() + local app = open() + local function add(key: string, name: string?) + app:click('#account-add-key-pi >> role:button "Add API key"') + settle(app) + app:click('#key-dialog-pi >> role:button "Provider"') + settle(app) + app:click('role:menuitem "OpenRouter"') + settle(app) + app:type('#key-dialog-pi >> role:textbox "API key"', key) + if name then + app:type('#key-dialog-pi >> role:textbox "Name (optional)"', name) + end + app:click('role:button "Save"') + app:frames(60) + end + add("sk-good-one-AAAA", "Work") + add("sk-good-two-BBBB", nil) + -- Named: its name over "OpenRouter · API key", the last four nowhere. + expect(shows(app, "#account-row-key-openrouter-AAAA", "Work")).to_be(true) + expect(shows(app, "#account-row-key-openrouter-AAAA", "OpenRouter · API key")).to_be(true) + expect(shows(app, "#account-row-key-openrouter-AAAA", "···AAAA")).to_be(false) + -- Unnamed: "API key ···BBBB" over its provider. + expect(shows(app, "#account-row-key-openrouter-BBBB", "API key ···BBBB")).to_be(true) + -- Two keys of one provider: two rows, one in use. + expect(in_use(app, "key-openrouter-AAAA")).to_be(true) + expect(in_use(app, "key-openrouter-BBBB")).to_be(false) + -- Renamed from its menu: just its name. + app:click('#account-row-key-openrouter-BBBB >> role:button "Account actions"') + settle(app) + app:click('"Rename"') + settle(app) + local field = '#rename-dialog-pi >> role:textbox "Name"' + expect(app:has(field)).to_be(true) + expect(app:has('#rename-dialog-pi >> role:textbox "API key"')).to_be(false) + -- A name holding part of a key: refused, said why, still open. + app:key("cmd+a") + app:type(field, "my sk-good key") + app:click('role:button "Save"') + settle(app) + expect(shows(app, "#rename-dialog-pi", "looks like a key")).to_be(true) + app:key("cmd+a") + app:type(field, "Personal") + app:click('role:button "Save"') + app:frames(60) + expect(app:state("groups_calls")).to_contain("rename:pi:key-openrouter-BBBB:Personal") + expect(shows(app, "#account-row-key-openrouter-BBBB", "Personal")).to_be(true) + -- (Logins aren't renamed: no Rename in their menu.) + app:click('#account-row-o1 >> role:button "Account actions"') + settle(app) + expect(line_of(app, PAGE, "menuitem", "Rename") == nil and line_of(app, "", "menuitem", "Rename") == nil).to_be(true) +end) + +test("another device's agents take sign-ins, never keys", function() + local app = open() + app:command("groups.remote") + settle(app) + expect(app:has("#account-add-key-pi")).to_be(false) + expect(app:has('#account-add-pi-anthropic >> role:button "Add Claude account"')).to_be(true) +end) + +test("switching a ChatGPT account moves the one in use within ChatGPT alone", function() + local app = open() + app:click('#account-row-o2 >> role:button "Account actions"') + settle(app) + app:click('"Switch to this account"') + settle(app) + expect(app:state("groups_calls")).to_contain("switch:pi:o2") + expect(in_use(app, "o2")).to_be(true) + expect(in_use(app, "o1")).to_be(false) + expect(in_use(app, "c1")).to_be(true) +end) + +test("Switch is offered only to an account that can be put in use and isn't; a refusal is said", function() + local app = open() + -- In use already: no Switch. + app:click('#account-row-o1 >> role:button "Account actions"') + settle(app) + expect(line_of(app, "", "menuitem", "Switch to this account")).to_be(nil) + app:key("Escape") + settle(app) + -- Refused by the engine: a toast says why. + app:click('#account-row-o3 >> role:button "Account actions"') + settle(app) + app:click('"Switch to this account"') + settle(app) + expect(app:state("groups_calls")).to_contain("switch:pi:o3") + expect(app:has('"Couldn\'t switch accounts"')).to_be(true) + expect(app:has('~"no longer exists"')).to_be(true) +end) + +test("Hermes' own pool is read-only, its add rows Hermes' own sign-ins and keys", function() + local app = open() + expect(in_use(app, "h1")).to_be(true) + expect(app:has('#account-row-h1 >> role:button "Account actions"')).to_be(false) + -- From the environment: never titled by its variable. + expect(shows(app, "#account-row-h3", "API key ···9f3e")).to_be(true) + expect(shows(app, "#account-row-h3", "OpenRouter · from environment")).to_be(true) + expect(shows(app, "#account-row-h3", "OPENROUTER_API_KEY")).to_be(false) + expect(app:has('#account-add-hermes-nous >> role:button "Add Nous Portal account"')).to_be(true) + expect(app:has('#account-add-hermes-xai-oauth >> role:button "Add xAI account"')).to_be(true) + expect(app:has('#account-add-key-hermes >> role:button "Add API key"')).to_be(true) + app:click('#account-add-hermes-nous >> role:button "Add Nous Portal account"') + settle(app) + expect(app:state("groups_calls")).to_contain("sign_in_to:hermes:nous") +end) + +test("an agent with one login looks as it always has", function() + local app = open() + expect(app:has("#account-add-key-claude-code")).to_be(false) + expect(shows(app, PAGE, "bo@example.com")).to_be(true) + -- (Claude Code's and Codex's foot: "Add account", as ever.) + local _, n = string.gsub(app:tree(PAGE), 'button "Add account"', "") + expect(n).to_be(2) +end) diff --git a/apps/zgx/ui/tests/providers_cloud.test.luau b/apps/zgx/ui/tests/providers_cloud.test.luau new file mode 100644 index 000000000..b6b696335 --- /dev/null +++ b/apps/zgx/ui/tests/providers_cloud.test.luau @@ -0,0 +1,77 @@ +-- Settings → Providers offers Cloud as one more choice after the computers, +-- while Cloud is on: its agents' accounts (the vault's, every Cloud machine +-- uses them), with no switch, no settings and nothing to install, and API +-- keys to save for it. Without Cloud, no such choice. On the shell in +-- ui/shell_fixture.luau, Cloud from ui/cloud_stub.luau. + +local PAGE = "#settings-page" +local NAV = "#settings-nav" + +local function shows(app: any, scope: string, text: string): boolean + return app:tree(scope):find(text, 1, true) ~= nil +end + +local function asked(app: any, entry: string): boolean + for _, c in (app:state("settings_stub_calls") :: any) or {} do + if c == entry then + return true + end + end + return false +end + +local function open(with_cloud: boolean): any + local app = mount("shell_fixture.luau") + app:resize(1200, 900) + app:frames(30) + app:command("settings_stub.sign_in") + if with_cloud then + app:command("cloud_stub.offer") + end + app:command("shell.settings") + app:frames(20) + app:click(`{NAV} >> role:tab "Providers"`) + app:frames(30) + return app +end + +test("with Cloud on, Providers offers Cloud: its agents' accounts, no switch or settings, and its API keys", function() + local app = open(true) + app:click(`{PAGE} >> role:button "Device"`) + app:frames(10) + expect(app:has('role:menuitem "Cloud"')).to_be(true) + app:click('role:menuitem "Cloud"') + app:frames(30) + expect(asked(app, "agents.target:cloud")).to_be(true) + expect(shows(app, PAGE, "Claude Code")).to_be(true) + expect(shows(app, PAGE, "Codex")).to_be(true) + expect(shows(app, PAGE, "ada@example.com")).to_be(true) + -- Nothing to switch, set or install: its accounts alone. + expect(app:has(`{PAGE} >> role:switch "Codex on"`)).to_be(false) + expect(app:has(`{PAGE} >> role:button "Codex settings"`)).to_be(false) + expect(shows(app, PAGE, "Add another agent")).to_be(false) + -- Its API keys, saved for Cloud. + expect(shows(app, PAGE, "Anthropic API key")).to_be(true) + expect(shows(app, PAGE, "OpenAI API key")).to_be(true) + app:type(`{PAGE} >> role:textbox "OpenAI API key"`, "sk-test-123") + app:frames(5) + app:click(`{PAGE} >> role:button "Save" [2]`) + app:frames(10) + expect(asked(app, "agents.cloud_key")).to_be(true) + expect(app:error()).to_be_nil() + -- Back to this computer: its agents as they were, with their switches. + app:click(`{PAGE} >> role:button "Device"`) + app:frames(10) + app:click('role:menuitem "MacBook Pro"') + app:frames(30) + expect(asked(app, "agents.target:")).to_be(true) + expect(app:has(`{PAGE} >> role:switch "Claude Code on"`)).to_be(true) + expect(shows(app, PAGE, "Anthropic API key")).to_be(false) +end) + +test("without Cloud, Providers offers no Cloud", function() + local app = open(false) + app:click(`{PAGE} >> role:button "Device"`) + app:frames(10) + expect(app:has('role:menuitem "Cloud"')).to_be(false) +end) diff --git a/apps/zgx/ui/tests/reduce_motion.test.luau b/apps/zgx/ui/tests/reduce_motion.test.luau index 8a7ca7ead..862e90e29 100644 --- a/apps/zgx/ui/tests/reduce_motion.test.luau +++ b/apps/zgx/ui/tests/reduce_motion.test.luau @@ -133,3 +133,44 @@ test("with motion reduced, a send's prompt lands at the top without gliding", fu expect(rest < 120).to_be(true) expect(between <= 1).to_be(true) end) + +-- A switch's knob, left of its track (`x` from its line): off at the +-- track's inset, on across it. +local function knob_x(app: any, scope: string): (number, number) + local lines = {} + for line in app:tree(scope):gmatch("[^\n]+") do + table.insert(lines, line) + end + local track = tonumber(lines[1]:match(" (%-?%d+),%-?%d+ %d+x%d+")) or -1 + local knob = tonumber((lines[#lines] or ""):match(" (%-?%d+),%-?%d+ %d+x%d+")) or -1 + return knob - track, #lines +end + +test("with motion reduced, a switch built on stands its knob on the right", function() + local app = mount("shell_fixture.luau") + app:resize(1200, 900) + app:frames(30) + app:command("settings_stub.sign_in") + app:command("shell.settings") + app:frames(20) + app:click('#settings-nav >> role:tab "Appearance"') + app:frames(30) + local reduce = '#settings-page >> role:switch "Reduce motion"' + local off = knob_x(app, reduce) + app:click(reduce) + app:frames(30) + local on = knob_x(app, reduce) + expect(on > off).to_be(true) + -- Away and back: the page builds again, now with motion reduced. + app:click('#settings-nav >> role:tab "General"') + app:frames(20) + app:click('#settings-nav >> role:tab "Appearance"') + app:frames(20) + expect(app:tree(reduce)).never.to_contain("unchecked") + expect(knob_x(app, reduce)).to_be(on) + -- And it still moves: off at once, back where it started. + app:click(reduce) + app:frames(2) + expect(app:tree(reduce)).to_contain("unchecked") + expect(knob_x(app, reduce)).to_be(off) +end) diff --git a/apps/zgx/ui/tests/shell_in_place.test.luau b/apps/zgx/ui/tests/shell_in_place.test.luau index 5a8297f64..e7cf8e478 100644 --- a/apps/zgx/ui/tests/shell_in_place.test.luau +++ b/apps/zgx/ui/tests/shell_in_place.test.luau @@ -463,6 +463,39 @@ test("settings is a page of its own, and the chats come back as they were", func -- And forward opens settings again. app:command("router.forward") app:frames(20) + expect(app:state("shell_route_path")).to_be("/settings/archived") +end) + +test("settings open again on the page shown last, your profile aside", function() + local app = open() + app:command("shell.settings") + app:frames(20) + expect(app:state("shell_route_path")).to_be("/settings/general") + app:click('#settings-nav >> "Archived"') + app:frames(20) + expect(app:state("shell_route_path")).to_be("/settings/archived") + + app:click('#settings-nav >> "Back to chats"') + app:frames(20) + expect(app:state("shell_route_path")).to_be("/") + app:command("shell.settings") + app:frames(20) + expect(app:state("shell_route_path")).to_be("/settings/archived") + + app:click('#settings-nav >> "Account"') + app:frames(20) + expect(app:state("shell_route_path")).to_be("/settings/profile") + app:key("Escape") + app:frames(20) + app:command("shell.settings") + app:frames(20) + expect(app:state("shell_route_path")).to_be("/settings/archived") + + app:key("Escape") + app:frames(20) + app:set_state("shell_settings_page", "gone") + app:command("shell.settings") + app:frames(20) expect(app:state("shell_route_path")).to_be("/settings/general") end) diff --git a/apps/zgx/ui/tests/tool_pictures.test.luau b/apps/zgx/ui/tests/tool_pictures.test.luau new file mode 100644 index 000000000..563f484b5 --- /dev/null +++ b/apps/zgx/ui/tests/tool_pictures.test.luau @@ -0,0 +1,72 @@ +-- A tool whose result carried a picture (a Read of a screenshot: the +-- engine's copy, `previewPaths`) opens to it as a small thumbnail, its own +-- shape within the theme's 240 by 160 (`zeron.prose.picture.thumb`), never +-- the reading column's width; a click opens it in the lightbox. Several sit +-- in a row. A Read that kept none opens to nothing of the kind +-- (ui/tool_pictures_fixture.luau). + +local function work(): any + local app = mount("tool_pictures_fixture.luau") + app:resize(900, 900) + app:frames(10) + expect(app:error()).to_be_nil() + -- (Settled work folds to its line: open it.) + app:click('role:button "Read 2 files · ran 1 command"') + app:frames(30) + return app +end + +-- A node's place and size in the tree, by a pattern on its line. +local function box(app: any, pattern: string): (number?, number?, number?, number?) + for line in app:tree():gmatch("[^\n]+") do + if line:find(pattern, 1, true) then + local x, y, w, h = line:match("(%-?[%d%.]+),(%-?[%d%.]+) ([%d%.]+)x([%d%.]+)") + if x then + return tonumber(x), tonumber(y), tonumber(w), tonumber(h) + end + end + end + return nil +end + +test("a read whose result kept a picture opens to a thumbnail of it, and it opens in the lightbox", function() + local app = work() + expect(app:has('"Open test.png"')).to_be(false) + app:click('role:button "Read test.png"') + app:frames(30) + expect(app:error()).to_be_nil() + expect(app:has('"Open test.png"')).to_be(true) + -- (868 by 617: as tall as the thumbnail allows, its shape kept.) + local _, _, w, h = box(app, '"Open test.png"') + expect(w).never.to_be_nil() + expect(h <= 160.5).to_be(true) + expect(w <= 240.5).to_be(true) + expect(math.abs(w / h - 868 / 617) < 0.02).to_be(true) + app:click('"Open test.png"') + app:frames(60) + local open = app:state("ds/lightbox.luau::open") + expect(open).never.to_be_nil() + expect(open.items[open.index].src).to_be("assets/composer/shell.png") +end) + +test("several pictures are thumbnails side by side", function() + local app = work() + app:click('role:button "Ran shoot both"') + app:frames(30) + expect(app:error()).to_be_nil() + local lx, ly, lw, lh = box(app, '"Open left.png"') + local rx, ry = box(app, '"Open right.png"') + expect(lx).never.to_be_nil() + expect(rx).never.to_be_nil() + expect(ly).to_be(ry) + expect(rx > lx + lw - 0.5).to_be(true) + expect(lh <= 160.5).to_be(true) +end) + +test("a read that kept no picture shows none", function() + local app = work() + app:click('role:button "Read old.png"') + app:frames(30) + expect(app:error()).to_be_nil() + expect(app:has('"Open old.png"')).to_be(false) +end) diff --git a/apps/zgx/ui/tests/transcript_scroll_away.test.luau b/apps/zgx/ui/tests/transcript_scroll_away.test.luau new file mode 100644 index 000000000..a4dddd99a --- /dev/null +++ b/apps/zgx/ui/tests/transcript_scroll_away.test.luau @@ -0,0 +1,84 @@ +-- Scrolled away from the end, the view stays where the person took it: it +-- isn't pulled back to the end. (Nov 14: "scrolling gets stuck to the +-- bottom; scroll away and it scrolls you back down".) Two ways it was: +-- - a scroll during a send's glide (the prompt rising to the view's top, or +-- a steer's waiting to land): the glide went on to the end over it; +-- - a scroll begun within moments of the view's size changing: the end +-- stayed held, and the next resize, however much later (the sidebar, a +-- panel, the window), went back to it. +-- On chat_fixture's `long_chat` (ui/long_chat_fixture.luau). + +local function settle(app: any) + app:wait("#never-shown", { timeout_ms = 250 }) + app:frames(10) +end + +local function offset(app: any): number + return app:state("chat.transcript.offset") +end + +-- How far the view is from its end, measured by going there (which holds +-- the end again: only at the close of a test). +local function from_end(app: any): number + local at = offset(app) + app:scroll("#transcript", 1e6) + app:frames(4) + return offset(app) - at +end + +local function open(): any + local app = mount("chat_fixture.luau") + app:resize(960, 700) + app:frames(20) + app:command("long_chat_sent") + app:command("go_s7") + app:frames(30) + settle(app) + return app +end + +local function send(app: any) + app:type("role:textbox", "three and one sounds like the most optional option") + app:key("Enter") +end + +local function scroll_up(app: any) + for _ = 1, 10 do + app:wheel("#transcript", { dy = -40 }) + app:frames(1) + end +end + +test("scrolled up while a send glides, the view stays where it was taken", function() + local app = open() + send(app) + app:frames(3) + scroll_up(app) + settle(app) + settle(app) + expect(from_end(app) > 100).to_be(true) +end) + +test("scrolled up just after a resize, a later resize leaves the view where it was", function() + local app = open() + send(app) + app:frames(40) + settle(app) + for _ = 1, 60 do + app:command("long_chat_streams") + app:frames(2) + end + app:frames(10) + app:resize(940, 700) + app:frames(2) + scroll_up(app) + -- (It rests inside the resize's moment, then a while.) + settle(app) + app:wait("#never-shown", { timeout_ms = 800 }) + local at = offset(app) + app:resize(900, 700) + app:frames(10) + settle(app) + expect(math.abs(offset(app) - at) < 1).to_be(true) + expect(from_end(app) > 100).to_be(true) +end) diff --git a/apps/zgx/ui/tool_pictures_fixture.luau b/apps/zgx/ui/tool_pictures_fixture.luau new file mode 100644 index 000000000..dafe00d1f --- /dev/null +++ b/apps/zgx/ui/tool_pictures_fixture.luau @@ -0,0 +1,60 @@ +-- A reply's work (ds/activity) with a Read of a picture whose result the +-- engine kept a copy of (its `pictures`, the tool's `previewPaths`), a Read +-- of another that kept none, and a command whose result kept two, for +-- tests/tool_pictures.test.luau. The +-- pictures are read from where the transcript reads an agent's shown ones +-- (stubbed: each path is the picture, nothing read). +-- Here, beside app.luau, as a mounted script loads modules from its own +-- directory down. + +ui.theme.strict("warn") +local ds = require("@ds") +ds.setup() +local Activity = require("@ds/activity") +local Lightbox = require("@ds/lightbox") + +local pictures = { + resolve = function(src: string): any + return { state = "ready", src = src, path = src, here = true } + end, + fetch = function(_src: string) end, +} + +local TOOLS = { + { + id = "r1", + kind = "read", + verb = "Read", + target = "test.png", + pictures = { { path = "assets/composer/shell.png", name = "test.png" } }, + }, + { id = "r2", kind = "read", verb = "Read", target = "old.png" }, + { + id = "r3", + kind = "exec", + verb = "Ran", + target = "shoot both", + pictures = { + { path = "assets/composer/shell.png", name = "left.png" }, + { path = "assets/composer/transcript.png", name = "right.png" }, + }, + }, +} + +return ui.column { + w_full = true, + h_full = true, + p = "$space.4", + ui.scroll { + w_full = true, + h_full = true, + Activity { + key = "work-pictures", + pictures = pictures, + tools = function(): { any } + return TOOLS + end, + }, + }, + Lightbox.Host(), +} diff --git a/crates/client/src/demo/transcripts.rs b/crates/client/src/demo/transcripts.rs index 63a34b94a..8cc6aefab 100644 --- a/crates/client/src/demo/transcripts.rs +++ b/crates/client/src/demo/transcripts.rs @@ -38,6 +38,7 @@ pub(crate) fn tool(id: &str, call: ToolCall, is_error: bool, output: Option<&str subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/client/src/session/mod.rs b/crates/client/src/session/mod.rs index e2bf64d70..c2e4114a1 100644 --- a/crates/client/src/session/mod.rs +++ b/crates/client/src/session/mod.rs @@ -1202,6 +1202,7 @@ fn refresh_setup_placeholder(st: &mut CoreState, machine: MachineWait) -> bool { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/client/src/subagents.rs b/crates/client/src/subagents.rs index 07263ff26..4a5c762cb 100644 --- a/crates/client/src/subagents.rs +++ b/crates/client/src/subagents.rs @@ -285,6 +285,7 @@ mod tests { subagent_ref: status.map(|_| format!("chat--sub--{id}")), subagent_status: status, subagent_tail: Some("Reading veil.rs".into()), + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/doc/examples/gen_fixture.rs b/crates/doc/examples/gen_fixture.rs index 7678b31ae..c98ec7f7c 100644 --- a/crates/doc/examples/gen_fixture.rs +++ b/crates/doc/examples/gen_fixture.rs @@ -55,6 +55,8 @@ fn main() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ); diff --git a/crates/doc/src/parts.rs b/crates/doc/src/parts.rs index 86884e9a2..64449be33 100644 --- a/crates/doc/src/parts.rs +++ b/crates/doc/src/parts.rs @@ -302,6 +302,12 @@ pub enum MessagePart { /// its tagged text deltas (capped; display-only). #[serde(default, skip_serializing_if = "Option::is_none")] subagent_tail: Option, + /// Uploads copies of images embedded in this tool's result. When + /// this is non-empty the chip previews these paths instead of files + /// the call named, which may sit outside the attachment jail. + /// Empty on older parts and on results that carried no image bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + preview_paths: Vec, /// A command's exit status, as its harness reported it (command /// tools only — see [`command_output_tail`]). #[serde(default, skip_serializing_if = "Option::is_none")] @@ -391,6 +397,7 @@ impl MessagePart { output, diff, diff_stats, + preview_paths, .. } => { serde_json::to_vec(call).map_or(0, |v| v.len()) @@ -401,6 +408,7 @@ impl MessagePart { + diff_stats .as_ref() .map_or(0, |s| serde_json::to_vec(s).map_or(0, |v| v.len())) + + preview_paths.iter().map(String::len).sum::() } MessagePart::Input { questions, answers, .. @@ -527,6 +535,7 @@ pub fn fold_event_into_parts(out: &mut Vec, event: &AgentEvent) { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -538,7 +547,9 @@ pub fn fold_event_into_parts(out: &mut Vec, event: &AgentEvent) { is_error, output, diff, + preview_paths, exit_code, + .. } => { for p in out.iter_mut() { if let MessagePart::Tool { @@ -550,6 +561,7 @@ pub fn fold_event_into_parts(out: &mut Vec, event: &AgentEvent) { diff: diff_slot, output_bytes, diff_stats, + preview_paths: stored, exit_code: exit_slot, output_truncated, output_lines, @@ -605,6 +617,11 @@ pub fn fold_event_into_parts(out: &mut Vec, event: &AgentEvent) { } *diff_slot = None; *diff_stats = diff.as_ref().map(|d| vec![diff_stat(d)]); + // A later result with no images must not wipe a preview + // already stored for this chip. + if !preview_paths.is_empty() { + *stored = preview_paths.clone(); + } } } } @@ -1155,6 +1172,8 @@ mod tests { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ); @@ -1169,6 +1188,55 @@ mod tests { } } + #[test] + fn tool_result_preview_paths_stick_and_an_empty_result_does_not_wipe_them() { + let mut parts = Vec::new(); + fold_event_into_parts( + &mut parts, + &AgentEvent::ToolCall { + id: "t".into(), + call: ToolCall::ReadFile { + path: "/tmp/shots/1.png".into(), + }, + }, + ); + fold_event_into_parts( + &mut parts, + &AgentEvent::ToolResult { + exit_code: None, + id: "t".into(), + is_error: false, + output: None, + diff: None, + preview_paths: vec!["/uploads/abc-image.png".into()], + image_payloads: Vec::new(), + }, + ); + fold_event_into_parts( + &mut parts, + &AgentEvent::ToolResult { + exit_code: None, + id: "t".into(), + is_error: false, + output: None, + diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), + }, + ); + match &parts[0] { + MessagePart::Tool { + preview_paths, + resolved, + .. + } => { + assert!(*resolved); + assert_eq!(preview_paths, &vec!["/uploads/abc-image.png".to_string()]); + } + other => panic!("unexpected {other:?}"), + } + } + #[test] fn sanitize_strips_heavy_inputs_and_is_idempotent() { let call = ToolCall::WriteFile { @@ -1274,6 +1342,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -1372,6 +1441,8 @@ mod tests { }, }, AgentEvent::ToolResult { + image_payloads: Vec::new(), + preview_paths: Vec::new(), id: "c".into(), is_error: exit_code.is_some_and(|c| c != 0), output: Some(output.into()), @@ -1493,6 +1564,8 @@ mod tests { }, }, AgentEvent::ToolResult { + image_payloads: Vec::new(), + preview_paths: Vec::new(), id: "c".into(), is_error: false, output: Some("hunter2-but-unlabelled\n".into()), @@ -1568,6 +1641,8 @@ mod tests { }, }, AgentEvent::ToolResult { + image_payloads: Vec::new(), + preview_paths: Vec::new(), id: "r".into(), is_error: false, output: Some("API_KEY=hunter2".into()), @@ -1614,6 +1689,8 @@ mod tests { old_text: Some("a\n".into()), new_text: "b\n".into(), }), + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ); @@ -1672,6 +1749,8 @@ mod tests { old_text: None, new_text: "x\n".into(), }), + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ); @@ -1827,6 +1906,8 @@ mod tests { is_error: false, output: Some(" \n".into()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }), None, @@ -1837,6 +1918,8 @@ mod tests { is_error: true, output: Some("full output".into()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }) .unwrap(); diff --git a/crates/doc/src/rebuild.rs b/crates/doc/src/rebuild.rs index 0ee8e47a6..177147d7f 100644 --- a/crates/doc/src/rebuild.rs +++ b/crates/doc/src/rebuild.rs @@ -183,6 +183,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/doc/src/schema.rs b/crates/doc/src/schema.rs index 725b6df65..66f854351 100644 --- a/crates/doc/src/schema.rs +++ b/crates/doc/src/schema.rs @@ -145,6 +145,9 @@ struct DocPartJson { /// One-line live tail of the subagent's output (additive). #[serde(default, skip_serializing_if = "Option::is_none")] subagent_tail: Option, + /// Uploads copies of images embedded in a tool result (additive). + #[serde(default, skip_serializing_if = "Option::is_none")] + preview_paths: Option>, /// A command's exit status (additive; command tools only). #[serde(default, skip_serializing_if = "Option::is_none")] exit_code: Option, @@ -208,6 +211,7 @@ fn to_doc_part(part: &MessagePart) -> Result { subagent_ref, subagent_status, subagent_tail, + preview_paths, exit_code, output_truncated, output_lines, @@ -234,6 +238,7 @@ fn to_doc_part(part: &MessagePart) -> Result { .to_owned() }), subagent_tail: subagent_tail.clone(), + preview_paths: (!preview_paths.is_empty()).then(|| preview_paths.clone()), exit_code: *exit_code, output_truncated: output_truncated.then_some(true), output_lines: *output_lines, @@ -323,6 +328,7 @@ fn from_doc_part(p: DocPartJson) -> MessagePart { _ => None, }), subagent_tail: p.subagent_tail, + preview_paths: p.preview_paths.unwrap_or_default(), exit_code: p.exit_code, output_truncated: p.output_truncated.unwrap_or(false), output_lines: p.output_lines, @@ -1599,6 +1605,18 @@ fn push_part(parts: &LoroList, part: &MessagePart) -> Result<(), DocError> { if let Some(subagent_tail) = &doc_part.subagent_tail { map.insert("subagentTail", subagent_tail.as_str())?; } + if let Some(preview_paths) = &doc_part.preview_paths { + map.insert( + "previewPaths", + loro_value_from_json(&serde_json::Value::Array( + preview_paths + .iter() + .cloned() + .map(serde_json::Value::String) + .collect(), + )), + )?; + } if let Some(exit_code) = doc_part.exit_code { map.insert("exitCode", exit_code as i64)?; } @@ -1772,6 +1790,10 @@ fn salvage_part(part: &serde_json::Value, entry_id: &str, ix: usize) -> Option Result<(), DocError> if let Some(subagent_tail) = &doc_part.subagent_tail { map.insert("subagentTail", subagent_tail.as_str())?; } + if let Some(preview_paths) = &doc_part.preview_paths { + map.insert( + "previewPaths", + loro_value_from_json(&serde_json::Value::Array( + preview_paths + .iter() + .cloned() + .map(serde_json::Value::String) + .collect(), + )), + )?; + } if let Some(exit_code) = doc_part.exit_code { map.insert("exitCode", exit_code as i64)?; } @@ -2866,6 +2900,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -2933,6 +2968,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -2988,6 +3024,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -3172,6 +3209,43 @@ mod tests { assert_eq!(ea.len(), 2); // one insert from each peer, converged in the same order } + #[test] + fn tool_preview_paths_round_trip_through_the_doc() { + let doc = SessionDoc::init("previews").unwrap(); + let mut writer = SegmentWriter::begin(&doc, "a1", "dev", 1).unwrap(); + let mut folded = Vec::new(); + fold_event_into_parts( + &mut folded, + &AgentEvent::ToolCall { + id: "t".into(), + call: ToolCall::ReadFile { + path: "/tmp/shots/1.png".into(), + }, + }, + ); + writer.sync(&folded).unwrap(); + fold_event_into_parts( + &mut folded, + &AgentEvent::ToolResult { + exit_code: None, + id: "t".into(), + is_error: false, + output: None, + diff: None, + preview_paths: vec!["/uploads/abc-image.png".into()], + image_payloads: Vec::new(), + }, + ); + writer.finish(&folded, MessageStatus::Complete).unwrap(); + let entries = doc.read_entries().unwrap(); + match &entries[0].parts[0] { + MessagePart::Tool { preview_paths, .. } => { + assert_eq!(preview_paths, &vec!["/uploads/abc-image.png".to_string()]); + } + other => panic!("unexpected {other:?}"), + } + } + #[test] fn segment_writer_streams_text_incrementally() { let doc = SessionDoc::init("chat-1").unwrap(); @@ -3199,6 +3273,8 @@ mod tests { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ); @@ -3319,6 +3395,8 @@ mod tests { old_text: Some("old\n".into()), new_text: "new\n".into(), }), + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ); @@ -3377,6 +3455,8 @@ mod tests { fold_event_into_parts( &mut folded, &AgentEvent::ToolResult { + image_payloads: Vec::new(), + preview_paths: Vec::new(), id: "c1".into(), is_error: true, output: Some(full.clone()), @@ -3451,6 +3531,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/doc/src/transcript_delta.rs b/crates/doc/src/transcript_delta.rs index 64bd29536..bd5d4f1ba 100644 --- a/crates/doc/src/transcript_delta.rs +++ b/crates/doc/src/transcript_delta.rs @@ -903,6 +903,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + preview_paths: Vec::new(), } } diff --git a/crates/engine/examples/mcp_standalone_smoke.rs b/crates/engine/examples/mcp_standalone_smoke.rs index 5c9fdd5cf..0b6b1e5e3 100644 --- a/crates/engine/examples/mcp_standalone_smoke.rs +++ b/crates/engine/examples/mcp_standalone_smoke.rs @@ -68,6 +68,7 @@ impl Harness for SmokeHarness { default: false, id: "smoke-1".into(), label: "Smoke 1".into(), + provider: None, description: None, reasoning_levels: vec![], options: vec![], diff --git a/crates/engine/src/agent_accounts.rs b/crates/engine/src/agent_accounts.rs index 93a6570da..8bd8fcdb5 100644 --- a/crates/engine/src/agent_accounts.rs +++ b/crates/engine/src/agent_accounts.rs @@ -11,14 +11,21 @@ //! |----------|--------|--------|--------------------------------|-------| //! | Grok | yes | yes | `grok login --device-auth` | yes | //! | Devin | yes | yes | ACP `authenticate` (loopback) | yes | -//! | OpenCode | yes | yes | ChatGPT loopback, Copilot code | yes | -//! | Pi | yes | yes | ChatGPT loopback | yes | +//! | OpenCode | yes | yes² | ChatGPT loopback, Copilot code | yes | +//! | Pi | yes | yes² | ChatGPT loopback, Copilot code | yes | //! | Hermes | yes | no¹ | `hermes auth add` (device code) | yes | //! //! ¹ Hermes keeps every account in its own credential pool and rotates //! through it itself; zeron lists the pool and adds to it through Hermes' //! own CLI, but never rewrites it. //! +//! ² Per model provider: these agents keep one login per provider in one +//! store, and a run reads the entry of its model's provider. Each row +//! carries its provider (`AgentAccount::provider`); rows sharing one form a +//! group with at most one in use, and switching (or a new sign-in) rewrites +//! that provider's entry alone — a ChatGPT switch never touches the Claude +//! or Copilot login beside it. +//! //! The original four providers each store exactly one live login: //! //! - **Claude Code** — credentials in `~/.claude/.credentials.json` @@ -105,6 +112,7 @@ pub struct RelayedCallback { pub location: Option, } +mod api_keys; mod muse; mod pins; mod oauth; @@ -725,6 +733,12 @@ struct ProbeEndpoints { github_api: String, /// GitHub's OAuth root (`/login/device/code`, `/login/oauth/access_token`). github_login: String, + /// A Copilot session's API root (`/models`): `None` in production, where + /// it's read from the session token itself. + copilot_api: Option, + /// Where API keys are checked: `None` in production (each provider's + /// own host, `api_keys::key_check`), a mock in tests. + api_key_check: Option, /// OpenAI's OAuth root (`/oauth/authorize`, `/oauth/token`). openai_auth: String, /// The ChatGPT sign-in's loopback port — FIXED at 1455 by the client @@ -752,6 +766,8 @@ impl Default for ProbeEndpoints { grok_usage: usage::GROK_USAGE_URL.into(), github_api: "https://api.github.com".into(), github_login: "https://github.com".into(), + copilot_api: None, + api_key_check: None, openai_auth: oauth::OPENAI_AUTH.into(), openai_port: oauth::OPENAI_LOOPBACK_PORT, nous_portal: usage::NOUS_PORTAL.into(), @@ -1038,6 +1054,15 @@ impl AgentAccounts { live(*harness, detected); self.snapshot_detected(*harness, detected)?; } + if self.opencode_keeps_its_own_store() { + warnings.push(AgentAccountWarning { + harness: HarnessId::Opencode, + message: "This OpenCode keeps its logins in its own database: switching or adding \ + them here doesn't reach it yet — use `opencode auth switch` / \ + `opencode auth login`." + .into(), + }); + } if let Some(message) = stores::opencode_env_warning() { warnings.push(AgentAccountWarning { harness: HarnessId::Opencode, @@ -1243,7 +1268,7 @@ impl AgentAccounts { let key = slot.store_key.as_deref().ok_or_else(|| { EngineError::Other("That saved login names no provider.".into()) })?; - self.write_keyed_entry(harness, key, Some(&slot.credentials))?; + self.swap_keyed(harness, key, &slot).await?; } other => { return Err(EngineError::Other(format!( @@ -1255,6 +1280,41 @@ impl AgentAccounts { self.list_locked(false).await } + /// Point OpenCode's / Pi's entry for `key` at `slot`'s login, under the + /// agent's own lock (Pi's is the one it refreshes under). The login in + /// use is identified first and saved into its slot with the tokens it + /// has NOW — the agent may have refreshed it since the last list, and + /// Claude's and ChatGPT's refresh tokens are single-use. If it can't be + /// identified (its profile call rate limited), or it changes between + /// that and the lock, the switch is refused rather than overwrite a + /// login no slot holds. + async fn swap_keyed(&self, harness: HarnessId, key: &str, slot: &Slot) -> Result<(), EngineError> { + let live = match self.detect_keyed_entry(harness, key).await { + None => None, + Some(Some(detected)) => Some(detected), + Some(None) => { + return Err(EngineError::Other( + "Couldn't confirm the login in use — try again in a moment.".into(), + )); + } + }; + if let Some(detected) = &live + && detected.account_key != slot.account_key + { + self.snapshot_detected(harness, detected)?; + } + let saved = live.as_ref().and_then(|d| d.credentials.clone()); + self.swap_keyed_entry(harness, key, &slot.credentials, &mut |old| { + if old.cloned() == saved { + Ok(()) + } else { + Err(EngineError::Other( + "The login in use just changed — try again in a moment.".into(), + )) + } + }) + } + /// Claude Code's own refresh lock (see /// [`zeron_harness::claude::refresh_lock`]), held while the live Claude /// login is read and replaced. @@ -1618,8 +1678,12 @@ impl AgentAccounts { /// [`Self::start_login_for`] for one model provider of an agent that /// keeps a login per provider (`provider`: OpenCode's `openai` / - /// `github-copilot`, Pi's `openai-codex`, Hermes' `openai-codex` / - /// `nous`); `None` picks the agent's default. + /// `github-copilot`, Pi's `openai-codex` / `github-copilot`, Hermes' + /// `openai-codex` / `nous` / `xai-oauth` — + /// `zeron_proto::providers::login_options`); `None` picks the agent's + /// default. The new login joins its provider's group only: it takes + /// over that provider's live login when there is none (or it re-signs + /// that one in), and never touches another provider's. pub async fn start_login_with( &self, harness: HarnessId, @@ -1657,6 +1721,8 @@ impl AgentAccounts { self.start_openai_login(HarnessId::Pi, "openai-codex") .await? } + "github-copilot" => self.start_copilot_login(HarnessId::Pi).await?, + "anthropic" => self.start_pi_claude_login().await?, other => return Err(stores::unsupported_login(harness, other)), }, HarnessId::Hermes => { @@ -6164,7 +6230,11 @@ mod login_tests { while let Ok((mut socket, _)) = listener.accept().await { let mut request = vec![0u8; 16 * 1024]; let _ = socket.read(&mut request).await; - counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + // (A preview scan elsewhere in the test process probes every + // local listener with `HEAD /`: not counted.) + if !request.starts_with(b"HEAD ") { + counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } let _ = socket .write_all( http_response(status, &[("Content-Type", "application/json")], body) diff --git a/crates/engine/src/agent_accounts/api_keys.rs b/crates/engine/src/agent_accounts/api_keys.rs new file mode 100644 index 000000000..07cdab757 --- /dev/null +++ b/crates/engine/src/agent_accounts/api_keys.rs @@ -0,0 +1,551 @@ +//! API keys for agents that keep a login per model provider — added in the +//! app instead of a CLI, stored exactly where and how each agent's own CLI +//! stores them (`zeron_proto::providers::api_key_options` says which): +//! +//! - **Pi** — `auth.json`'s provider entry `{"type": "api_key", "key"}` +//! (pi-ai `envApiKeyAuth`'s login result; pi's `FileAuthStorageBackend` +//! writes it 0600 under its proper-lockfile lock, as zeron does). Pi reads +//! a key starting `!` as a shell command and expands `$VAR`s, so a key is +//! only ever a plain token (see [`valid_key`]). +//! - **OpenCode 1.x** — `auth.json`'s entry `{"type": "api", "key"}` (its +//! credential schema; 0600). **OpenCode 2.x** keeps every credential in +//! its own database (`opencode.db`'s `credential` table; `auth.json` is +//! imported once and never read again), so a key written to `auth.json` +//! would do nothing: refused, with what to do instead. +//! - **Hermes** — its own credential pool, through its own CLI: `hermes +//! auth add --type api-key`, the key on its STDIN (its +//! `masked_secret_prompt` falls back to `getpass`, which reads stdin when +//! the child has no terminal — it runs in a session of its own, so it +//! never has one). Hermes writes and locks its pool itself. +//! +//! Each key is checked with its provider first (a models / key-info call +//! that costs nothing) and only saved once accepted. Like every login on +//! this device, a key added to Pi or OpenCode is also kept in its account +//! slot (owner-only, 0600) so switching away from it and back works. +//! +//! The key is a secret end to end: never logged, never in an error, never +//! in a list (a key row says `API key ····abcd`), never on a command line, +//! and never sent anywhere but its provider — `AddAgentApiKey` is answered +//! only over this device's own IPC (`zeron_rpc::local_only`), and a request +//! naming another device is refused rather than forwarded. + +use zeron_proto::providers::api_key_option; + +use super::*; + +/// How a provider's key is checked: the cheapest authenticated call it has. +struct KeyCheck { + vendor: &'static str, + base: &'static str, + path: &'static str, + auth: KeyAuth, +} + +enum KeyAuth { + Bearer, + /// Anthropic's `x-api-key` (+ `anthropic-version`). + Anthropic, + /// Google's `x-goog-api-key` (never the `?key=` query: urls get logged). + Google, +} + +fn key_check(provider: &str) -> Option { + let check = |vendor, base, path, auth| KeyCheck { + vendor, + base, + path, + auth, + }; + Some(match provider { + "openai" | "openai-api" => check( + "OpenAI", + "https://api.openai.com", + "/v1/models", + KeyAuth::Bearer, + ), + "anthropic" => check( + "Anthropic", + "https://api.anthropic.com", + "/v1/models", + KeyAuth::Anthropic, + ), + "openrouter" => check( + "OpenRouter", + "https://openrouter.ai", + "/api/v1/key", + KeyAuth::Bearer, + ), + "google" | "gemini" => check( + "Google", + "https://generativelanguage.googleapis.com", + "/v1beta/models", + KeyAuth::Google, + ), + "xai" => check("xAI", "https://api.x.ai", "/v1/api-key", KeyAuth::Bearer), + "groq" => check( + "Groq", + "https://api.groq.com", + "/openai/v1/models", + KeyAuth::Bearer, + ), + "deepseek" => check( + "DeepSeek", + "https://api.deepseek.com", + "/models", + KeyAuth::Bearer, + ), + "mistral" => check( + "Mistral", + "https://api.mistral.ai", + "/v1/models", + KeyAuth::Bearer, + ), + _ => return None, + }) +} + +/// A key as zeron accepts it: one plain token of 8 to 512 characters from +/// the alphabet API keys use. Nothing a shell, Pi's `!command` / `$VAR` +/// expansion or a JSON / TOML store could read as anything but a literal. +pub(super) fn valid_key(key: &str) -> bool { + (8..=512).contains(&key.len()) + && !key.starts_with(['!', '-']) + && key + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_.:+/=~".contains(c)) +} + +/// A key as a list may show it: its last four characters. +pub(super) fn masked(key: &str) -> String { + let chars: Vec = key.chars().collect(); + let tail: String = chars[chars.len().saturating_sub(4)..].iter().collect(); + format!("···{tail}") +} + +/// How a key's row reads — its last four characters said exactly once: +/// named, "Work" over "OpenRouter · API key"; unnamed, "API key ···a1b2" +/// over "OpenRouter"; seeded from an environment variable (Hermes), never +/// that variable's name: "API key ···a1b2" over "OpenRouter · from +/// environment". `key`: the key, when it's a plain one (none: a command or +/// variable Pi resolves, of which nothing is shown). +pub(super) fn key_rows( + provider: &str, + key: Option<&str>, + name: Option<&str>, + from_env: bool, +) -> (String, String) { + let unnamed = match key { + Some(key) => format!("API key {}", masked(key)), + None => "API key".to_string(), + }; + match (name, from_env) { + (_, true) => (unnamed, format!("{provider} · from environment")), + (Some(name), false) => (name.to_string(), format!("{provider} · API key")), + (None, false) => (unnamed, provider.to_string()), + } +} + +/// `profile` as a key's, named `name` (none: unnamed). The name, when set, +/// is also kept apart (`display_name`), so it's never mistaken for the +/// derived title. +pub(super) fn name_key_profile( + profile: &mut SlotProfile, + provider: &str, + key: Option<&str>, + name: Option<&str>, +) { + let (title, line) = key_rows(provider, key, name, false); + profile.email = title; + profile.plan = Some(line); + profile.display_name = name.map(str::to_string); +} + +/// A name for a key as given, or why not: one line of at most 48 +/// characters that doesn't look like a key itself. The check never looks at +/// the key: a name is renamed from other devices too, and a refusal that +/// depended on the key's contents would let a peer probe it. +pub(super) fn key_name(name: &str) -> Result, EngineError> { + let name = name.trim(); + if name.is_empty() { + return Ok(None); + } + if name.chars().count() > 48 || name.chars().any(char::is_control) { + return Err(EngineError::Other( + "A name is one short line — 48 characters at most.".into(), + )); + } + if looks_like_a_key(name) { + return Err(EngineError::Other( + "That looks like a key — give it a name instead.".into(), + )); + } + Ok(Some(name.to_string())) +} + +/// Whether any word of `text` reads as a secret: a key's own prefix +/// (`sk-`, `sk-ant-`, `sk-or-`, `xai-`, `AIza`, GitHub's `gh?_`), or a run of +/// 16 or more key characters with no space in it. +fn looks_like_a_key(text: &str) -> bool { + const PREFIXES: &[&str] = &[ + "sk-", + "sk_", + "xai-", + "AIza", + "ghp_", + "gho_", + "ghu_", + "ghs_", + "github_pat_", + ]; + text.split_whitespace().any(|word| { + let lower = word.to_ascii_lowercase(); + PREFIXES + .iter() + .any(|p| word.starts_with(p) || lower.starts_with(&p.to_ascii_lowercase())) + || word + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-')) + .any(|run| run.chars().count() >= 16) + }) +} + +/// The entry's key, if it's an API-key entry in `harness`'s own shape (Pi +/// `api_key`, OpenCode `api`). +pub(super) fn key_entry_secret(harness: HarnessId, entry: &serde_json::Value) -> Option { + let kind = match harness { + HarnessId::Pi => "api_key", + HarnessId::Opencode => "api", + _ => return None, + }; + (entry.get("type").and_then(|t| t.as_str()) == Some(kind)) + .then(|| str_field(entry, "key")) + .flatten() +} + +/// An API-key entry of Pi's / OpenCode's store as a login: keyed by a +/// digest of the key (never the key), shown by its last four characters. +/// A Pi key that is really a command or variable (`!…`, `$…`) shows none. +pub(super) fn key_detected( + harness: HarnessId, + store_key: &str, + entry: &serde_json::Value, +) -> Option { + let key = key_entry_secret(harness, entry)?; + let provider = zeron_proto::providers::account_group_label(harness, store_key); + // (A Pi key that's really a command or a variable shows none of it.) + let plain = valid_key(&key).then_some(key.as_str()); + let digest = crate::repos::hex(&Sha256::digest(key.as_bytes()))[..16].to_string(); + // Unnamed until it's given a name ([`AgentAccounts::rename_account`]). + let mut profile = SlotProfile { + email: String::new(), + display_name: None, + organization: None, + plan: None, + auth_kind: AgentAuthKind::ApiKey, + }; + name_key_profile(&mut profile, &provider, plain, None); + let mut detected = Detected::known(format!("{store_key}:key:{digest}"), profile, entry.clone()) + .keyed(store_key); + // A key carries no name of its own: the one its slot keeps (given when + // it was added, or since) wins over the default. + detected.identity_known = false; + Some(detected) +} + +/// The entry `harness`'s own CLI writes for a key. +fn key_entry(harness: HarnessId, key: &str) -> serde_json::Value { + match harness { + HarnessId::Opencode => serde_json::json!({ "type": "api", "key": key }), + _ => serde_json::json!({ "type": "api_key", "key": key }), + } +} + +/// A string overwritten when dropped (the key's copy on its way to stdin). +struct Zeroized(String); + +impl Drop for Zeroized { + fn drop(&mut self) { + // SAFETY: zeros are valid UTF-8; the bytes are dropped right after. + unsafe { self.0.as_bytes_mut().fill(0) }; + } +} + +fn zeroize_on_drop(text: String) -> Zeroized { + Zeroized(text) +} + +/// Every occurrence of `key` in `text`, blanked — for the agent's own +/// words, which never name a key, but are never trusted to. +fn without(text: &str, key: &str) -> String { + if key.is_empty() { + return text.to_string(); + } + text.replace(key, "[key]") +} + +impl AgentAccounts { + /// Add `key` for `provider` of `harness` (an `api_key_options` pair), + /// checked with the provider first. Pi / OpenCode: written to the + /// agent's store when that provider has no live login there (else kept + /// beside it, to switch to), Hermes: appended to its own pool. + pub async fn add_api_key( + &self, + harness: HarnessId, + provider: &str, + key: &str, + name: Option<&str>, + ) -> Result { + let added = self + .add_api_key_unpublished(harness, provider, key, name) + .await; + self.published(added) + } + + async fn add_api_key_unpublished( + &self, + harness: HarnessId, + provider: &str, + key: &str, + name: Option<&str>, + ) -> Result { + let key = key.trim(); + let Some(option) = api_key_option(harness, provider) else { + return Err(EngineError::Other(format!( + "Zeron doesn't add {provider} keys for {}.", + stores::cli_name(harness) + ))); + }; + if !valid_key(key) { + return Err(EngineError::Other(format!( + "That doesn't look like a {} API key — paste the whole key, nothing else.", + option.label + ))); + } + let name = key_name(name.unwrap_or_default())?; + if harness == HarnessId::Opencode && self.opencode_keeps_its_own_store() { + return Err(EngineError::Other( + "This OpenCode keeps its keys in its own database — add it with \ + `opencode auth login` there." + .into(), + )); + } + self.check_api_key(provider, key).await?; + match harness { + HarnessId::Hermes => { + self.add_hermes_key(provider, key, name.as_deref()).await?; + let _ops = self.inner.ops.lock().await; + self.list_locked(false).await + } + HarnessId::Pi | HarnessId::Opencode => { + let entry = key_entry(harness, key); + let mut detected = key_detected(harness, provider, &entry) + .ok_or_else(|| EngineError::Other("That key couldn't be stored.".into()))?; + let group = zeron_proto::providers::account_group_label(harness, provider); + name_key_profile(&mut detected.profile, &group, Some(key), name.as_deref()); + self.save_new_login(harness, &detected).await?; + let _ops = self.inner.ops.lock().await; + // (Added again under a new name: the new name.) + if let Some(name) = name + && let Some(mut slot) = + self.read_slot(harness, &slot_id_for(harness, &detected.account_key)) + && slot.profile.display_name.as_deref() != Some(name.as_str()) + { + name_key_profile(&mut slot.profile, &group, Some(key), Some(&name)); + self.write_slot(&slot)?; + } + self.list_locked(false).await + } + _ => Err(EngineError::Other("No API keys for this agent.".into())), + } + } + + /// Ask the provider whether it takes `key` — the one request the key is + /// ever sent in by zeron, over https to the provider's own host. + async fn check_api_key(&self, provider: &str, key: &str) -> Result<(), EngineError> { + let Some(check) = key_check(provider) else { + return Err(EngineError::Other( + "Zeron can't check that provider's keys yet.".into(), + )); + }; + let base = self + .inner + .endpoints + .api_key_check + .as_deref() + .unwrap_or(check.base) + .trim_end_matches('/'); + let request = self + .inner + .http + .get(format!("{base}{}", check.path)) + .header("Accept", "application/json") + .timeout(Duration::from_secs(10)); + let request = match check.auth { + KeyAuth::Bearer => request.bearer_auth(key), + KeyAuth::Anthropic => request + .header("x-api-key", key) + .header("anthropic-version", "2023-06-01"), + KeyAuth::Google => request.header("x-goog-api-key", key), + }; + let vendor = check.vendor; + // (The error is reqwest's, which names the url, never a header.) + let response = request.send().await.map_err(|_| { + EngineError::Other(format!( + "Couldn't reach {vendor} to check the key — try again." + )) + })?; + let status = response.status(); + if status.is_success() { + return Ok(()); + } + // Never the body: some providers echo what they were sent. + Err(EngineError::Other(match status.as_u16() { + 400 | 401 | 403 => format!("{vendor} didn't accept that key — check it and try again."), + 402 => format!("{vendor} accepted the key, but its account has no credit."), + 429 => format!("{vendor} is rate limiting right now — try the key again in a minute."), + _ => format!("{vendor} couldn't check the key ({status}) — try again."), + })) + } + + /// `hermes auth add --type api-key`, the key written to its + /// stdin (never argv, never its environment), in a session of its own + /// so `getpass` has no terminal to prompt on and reads stdin instead. + async fn add_hermes_key( + &self, + provider: &str, + key: &str, + name: Option<&str>, + ) -> Result<(), EngineError> { + // (Its name is no secret — checked to hold none of the key — so it + // may ride on the command line, as Hermes takes it.) + // (`--label=…` in one argument: a name starting with `-` is never + // read as a flag.) + let label = name.map(|name| format!("--label={name}")); + let mut args = vec!["auth", "add", provider, "--type", "api-key"]; + if let Some(label) = &label { + args.push(label); + } + let mut command = self.cli_command(HarnessId::Hermes, &args).await?; + // A sign-in abandoned (the engine stopping, the wait timing out) + // takes Hermes with it. + command.kill_on_drop(true); + command + .env("HERMES_HOME", &self.inner.config.hermes_home) + .stdin(zeron_harness::process::Stdio::piped()) + .stdout(zeron_harness::process::Stdio::piped()) + .stderr(zeron_harness::process::Stdio::piped()); + #[cfg(unix)] + // SAFETY: `setsid` is async-signal-safe; nothing else runs between + // fork and exec. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = command + .spawn() + .map_err(|e| EngineError::Other(format!("Couldn't run hermes: {e}")))?; + if let Some(mut stdin) = child.stdin.take() { + use tokio::io::AsyncWriteExt as _; + let line = zeroize_on_drop(format!("{key}\n")); + let _ = stdin.write_all(line.0.as_bytes()).await; + let _ = stdin.shutdown().await; + } + let output = tokio::time::timeout(Duration::from_secs(60), child.wait_with_output()) + .await + .map_err(|_| EngineError::Other("hermes didn't finish adding the key.".into()))? + .map_err(|e| EngineError::Other(format!("hermes failed: {e}")))?; + if output.status.success() { + return Ok(()); + } + let said = String::from_utf8_lossy(&output.stderr); + let said = without(said.trim(), key); + let last = said + .lines() + .rev() + .find(|l| !l.trim().is_empty() && !l.contains("GetPassWarning")) + .unwrap_or("hermes refused the key"); + Err(EngineError::Other(zeron_harness::redact::redact_output( + &without(last.trim(), key), + ))) + } + + /// OpenCode 2.x: its credentials live in `opencode.db`'s `credential` + /// table, beside the `auth.json` 1.x read (imported once, then unread). + pub(super) fn opencode_keeps_its_own_store(&self) -> bool { + let Some(dir) = self.inner.config.opencode_auth_file.parent() else { + return false; + }; + let db = dir.join("opencode.db"); + if !db.exists() { + return false; + } + let Ok(conn) = rusqlite::Connection::open_with_flags( + &db, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) else { + return false; + }; + conn.query_row( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'credential'", + [], + |_| Ok(()), + ) + .is_ok() + } +} + +impl AgentAccounts { + /// A key's name, changed (no key asked again): kept with its slot's + /// other details, so it shows wherever the row does. Keys alone are + /// named (a login goes by its own address); Hermes' pool is Hermes' to + /// label. + pub async fn rename_account( + &self, + harness: HarnessId, + account_id: &str, + name: &str, + ) -> Result { + let renamed = self + .rename_account_unpublished(harness, account_id, name) + .await; + self.published(renamed) + } + + async fn rename_account_unpublished( + &self, + harness: HarnessId, + account_id: &str, + name: &str, + ) -> Result { + if account_id.len() != 16 + || !account_id + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(EngineError::Other("Unknown account.".into())); + } + if harness == HarnessId::Hermes { + return Err(EngineError::Other( + "Hermes names its own keys — rename one with `hermes auth`.".into(), + )); + } + let _ops = self.inner.ops.lock().await; + let mut slot = self + .read_slot(harness, account_id) + .filter(|slot| slot.profile.auth_kind == AgentAuthKind::ApiKey) + .ok_or_else(|| EngineError::Other("Only an API key takes a name here.".into()))?; + let key = key_entry_secret(harness, &slot.credentials); + let provider = zeron_proto::providers::account_group_label( + harness, + slot.store_key.as_deref().unwrap_or_default(), + ); + let name = key_name(name)?; + let plain = key.as_deref().filter(|k| valid_key(k)); + name_key_profile(&mut slot.profile, &provider, plain, name.as_deref()); + self.write_slot(&slot)?; + self.list_locked(false).await + } +} diff --git a/crates/engine/src/agent_accounts/oauth.rs b/crates/engine/src/agent_accounts/oauth.rs index e70002f84..4f7d03ae3 100644 --- a/crates/engine/src/agent_accounts/oauth.rs +++ b/crates/engine/src/agent_accounts/oauth.rs @@ -10,12 +10,29 @@ //! Each login is a fresh grant: a refresh token is never shared with the //! Codex slots (OpenAI rotates them, so sharing one logs the other out). //! The callback port is reported, so a remote login tunnels it. -//! - **GitHub Copilot** (OpenCode `github-copilot`): GitHub's device flow -//! with OpenCode's OAuth app (scope `read:user`) — the dialog shows the -//! code; no loopback, so a remote login needs no tunnel. OpenCode stores -//! the GitHub token as both `access` and `refresh` with `expires: 0`. -//! Pi's Copilot login exchanges the token for an internal Copilot session -//! and is left to pi's own `/login`. +//! - **Claude** (Pi `anthropic`): the Claude Pro/Max sign-in pi's `/login` +//! runs — Claude Code's public client, PKCE against our own loopback on +//! any free port, the code redeemed at Anthropic's token endpoint — saved +//! as pi saves it (`{type: "oauth", refresh, access, expires}`, `expires` +//! five minutes early). A fresh grant of its own: never Claude Code's +//! refresh token (single-use: sharing one would log the other out). Pi +//! refreshes it under its own lock, which every zeron swap takes too. +//! (OpenCode has no Claude sign-in: none offered.) +//! - **GitHub Copilot** (`github-copilot`, OpenCode and Pi): GitHub's +//! device flow (scope `read:user`) — the dialog shows the code; no +//! loopback, so a remote login needs no tunnel. Each agent signs in with +//! its own OAuth app and keeps its own entry shape: +//! - OpenCode (its app): the GitHub token as both `access` and `refresh`, +//! `expires: 0`. +//! - Pi (the Copilot editor app pi's `/login` uses — Copilot's token +//! endpoint only serves that one): the GitHub token is `refresh`, and +//! `access` the Copilot session it's exchanged for at +//! `copilot_internal/v2/token`, with its `expires` — pi re-exchanges it +//! itself when it runs out. As pi's login does, the models the account +//! may pick but hasn't enabled yet (`policy.state: "unconfigured"`) are +//! enabled, and the ones it can use recorded as `availableModelIds` +//! (pi lists those). Both best effort: pi fills them on its next +//! refresh anyway. github.com only — an Enterprise host stays with pi. use super::stores::{Upstream, openai_detected, upstream_of}; use super::*; @@ -29,6 +46,24 @@ pub(super) const OPENAI_LOOPBACK_PORT: u16 = 1455; const OPENAI_SCOPES: &str = "openid profile email offline_access"; /// OpenCode's GitHub OAuth app (its Copilot device flow). const OPENCODE_COPILOT_CLIENT_ID: &str = "Ov23li8tweQw6odWQebz"; +/// The Copilot editor app pi's `/login` signs in with (pi-ai +/// `auth/oauth/github-copilot`): Copilot's token exchange serves its tokens. +const PI_COPILOT_CLIENT_ID: &str = "Iv1.b507a08c87ecfe98"; +/// The headers pi's Copilot client sends (pi-ai `COPILOT_HEADERS`). +const PI_COPILOT_HEADERS: [(&str, &str); 4] = [ + ("User-Agent", "GitHubCopilotChat/0.35.0"), + ("Editor-Version", "vscode/1.107.0"), + ("Editor-Plugin-Version", "copilot-chat/0.35.0"), + ("Copilot-Integration-Id", "vscode-chat"), +]; +/// Pi's Claude Pro/Max sign-in (pi-ai `auth/oauth/anthropic`): Claude +/// Code's public client, claude.ai's authorize page, the scopes pi asks +/// for. Any loopback port is accepted by the client registration. +const PI_CLAUDE_AUTHORIZE_URL: &str = "https://claude.ai/oauth/authorize"; +const PI_CLAUDE_SCOPES: &str = "org:create_api_key user:profile user:inference \ + user:sessions:claude_code user:mcp_servers user:file_upload"; +/// Where an individual Copilot account's API is when its token names none. +const COPILOT_INDIVIDUAL_API: &str = "https://api.individual.githubcopilot.com"; /// How long a sign-in waits on the browser before giving up. const LOGIN_WAIT: Duration = Duration::from_secs(10 * 60); @@ -232,9 +267,173 @@ impl AgentAccounts { self.save_new_login(harness, &detected).await } - /// GitHub Copilot for OpenCode: GitHub's device flow. The start asks - /// GitHub for the code (the dialog shows it), then a task polls until - /// the user approves. + /// Claude for Pi: pi's own Claude Pro/Max sign-in, on our loopback. + pub(super) async fn start_pi_claude_login(&self) -> Result { + self.reap_spawned_flows(HarnessId::Pi); + let listener = bind_loopback(0).await.map_err(|err| { + EngineError::Other(format!("Could not open the sign-in callback: {err}")) + })?; + let port = listener + .local_addr() + .map_err(|e| EngineError::Other(format!("sign-in callback has no port: {e}")))? + .port(); + let login_id = new_id(); + let (verifier, challenge) = pkce_pair(); + let state = random_url_token(); + let redirect = format!("http://localhost:{port}/callback"); + let url = format!( + "{PI_CLAUDE_AUTHORIZE_URL}?code=true&client_id={CLAUDE_CLIENT_ID}\ + &response_type=code&redirect_uri={}&scope={}&code_challenge={challenge}\ + &code_challenge_method=S256&state={state}", + urlencode(&redirect), + urlencode(PI_CLAUDE_SCOPES), + ); + let task_state = Arc::new(Mutex::new(TaskLoginState { + url: Some(url.clone()), + ..Default::default() + })); + let this = self.clone(); + let outcome_state = task_state.clone(); + let handle = tokio::spawn(async move { + let outcome = tokio::time::timeout( + LOGIN_WAIT, + this.finish_pi_claude_login(listener, &state, &verifier, &redirect), + ) + .await + .unwrap_or_else(|_| Err(EngineError::Other("The sign-in timed out.".into()))); + lock(&outcome_state).outcome = Some(outcome.map_err(|e| e.to_string())); + }); + lock(&self.inner.flows).insert( + login_id.clone(), + LoginFlow::Task { + harness: HarnessId::Pi, + started_at: Instant::now(), + state: task_state, + handle, + home: None, + port: Some(port), + }, + ); + Ok(AgentLoginStart { + login_id, + url, + mode: AgentLoginMode::Browser, + callback_port: Some(port), + }) + } + + async fn finish_pi_claude_login( + &self, + listener: tokio::net::TcpListener, + state: &str, + verifier: &str, + redirect: &str, + ) -> Result<(), EngineError> { + use tokio::io::AsyncWriteExt as _; + let (callback, mut browser) = await_claude_callback(&listener, state).await; + drop(listener); + let result = match callback { + Ok(code) => { + self.redeem_pi_claude_code(&code, state, verifier, redirect) + .await + } + Err(message) => Err(EngineError::Other(message)), + }; + let (status, body) = match &result { + Ok(()) => ( + "200 OK", + "Signed in

Signed in to Claude for Pi.

\ +

You can close this tab and return to Zeron.

" + .to_string(), + ), + Err(error) => ( + "400 Bad Request", + format!( + "Sign-in failed

{}

\ +

Return to Zeron to try again.

", + html_escape(&error.to_string()) + ), + ), + }; + let response = http_response( + status, + &[("Content-Type", "text/html; charset=utf-8")], + &body, + ); + let _ = browser.write_all(response.as_bytes()).await; + let _ = browser.shutdown().await; + result + } + + /// Redeem the code as pi does and save the login in pi's entry format. + async fn redeem_pi_claude_code( + &self, + code: &str, + state: &str, + verifier: &str, + redirect: &str, + ) -> Result<(), EngineError> { + let response = self + .inner + .http + .post(&self.inner.endpoints.claude_loopback_token) + .json(&serde_json::json!({ + "grant_type": "authorization_code", + "client_id": CLAUDE_CLIENT_ID, + "code": code, + "state": state, + "redirect_uri": redirect, + "code_verifier": verifier, + })) + .timeout(Duration::from_secs(15)) + .send() + .await + .map_err(|e| EngineError::Other(format!("token exchange failed: {e}")))?; + if !response.status().is_success() { + let status = response.status(); + // Never echo the body: it can carry token material on odd errors. + return Err(EngineError::Other(format!( + "Anthropic rejected the sign-in ({status}) — try again." + ))); + } + let tokens: serde_json::Value = response + .json() + .await + .map_err(|e| EngineError::Other(format!("token exchange returned junk: {e}")))?; + let (Some(access), Some(refresh)) = ( + str_field(&tokens, "access_token"), + str_field(&tokens, "refresh_token"), + ) else { + return Err(EngineError::Other( + "Anthropic returned no usable tokens — try signing in again.".into(), + )); + }; + let expires_in = tokens + .get("expires_in") + .and_then(|v| v.as_i64()) + .unwrap_or(3600); + let entry = serde_json::json!({ + "type": "oauth", + "refresh": refresh, + "access": access, + "expires": now_ms() + expires_in * 1000 - 5 * 60 * 1000, + }); + // The profile names the plan; the token response already names the + // account (as Claude Code's own sign-in reads it), so a profile call + // that fails (rate limited, say) still signs in, plan unnamed. + let (account_key, profile) = match self.anthropic_identity("anthropic", &access).await { + Some(identity) => identity, + None => token_identity(&tokens).ok_or_else(|| { + EngineError::Other("Could not identify the signed-in Claude account.".into()) + })?, + }; + let detected = Detected::known(account_key, profile, entry).keyed("anthropic"); + self.save_new_login(HarnessId::Pi, &detected).await + } + + /// GitHub Copilot for OpenCode / Pi: GitHub's device flow, with the + /// agent's own OAuth app. The start asks GitHub for the code (the dialog + /// shows it), then a task polls until the user approves. pub(super) async fn start_copilot_login( &self, harness: HarnessId, @@ -251,9 +450,9 @@ impl AgentAccounts { .http .post(format!("{login}/login/device/code")) .header("Accept", "application/json") - .header("User-Agent", "zeron") + .header("User-Agent", copilot_user_agent(harness)) .form(&[ - ("client_id", OPENCODE_COPILOT_CLIENT_ID), + ("client_id", copilot_client_id(harness)), ("scope", "read:user"), ]) .send() @@ -325,9 +524,9 @@ impl AgentAccounts { .http .post(format!("{login}/login/oauth/access_token")) .header("Accept", "application/json") - .header("User-Agent", "zeron") + .header("User-Agent", copilot_user_agent(harness)) .form(&[ - ("client_id", OPENCODE_COPILOT_CLIENT_ID), + ("client_id", copilot_client_id(harness)), ("device_code", device_code), ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), ]) @@ -364,12 +563,15 @@ impl AgentAccounts { } } }; - let entry = serde_json::json!({ - "type": "oauth", - "refresh": token, - "access": token, - "expires": 0, - }); + let entry = match harness { + HarnessId::Pi => self.pi_copilot_entry(&token).await?, + _ => serde_json::json!({ + "type": "oauth", + "refresh": token, + "access": token, + "expires": 0, + }), + }; let (account_key, profile) = self .github_identity("github-copilot", &token, &entry) .await @@ -379,6 +581,230 @@ impl AgentAccounts { let detected = Detected::known(account_key, profile, entry).keyed("github-copilot"); self.save_new_login(harness, &detected).await } + + /// Pi's Copilot entry for a fresh GitHub token, as pi's `/login` writes + /// it: the token exchanged for a Copilot session (refused: the account + /// has no Copilot, said so), then the models it may use. + async fn pi_copilot_entry(&self, github_token: &str) -> Result { + let api = self.inner.endpoints.github_api.trim_end_matches('/'); + let mut request = self + .inner + .http + .get(format!("{api}/copilot_internal/v2/token")) + .header("Accept", "application/json") + .bearer_auth(github_token) + .timeout(Duration::from_secs(15)); + for (name, value) in PI_COPILOT_HEADERS { + request = request.header(name, value); + } + let response = request + .send() + .await + .map_err(|e| EngineError::Other(format!("Couldn't reach GitHub Copilot: {e}")))?; + let status = response.status(); + if matches!(status.as_u16(), 401 | 403 | 404) { + return Err(EngineError::Other( + "That GitHub account has no GitHub Copilot — sign in with one that does.".into(), + )); + } + if !status.is_success() { + // Never echo the body: it may carry token material. + return Err(EngineError::Other(format!( + "GitHub Copilot refused the sign-in ({status}) — try again." + ))); + } + let session: serde_json::Value = response + .json() + .await + .map_err(|e| EngineError::Other(format!("GitHub Copilot returned junk: {e}")))?; + let (Some(access), Some(expires_at)) = ( + str_field(&session, "token"), + session.get("expires_at").and_then(|v| v.as_i64()), + ) else { + return Err(EngineError::Other( + "GitHub Copilot returned no session — try signing in again.".into(), + )); + }; + let mut entry = serde_json::json!({ + "type": "oauth", + "refresh": github_token, + "access": access, + // pi re-exchanges five minutes early, as its own login sets it. + "expires": expires_at * 1000 - 5 * 60 * 1000, + }); + if let Some(models) = self.pi_copilot_models(&access).await + && let Some(map) = entry.as_object_mut() + { + map.insert("availableModelIds".into(), serde_json::json!(models)); + } + Ok(entry) + } + + /// The Copilot models a fresh Pi login may use (pi-ai + /// `parseGitHubCopilotModelCatalog` + `enableGitHubCopilotModels`): + /// those in the account's picker and not disabled by policy, plus the + /// ones it may pick but never enabled, enabled now. `None` when the + /// catalog can't be read (pi lists every model until it refreshes). + async fn pi_copilot_models(&self, copilot_token: &str) -> Option> { + let base = match &self.inner.endpoints.copilot_api { + Some(base) => base.trim_end_matches('/').to_string(), + None => copilot_api_from_token(copilot_token)?, + }; + let headers = |mut request: reqwest::RequestBuilder| { + request = request + .header("Accept", "application/json") + .bearer_auth(copilot_token) + .timeout(Duration::from_secs(10)); + for (name, value) in PI_COPILOT_HEADERS { + request = request.header(name, value); + } + request + }; + let catalog: serde_json::Value = headers(self.inner.http.get(format!("{base}/models"))) + .header("X-GitHub-Api-Version", "2026-06-01") + .send() + .await + .ok() + .filter(|res| res.status().is_success())? + .json() + .await + .ok()?; + let (mut available, to_enable) = + copilot_model_choices(&catalog, base == COPILOT_INDIVIDUAL_API)?; + for id in to_enable.into_iter().take(32) { + let enabled = headers( + self.inner + .http + .post(format!("{base}/models/{}/policy", urlencode(&id))), + ) + .header("openai-intent", "chat-policy") + .header("x-interaction-type", "chat-policy") + .json(&serde_json::json!({ "state": "enabled" })) + .send() + .await; + match enabled { + Ok(res) if res.status().is_success() => { + if !available.contains(&id) { + available.push(id); + } + } + // Rate limited: the rest stay as they are (pi stops too). + Ok(res) if res.status().as_u16() == 429 => break, + _ => {} + } + } + Some(available) + } +} + +/// The account a Claude token response names (`account.uuid`, +/// `account.email_address`, `organization.name`), keyed as +/// `anthropic_identity` keys it: the identity when the profile call fails. +/// The plan isn't in it. +fn token_identity(tokens: &serde_json::Value) -> Option<(String, SlotProfile)> { + let account = tokens.get("account")?; + let email = str_field(account, "email_address")?; + let uuid = str_field(account, "uuid").unwrap_or_else(|| email.clone()); + let organization = tokens + .get("organization") + .and_then(|org| str_field(org, "name")); + Some(( + format!("anthropic:{uuid}"), + SlotProfile { + email, + display_name: None, + organization, + plan: Some("Claude".to_string()), + auth_kind: AgentAuthKind::Oauth, + }, + )) +} + +fn copilot_client_id(harness: HarnessId) -> &'static str { + match harness { + HarnessId::Pi => PI_COPILOT_CLIENT_ID, + _ => OPENCODE_COPILOT_CLIENT_ID, + } +} + +fn copilot_user_agent(harness: HarnessId) -> &'static str { + match harness { + HarnessId::Pi => PI_COPILOT_HEADERS[0].1, + _ => "zeron", + } +} + +/// A Copilot session's API root, from its token's `proxy-ep` (`proxy.X` → +/// `https://api.X`) — only on GitHub Copilot's own hosts, or the individual +/// default when the token names none. +pub(super) fn copilot_api_from_token(token: &str) -> Option { + let Some(proxy) = token + .split(';') + .find_map(|part| part.trim().strip_prefix("proxy-ep=")) + else { + return Some(COPILOT_INDIVIDUAL_API.to_string()); + }; + let host = proxy.trim().trim_start_matches("proxy."); + let host = format!("api.{host}").to_ascii_lowercase(); + let valid = host + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-'); + (valid && super::stores::host_in(&host, &["githubcopilot.com"])) + .then(|| format!("https://{host}")) +} + +/// From a Copilot `/models` reply: the model ids the account can use now, +/// and those it may pick but must enable first. `individual` admits pi's +/// fallback for individual accounts whose picker flags are all off. +pub(super) fn copilot_model_choices( + catalog: &serde_json::Value, + individual: bool, +) -> Option<(Vec, Vec)> { + struct Listed { + id: String, + picker: bool, + policy: Option, + } + let listed: Vec = catalog + .get("data")? + .as_array()? + .iter() + .filter_map(|item| { + let id = str_field(item, "id")?; + let tools = item + .pointer("/capabilities/supports/tool_calls") + .and_then(|v| v.as_bool()); + (tools != Some(false)).then(|| Listed { + id, + picker: item.get("model_picker_enabled").and_then(|v| v.as_bool()) == Some(true), + policy: item + .pointer("/policy/state") + .and_then(|v| v.as_str()) + .map(str::to_string), + }) + }) + .collect(); + let in_picker: Vec = listed + .iter() + .filter(|m| m.picker && m.policy.as_deref() != Some("disabled")) + .map(|m| m.id.clone()) + .collect(); + let fallback = individual && in_picker.is_empty(); + let available = if fallback { + listed + .iter() + .filter(|m| m.policy.as_deref() == Some("enabled")) + .map(|m| m.id.clone()) + .collect() + } else { + in_picker + }; + let to_enable = listed + .iter() + .filter(|m| m.policy.as_deref() == Some("unconfigured") && (m.picker || fallback)) + .map(|m| m.id.clone()) + .collect(); + Some((available, to_enable)) } /// A loopback listener on `port` (0 = any): `localhost` resolves to either diff --git a/crates/engine/src/agent_accounts/provider_tests.rs b/crates/engine/src/agent_accounts/provider_tests.rs index d25ded374..ee89ae9f7 100644 --- a/crates/engine/src/agent_accounts/provider_tests.rs +++ b/crates/engine/src/agent_accounts/provider_tests.rs @@ -6,6 +6,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use super::api_keys::key_rows; use super::stores::*; use super::usage::*; use super::*; @@ -89,7 +90,12 @@ impl MockServer { let mut first = head.lines().next().unwrap_or("").split_whitespace(); let method = first.next().unwrap_or("").to_string(); let path = first.next().unwrap_or("").to_string(); - lock(&hits).push(format!("{method} {path}")); + // (A preview scan elsewhere in the test process probes + // every local listener with `HEAD /`: not a request any + // code here made, so not recorded.) + if method != "HEAD" { + lock(&hits).push(format!("{method} {path}")); + } let (status, reply) = handler(&method, &path, &body); let response = http_response( &format!("{status} X"), @@ -137,6 +143,8 @@ fn mocked(base: &str) -> ProbeEndpoints { grok_usage: format!("{base}/v1/billing?format=credits"), github_api: base.to_string(), github_login: base.to_string(), + copilot_api: Some(base.to_string()), + api_key_check: Some(base.to_string()), openai_auth: base.to_string(), openai_port: 0, nous_portal: base.to_string(), @@ -381,17 +389,26 @@ async fn forgetting_a_live_login_signs_out_only_that_login() { &config.devin_credentials_file, "windsurf_api_key = \"devin-key-1234\"\n", ); + // (OpenCode's Anthropic API key is a login of its own provider: it + // stays when the ChatGPT one goes.) + let not_key = |a: &AgentAccount| a.auth_kind != Some(AgentAuthKind::ApiKey); let snapshot = accounts.list(false).await.unwrap(); for harness in [HarnessId::Grok, HarnessId::Opencode, HarnessId::Devin] { - let live = rows(&snapshot, harness); + let live: Vec<_> = rows(&snapshot, harness).into_iter().filter(not_key).collect(); assert_eq!(live.len(), 1, "{harness:?}"); assert!(live[0].active); - let left = rows( + let left: Vec<_> = rows( &accounts.forget(harness, &live[0].id).await.unwrap(), harness, - ); + ) + .into_iter() + .filter(not_key) + .collect(); assert!(left.is_empty(), "{harness:?}: {left:?}"); - assert!(accounts.read_slots(harness).is_empty(), "{harness:?}"); + assert!( + accounts.read_slots(harness).iter().all(|s| s.profile.auth_kind == AgentAuthKind::ApiKey), + "{harness:?}" + ); } let grok: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&grok_file).unwrap()).unwrap(); @@ -406,10 +423,13 @@ async fn forgetting_a_live_login_signs_out_only_that_login() { assert!(opencode.get("openai").is_none()); assert_eq!(opencode["anthropic"]["key"], "sk-ant-keep"); assert!(!config.devin_credentials_file.exists()); - // Nothing comes back on the next list. + // Nothing comes back on the next list (but the key, still OpenCode's). let snapshot = accounts.list(false).await.unwrap(); for harness in [HarnessId::Grok, HarnessId::Opencode, HarnessId::Devin] { - assert!(rows(&snapshot, harness).is_empty(), "{harness:?}"); + assert!( + rows(&snapshot, harness).into_iter().filter(not_key).next().is_none(), + "{harness:?}" + ); } } @@ -716,18 +736,26 @@ async fn opencode_swaps_one_provider_entry_and_leaves_the_rest() { .to_string() }; write(file, &store(openai_entry("a@example.com", "acct-a"))); - let rows_a = rows(&accounts.list(false).await.unwrap(), HarnessId::Opencode); - assert_eq!(rows_a.len(), 1, "API-key entries aren't accounts"); + let rows_a: Vec<_> = rows(&accounts.list(false).await.unwrap(), HarnessId::Opencode) + .into_iter() + .filter(|a| a.provider.as_deref() == Some("openai")) + .collect(); + assert_eq!(rows_a.len(), 1); assert_eq!(rows_a[0].provider.as_deref(), Some("openai")); assert_eq!(rows_a[0].plan_label.as_deref(), Some("ChatGPT Plus")); assert_eq!(rows_a[0].email.as_deref(), Some("a@example.com")); let a_id = rows_a[0].id.clone(); write(file, &store(openai_entry("b@example.com", "acct-b"))); - assert_eq!( - rows(&accounts.list(false).await.unwrap(), HarnessId::Opencode).len(), - 2 - ); + let listed = rows(&accounts.list(false).await.unwrap(), HarnessId::Opencode); + // Two ChatGPT logins, and the Anthropic API key, shown by its tail only. + assert_eq!(listed.len(), 3); + let key = listed + .iter() + .find(|a| a.provider.as_deref() == Some("anthropic")) + .unwrap(); + assert_eq!(key.email.as_deref(), Some("API key ···keep")); + assert_eq!(key.auth_kind, Some(AgentAuthKind::ApiKey)); accounts.activate(HarnessId::Opencode, &a_id).await.unwrap(); let written: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(file).unwrap()).unwrap(); @@ -932,12 +960,12 @@ async fn chatgpt_sign_in_for_pi_lands_on_the_loopback_and_connects_the_first_log pi.iter() .all(|a| a.plan_label.as_deref() == Some("ChatGPT Pro")) ); - // Claude logins for Pi stay with pi. + // OpenCode has no Claude sign-in of its own: refused, saying what works. let refused = accounts - .start_login_with(HarnessId::Pi, Some("anthropic"), None) + .start_login_with(HarnessId::Opencode, Some("anthropic"), None) .await .unwrap_err(); - assert!(refused.to_string().contains("/login"), "{refused}"); + assert!(refused.to_string().contains("API key"), "{refused}"); } /// Signing in again as the live account (its tokens dead or revoked) makes @@ -1218,13 +1246,15 @@ fn hermes_auth() -> serde_json::Value { ], "openai-codex": [ { "id": "c2", "label": "second@example.com", "auth_type": "oauth", "priority": 1, + "source": "manual:device_code", "access_token": chatgpt_access("second@example.com", "acct-2", "plus") }, { "id": "c1", "label": "first@example.com", "auth_type": "oauth", "priority": 0, + "source": "device_code", "access_token": chatgpt_access("first@example.com", "acct-1", "pro") }, ], "openrouter": [ { "id": "k1", "label": "OPENROUTER_API_KEY", "auth_type": "api_key", "priority": 0, - "access_token": "sk-or" }, + "source": "manual", "access_token": "sk-or" }, ], } }) @@ -1258,10 +1288,18 @@ async fn hermes_lists_its_own_pool_read_only() { "first@example.com", "second@example.com", "nous@example.com", + // A key: its label and last four characters, never more. "OPENROUTER_API_KEY" ] ); - assert!(hermes[0].active && !hermes[1].active && !hermes[2].active); + // Each provider's first entry is the one its models run on: one in use + // per provider group. + assert!(hermes[0].active && !hermes[1].active && hermes[2].active && hermes[3].active); + let groups: Vec<_> = hermes.iter().map(|a| a.provider.clone().unwrap()).collect(); + assert_eq!( + groups, + ["openai-codex", "openai-codex", "nous", "openrouter"] + ); assert!(hermes.iter().all(|a| !a.switchable && a.saved_at.is_none())); assert_eq!(hermes[0].plan_label.as_deref(), Some("ChatGPT Pro")); assert!((hermes[0].usage_windows[0].used_fraction - 0.1).abs() < 1e-6); @@ -1303,7 +1341,7 @@ case "$HERMES_SHARED_AUTH_DIR" in *".login-"*) ;; *) exit 4 ;; esac printf 'To continue, follow these steps:\n\n 1. Open this URL in your browser:\n \033[94mhttps://auth.openai.com/codex/device\033[0m\n\n 2. Enter this code:\n \033[94mQRST-5678\033[0m\n\nWaiting for sign-in...\n' sleep 1 mkdir -p "$HERMES_HOME" -printf '{"active_provider":"openai-codex","credential_pool":{"openai-codex":[{"id":"abc123","label":"new@example.com","auth_type":"oauth","priority":0,"access_token":"x"}]}}' > "$HERMES_HOME/auth.json" +printf '{"active_provider":"openai-codex","credential_pool":{"openai-codex":[{"id":"abc123","label":"new@example.com","auth_type":"oauth","priority":0,"source":"device_code","access_token":"x"}]}}' > "$HERMES_HOME/auth.json" echo 'Added openai-codex OAuth credential #1: "new@example.com"' "#, ); @@ -1641,6 +1679,7 @@ async fn untrusted_endpoints_in_credentials_are_never_sent_a_secret() { ); let hermes = serde_json::json!({ "active_provider": "nous", "credential_pool": { "nous": [ { "id": "n1", "label": "n@example.com", "auth_type": "oauth", "priority": 0, + "source": "device_code", "access_token": "t", "portal_base_url": "https://portal.nousresearch.com.evil.example" }, ]}}); write(&config.hermes_home.join("auth.json"), &hermes.to_string()); @@ -1796,7 +1835,10 @@ async fn a_self_hosted_ghes_login_switches_away_and_back_without_the_network() { let written: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(file).unwrap()).unwrap(); assert_eq!(written["github-copilot"], ghes); - let listed = rows(&accounts.list(false).await.unwrap(), HarnessId::Opencode); + let listed: Vec<_> = rows(&accounts.list(false).await.unwrap(), HarnessId::Opencode) + .into_iter() + .filter(|a| a.provider.as_deref() == Some("github-copilot")) + .collect(); assert_eq!(listed.len(), 2); assert!(listed.iter().any(|a| a.id == ghes_id && a.active)); // Only the github.com login was ever looked up; no request carried the @@ -2071,3 +2113,904 @@ async fn codex_banked_resets_list_persist_and_redeem_against_the_mock() { assert!(accounts.consume_codex_reset_credit(&account, "", "key-3").await.is_err()); assert!(accounts.consume_codex_reset_credit("no-such-account", "credit-2", "key-4").await.is_err()); } + +// ── per-provider accounts (Pi, OpenCode, Hermes) ──────────────────────────── + +fn copilot_entry(github_token: &str) -> serde_json::Value { + serde_json::json!({ + "type": "oauth", + "refresh": github_token, + "access": format!("tid=1;exp=9;proxy-ep=proxy.individual.githubcopilot.com;{github_token}"), + "expires": 1, + }) +} + +#[tokio::test] +async fn copilot_device_sign_in_for_pi_exchanges_the_session_and_keeps_chatgpt() { + let polls = Arc::new(AtomicUsize::new(0)); + let polled = polls.clone(); + let server = MockServer::start(move |method, path, body| match (method, path) { + ("POST", "/login/device/code") => { + // pi's own Copilot app: Copilot's token exchange serves only it. + assert!(body.contains("client_id=Iv1.b507a08c87ecfe98"), "{body}"); + ( + 200, + r#"{"device_code":"dc","user_code":"WXYZ-0001","verification_uri":"https://github.com/login/device","interval":1,"expires_in":900}"#.into(), + ) + } + ("POST", "/login/oauth/access_token") => { + if polled.fetch_add(1, Ordering::SeqCst) == 0 { + (200, r#"{"error":"authorization_pending"}"#.into()) + } else { + (200, r#"{"access_token":"gho_pi","token_type":"bearer"}"#.into()) + } + } + ("GET", "/copilot_internal/v2/token") => ( + 200, + r#"{"token":"tid=1;exp=2;proxy-ep=proxy.individual.githubcopilot.com;sig","expires_at":2000000000}"#.into(), + ), + ("GET", "/models") => ( + 200, + serde_json::json!({ "data": [ + { "id": "gpt-6", "model_picker_enabled": true, "policy": { "state": "enabled" } }, + { "id": "claude-opus-5", "model_picker_enabled": true, "policy": { "state": "unconfigured" } }, + { "id": "o-old", "model_picker_enabled": true, "policy": { "state": "disabled" } }, + { "id": "embed", "model_picker_enabled": false, "capabilities": { "supports": { "tool_calls": false } } }, + ]}) + .to_string(), + ), + ("POST", "/models/claude-opus-5/policy") => { + assert!(body.contains(r#""state":"enabled""#), "{body}"); + (200, "{}".into()) + } + ("GET", "/user") => (200, r#"{"id":7,"login":"pi-octo","name":"Pi Octo"}"#.into()), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let file = config.pi_agent_dir.join("auth.json"); + let chatgpt = openai_entry("a@example.com", "acct-a"); + write( + &file, + &serde_json::json!({ + "openai-codex": chatgpt, + "openrouter": { "type": "api_key", "key": "sk-or-keep" }, + }) + .to_string(), + ); + let start = accounts + .start_login_with(HarnessId::Pi, Some("github-copilot"), None) + .await + .unwrap(); + assert_eq!(start.url, "https://github.com/login/device"); + assert_eq!(start.callback_port, None, "a device code needs no tunnel"); + let polls = settle(&accounts, &start.login_id).await; + assert_eq!( + polls.last().unwrap().status, + AgentLoginStatus::Done, + "{polls:?}" + ); + assert_eq!(server.hits("POST /models/claude-opus-5/policy"), 1); + assert_eq!(server.hits("POST /models/gpt-6/policy"), 0); + + // pi's entry shape: the GitHub token refreshes, the Copilot session is + // the access token; the first Copilot login is in use at once. + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + let copilot = &live["github-copilot"]; + assert_eq!(copilot["type"], "oauth"); + assert_eq!(copilot["refresh"], "gho_pi"); + assert!(copilot["access"].as_str().unwrap().contains("proxy-ep=")); + assert_eq!(copilot["expires"], 2_000_000_000i64 * 1000 - 300_000); + assert_eq!( + copilot["availableModelIds"], + serde_json::json!(["gpt-6", "claude-opus-5"]) + ); + // The ChatGPT login beside it is untouched, and so is everything else. + assert_eq!(live["openai-codex"], chatgpt); + assert_eq!(live["openrouter"]["key"], "sk-or-keep"); + + let pi = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + let copilot_rows: Vec<_> = pi + .iter() + .filter(|a| a.provider.as_deref() == Some("github-copilot")) + .collect(); + assert_eq!(copilot_rows.len(), 1); + assert_eq!(copilot_rows[0].email.as_deref(), Some("pi-octo")); + assert!(copilot_rows[0].active && copilot_rows[0].switchable); + assert!( + pi.iter() + .any(|a| a.provider.as_deref() == Some("openai-codex") && a.active), + "the ChatGPT login stays in use" + ); +} + +#[tokio::test] +async fn a_copilot_sign_in_without_copilot_says_so_and_writes_nothing() { + let server = MockServer::start(|method, path, _| match (method, path) { + ("POST", "/login/device/code") => ( + 200, + r#"{"device_code":"dc","user_code":"NOPE-0000","verification_uri":"https://github.com/login/device","interval":1}"#.into(), + ), + ("POST", "/login/oauth/access_token") => (200, r#"{"access_token":"gho_none"}"#.into()), + ("GET", "/copilot_internal/v2/token") => (404, r#"{"message":"Not Found"}"#.into()), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let start = accounts + .start_login_with(HarnessId::Pi, Some("github-copilot"), None) + .await + .unwrap(); + let polls = settle(&accounts, &start.login_id).await; + let last = polls.last().unwrap(); + assert_eq!(last.status, AgentLoginStatus::Error); + assert!( + last.message + .as_deref() + .unwrap_or_default() + .contains("no GitHub Copilot"), + "{last:?}" + ); + assert!(!config.pi_agent_dir.join("auth.json").exists()); + assert!(accounts.read_slots(HarnessId::Pi).is_empty()); +} + +#[tokio::test] +async fn switching_one_providers_account_never_touches_another_providers_login() { + let server = MockServer::start(|_, path, _| match path { + "/user" => (200, r#"{"id":9,"login":"octo"}"#.into()), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let file = config.pi_agent_dir.join("auth.json"); + let copilot = copilot_entry("gho_keep"); + let store = |chatgpt: serde_json::Value| { + serde_json::json!({ "openai-codex": chatgpt, "github-copilot": copilot }).to_string() + }; + write(&file, &store(openai_entry("a@example.com", "acct-a"))); + accounts.list(false).await.unwrap(); + write(&file, &store(openai_entry("b@example.com", "acct-b"))); + let pi = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + assert_eq!(pi.len(), 3); + // One in use per provider group: b's ChatGPT, and the Copilot login. + let in_use = |rows: &[AgentAccount], provider: &str| -> Vec { + rows.iter() + .filter(|a| a.provider.as_deref() == Some(provider) && a.active) + .map(|a| a.email.clone().unwrap()) + .collect() + }; + assert_eq!(in_use(&pi, "openai-codex"), ["b@example.com"]); + assert_eq!(in_use(&pi, "github-copilot"), ["octo"]); + + let a = pi + .iter() + .find(|r| r.email.as_deref() == Some("a@example.com")) + .unwrap(); + let after = rows( + &accounts.activate(HarnessId::Pi, &a.id).await.unwrap(), + HarnessId::Pi, + ); + assert_eq!(in_use(&after, "openai-codex"), ["a@example.com"]); + assert_eq!(in_use(&after, "github-copilot"), ["octo"]); + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["openai-codex"]["accountId"], "acct-a"); + assert_eq!(live["github-copilot"], copilot, "byte for byte"); +} + +#[cfg(unix)] +#[tokio::test] +async fn hermes_adds_an_xai_account_through_its_own_device_code() { + let tmp = tempfile::tempdir().unwrap(); + let (accounts, _config) = accounts_with(tmp.path(), ProbeEndpoints::default()); + let cli = script( + tmp.path(), + "hermes", + r#"#!/bin/sh +[ "$*" = "auth add xai-oauth --type oauth --no-browser" ] || { echo "bad args: $*" >&2; exit 3; } +printf 'Open this URL to sign in:\n https://accounts.x.ai/device?user_code=XAI-1234\nEnter this code: XAI-1234\nWaiting for approval (polling every 5s)...\n' +sleep 1 +mkdir -p "$HERMES_HOME" +printf '{"active_provider":"openai-codex","credential_pool":{"xai-oauth":[{"id":"x1","label":"grok@example.com","auth_type":"oauth","priority":0,"source":"device_code","access_token":"x"}]}}' > "$HERMES_HOME/auth.json" +"#, + ); + accounts.override_cli(HarnessId::Hermes, cli); + let start = accounts + .start_login_with(HarnessId::Hermes, Some("xai-oauth"), None) + .await + .unwrap(); + assert_eq!(start.url, "https://accounts.x.ai/device?user_code=XAI-1234"); + let polls = settle(&accounts, &start.login_id).await; + assert_eq!( + polls.last().unwrap().status, + AgentLoginStatus::Done, + "{polls:?}" + ); + let hermes = rows(&accounts.list(false).await.unwrap(), HarnessId::Hermes); + assert_eq!(hermes.len(), 1); + assert_eq!(hermes[0].provider.as_deref(), Some("xai-oauth")); + assert!(hermes[0].active && !hermes[0].switchable); +} + +#[test] +fn copilot_sessions_name_their_own_api_and_models() { + assert_eq!( + oauth::copilot_api_from_token("tid=1;proxy-ep=proxy.business.githubcopilot.com;x") + .as_deref(), + Some("https://api.business.githubcopilot.com") + ); + assert_eq!( + oauth::copilot_api_from_token("tid=1;exp=2").as_deref(), + Some("https://api.individual.githubcopilot.com") + ); + // A token naming any other host is never sent there. + assert_eq!( + oauth::copilot_api_from_token("proxy-ep=proxy.evil.example;x"), + None + ); + assert_eq!( + oauth::copilot_api_from_token("proxy-ep=proxy.githubcopilot.com.evil.example"), + None + ); + + let catalog = serde_json::json!({ "data": [ + { "id": "a", "model_picker_enabled": false, "policy": { "state": "enabled" } }, + { "id": "b", "model_picker_enabled": false, "policy": { "state": "unconfigured" } }, + ]}); + // An individual account whose picker flags are all off: pi's fallback. + let (available, enable) = oauth::copilot_model_choices(&catalog, true).unwrap(); + assert_eq!( + (available, enable), + (vec!["a".to_string()], vec!["b".to_string()]) + ); + let (available, enable) = oauth::copilot_model_choices(&catalog, false).unwrap(); + assert!(available.is_empty() && enable.is_empty()); + assert!(oauth::copilot_model_choices(&serde_json::json!({}), true).is_none()); +} + +// ── API keys (Pi, OpenCode, Hermes) ───────────────────────────────────────── + +const OR_KEY: &str = "sk-or-v1-0123456789abcdefZEROTESTkeyWXYZ"; + +/// A mock provider that accepts `OR_KEY` (Bearer) on OpenRouter's key-info +/// path and refuses anything else. +async fn key_server() -> MockServer { + MockServer::start(|method, path, _| match (method, path) { + ("GET", "/api/v1/key") => (200, r#"{"data":{"label":"x"}}"#.into()), + _ => (404, String::new()), + }) + .await +} + +/// Everything zeron wrote for itself under `root` (slots, usage cache, +/// pins…) and every file of the agents' stores, as one string. +fn every_file(root: &Path) -> String { + fn walk(dir: &Path, out: &mut String) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else if let Ok(bytes) = std::fs::read(&path) { + out.push_str(&path.display().to_string()); + out.push('\n'); + out.push_str(&String::from_utf8_lossy(&bytes)); + } + } + } + let mut out = String::new(); + walk(root, &mut out); + out +} + +/// Every log line (any level, any target) while `run` runs, as text. +async fn logged(run: impl std::future::Future) -> (T, String) { + #[derive(Clone, Default)] + struct Sink(Arc>>); + impl std::io::Write for Sink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + lock(&self.0).extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let sink = Sink::default(); + let writer = sink.clone(); + let subscriber = tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let out = run.await; + let text = String::from_utf8_lossy(&lock(&sink.0)).to_string(); + (out, text) +} + +#[tokio::test(flavor = "current_thread")] +async fn a_pi_api_key_is_checked_then_stored_as_pi_stores_it_and_never_shown_or_logged() { + let server = key_server().await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let file = config.pi_agent_dir.join("auth.json"); + let chatgpt = openai_entry("a@example.com", "acct-a"); + write(&file, &serde_json::json!({ "openai-codex": chatgpt }).to_string()); + + let (snapshot, log) = logged(accounts.add_api_key(HarnessId::Pi, "openrouter", OR_KEY, None)).await; + let snapshot = snapshot.unwrap(); + // Checked with the provider, once, before anything was written. + assert_eq!(server.hits("GET /api/v1/key"), 1); + // Pi's own shape, beside the untouched ChatGPT login, owner-only. + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["openrouter"], serde_json::json!({ "type": "api_key", "key": OR_KEY })); + assert_eq!(live["openai-codex"], chatgpt); + #[cfg(unix)] + assert_eq!(mode(&file), 0o600); + // Listed by its last four characters, in use, switchable. + let key_row = rows(&snapshot, HarnessId::Pi) + .into_iter() + .find(|a| a.provider.as_deref() == Some("openrouter")) + .unwrap(); + // Unnamed: "API key" and its last four, over its provider. + assert_eq!(key_row.email.as_deref(), Some("API key ···WXYZ")); + assert_eq!(key_row.plan_label.as_deref(), Some("OpenRouter")); + assert_eq!(key_row.auth_kind, Some(AgentAuthKind::ApiKey)); + assert!(key_row.active && key_row.switchable); + // Never in what the UI gets, never logged, never in its slot's id. + let wire = serde_json::to_string(&snapshot).unwrap(); + assert!(!wire.contains(OR_KEY) && !wire.contains("ZEROTESTkey"), "{wire}"); + assert!(!log.contains(OR_KEY) && !log.contains("ZEROTESTkey"), "{log}"); + // Its slot (for switching back) is the device's own, owner-only. + let slot = accounts + .read_slots(HarnessId::Pi) + .into_iter() + .find(|s| s.store_key.as_deref() == Some("openrouter")) + .unwrap(); + assert!(!slot.account_key.contains(OR_KEY)); + #[cfg(unix)] + { + let slot_file = accounts.slots_dir(HarnessId::Pi).unwrap().join(format!("{}.json", slot.id)); + assert_eq!(mode(&slot_file), 0o600); + } + // Usage is never probed with a key (no request carries it but the check). + accounts.list(true).await.unwrap(); + // (Only the ChatGPT login's usage was asked after.) + assert_eq!(server.hits("GET /api/v1/key"), 1); + assert!( + lock(&server.hits).iter().all(|h| h == "GET /api/v1/key" || h == "GET /backend-api/wham/usage"), + "{:?}", + lock(&server.hits) + ); + // Removed like any login: the entry goes, the rest stays. + let left = rows(&accounts.forget(HarnessId::Pi, &key_row.id).await.unwrap(), HarnessId::Pi); + assert!(left.iter().all(|a| a.provider.as_deref() != Some("openrouter"))); + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert!(live.get("openrouter").is_none()); + assert_eq!(live["openai-codex"], chatgpt); +} + +#[tokio::test] +async fn a_refused_or_malformed_key_is_never_stored_echoed_or_sent_on() { + let server = key_server().await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + // The provider refuses it: said plainly, the key nowhere in the words. + let wrong = "sk-or-v1-WRONGwrongWRONGwrong0000"; + let mocked_refusal = MockServer::start(|_, _, _| (401, format!(r#"{{"error":"bad key {}"}}"#, "sk-or-v1-WRONGwrongWRONGwrong0000"))).await; + let (refusing, _) = accounts_with(tmp.path(), mocked(&mocked_refusal.base)); + let err = refusing + .add_api_key(HarnessId::Pi, "openrouter", wrong, None) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("didn't accept that key"), "{err}"); + assert!(!err.contains(wrong) && !err.contains("WRONG"), "{err}"); + // Not a key at all (a Pi command, a variable, a sentence): refused + // before any request. + for bad in ["!rm -rf ~", "$OPENROUTER_API_KEY", "sk-or v1 two words", "short", "-sk-or-flaglike"] { + let err = accounts + .add_api_key(HarnessId::Pi, "openrouter", bad, None) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("doesn't look like"), "{bad}: {err}"); + } + assert_eq!(server.hits("GET"), 0); + // A provider Zeron doesn't add keys for. + assert!(accounts.add_api_key(HarnessId::Pi, "acme", OR_KEY, None).await.is_err()); + assert!(accounts.add_api_key(HarnessId::ClaudeCode, "anthropic", OR_KEY, None).await.is_err()); + assert!(!config.pi_agent_dir.join("auth.json").exists()); + assert!(accounts.read_slots(HarnessId::Pi).is_empty()); + assert!(!every_file(tmp.path()).contains("WRONG")); +} + +#[tokio::test] +async fn opencode_keys_use_its_shape_and_opencode_2s_own_database_is_left_alone() { + let server = key_server().await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + accounts + .add_api_key(HarnessId::Opencode, "openrouter", OR_KEY, None) + .await + .unwrap(); + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&config.opencode_auth_file).unwrap()) + .unwrap(); + assert_eq!(live["openrouter"], serde_json::json!({ "type": "api", "key": OR_KEY })); + #[cfg(unix)] + assert_eq!(mode(&config.opencode_auth_file), 0o600); + + // OpenCode 2.x reads its own database, not auth.json: refused, said so. + let tmp2 = tempfile::tempdir().unwrap(); + let (accounts2, config2) = accounts_with(tmp2.path(), mocked(&server.base)); + let db = config2.opencode_auth_file.with_file_name("opencode.db"); + std::fs::create_dir_all(db.parent().unwrap()).unwrap(); + rusqlite::Connection::open(&db) + .unwrap() + .execute_batch("CREATE TABLE credential (id text PRIMARY KEY, integration_id text, label text NOT NULL, value text NOT NULL);") + .unwrap(); + let err = accounts2 + .add_api_key(HarnessId::Opencode, "openrouter", OR_KEY, None) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("opencode auth login"), "{err}"); + assert!(!config2.opencode_auth_file.exists()); + assert_eq!(server.hits("GET"), 1, "only the first add was checked"); + let warned = accounts2.list(false).await.unwrap(); + assert!(warned.warnings.iter().any(|w| w.harness == HarnessId::Opencode && w.message.contains("own database"))); +} + +#[cfg(unix)] +#[tokio::test] +async fn a_hermes_key_goes_to_hermes_on_stdin_never_argv_env_or_a_terminal() { + let server = key_server().await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let seen = tmp.path().join("seen"); + let cli = script( + tmp.path(), + "hermes", + &format!( + r#"#!/bin/sh +[ "$*" = "auth add openrouter --type api-key" ] || {{ echo "bad args: $*" >&2; exit 3; }} +case "$*" in *ZEROTEST*) echo "key in argv" >&2; exit 4 ;; esac +env | grep -q ZEROTEST && {{ echo "key in env" >&2; exit 5; }} +( exec 3/dev/null && {{ echo "has a terminal" >&2; exit 6; }} +IFS= read -r key +printf '%s' "$key" > "{seen}" +mkdir -p "$HERMES_HOME" +printf '{{"credential_pool":{{"openrouter":[{{"id":"k9","label":"api-key-1","auth_type":"api_key","priority":0,"source":"manual","access_token":"%s"}}]}}}}' "$key" > "$HERMES_HOME/auth.json" +echo 'Added openrouter credential #1: "api-key-1"' +"#, + seen = seen.display() + ), + ); + accounts.override_cli(HarnessId::Hermes, cli.clone()); + let (snapshot, log) = logged(accounts.add_api_key(HarnessId::Hermes, "openrouter", OR_KEY, None)).await; + let snapshot = snapshot.unwrap(); + assert_eq!(std::fs::read_to_string(&seen).unwrap(), OR_KEY, "read from stdin"); + let hermes = rows(&snapshot, HarnessId::Hermes); + assert_eq!(hermes.len(), 1); + // (Hermes' "api-key-1" is no name: it reads as an unnamed key.) + assert_eq!(hermes[0].email.as_deref(), Some("API key ···WXYZ")); + assert_eq!(hermes[0].plan_label.as_deref(), Some("OpenRouter")); + assert!(!hermes[0].switchable); + let wire = serde_json::to_string(&snapshot).unwrap(); + assert!(!wire.contains(OR_KEY), "{wire}"); + assert!(!log.contains(OR_KEY), "{log}"); + // Hermes keeps it in its own store; zeron keeps no copy of its own. + assert!(accounts.read_slots(HarnessId::Hermes).is_empty()); + assert!(!every_file(&config.data_dir).contains(OR_KEY)); + + // Hermes failing (even echoing the key): its words, the key blanked. + let loud = script( + tmp.path(), + "hermes-loud", + r#"#!/bin/sh +IFS= read -r key +echo "Login failed: provider refused $key" >&2 +exit 1 +"#, + ); + accounts.override_cli(HarnessId::Hermes, loud); + let err = accounts + .add_api_key(HarnessId::Hermes, "openrouter", OR_KEY, None) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("provider refused"), "{err}"); + assert!(!err.contains(OR_KEY) && !err.contains("ZEROTEST"), "{err}"); +} + +#[tokio::test] +async fn a_key_and_a_sign_in_of_one_provider_switch_between_each_other() { + let server = MockServer::start(|method, path, _| match (method, path) { + ("GET", "/v1/models") => (200, r#"{"data":[]}"#.into()), + ("GET", "/api/oauth/profile") => ( + 200, + r#"{"account":{"uuid":"u-1","email_address":"ada@claude.test"},"organization":{"organization_type":"claude_max"}}"#.into(), + ), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let file = config.pi_agent_dir.join("auth.json"); + let claude = serde_json::json!({ "type": "oauth", "refresh": "rt-1", "access": "at-1", "expires": 1 }); + write(&file, &serde_json::json!({ "anthropic": claude }).to_string()); + let key = "sk-ant-api03-ZEROTESTanthropicKEYabcd"; + // A Claude login is live: the key is saved beside it, not swapped in. + let snapshot = accounts.add_api_key(HarnessId::Pi, "anthropic", key, None).await.unwrap(); + let anthropic: Vec<_> = rows(&snapshot, HarnessId::Pi) + .into_iter() + .filter(|a| a.provider.as_deref() == Some("anthropic")) + .collect(); + assert_eq!(anthropic.len(), 2); + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["anthropic"], claude); + let key_row = anthropic.iter().find(|a| a.auth_kind == Some(AgentAuthKind::ApiKey)).unwrap(); + assert!(!key_row.active); + // Switched to: the key is the entry; and back: the Claude login again. + accounts.activate(HarnessId::Pi, &key_row.id).await.unwrap(); + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["anthropic"], serde_json::json!({ "type": "api_key", "key": key })); + let claude_row = anthropic.iter().find(|a| a.auth_kind != Some(AgentAuthKind::ApiKey)).unwrap(); + accounts.activate(HarnessId::Pi, &claude_row.id).await.unwrap(); + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["anthropic"]["refresh"], "rt-1"); +} + +#[tokio::test] +async fn a_refresh_the_agent_made_since_the_last_list_is_kept_when_switching_away() { + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), ProbeEndpoints::default()); + let file = config.pi_agent_dir.join("auth.json"); + let a = openai_entry("a@example.com", "acct-a"); + write(&file, &serde_json::json!({ "openai-codex": a }).to_string()); + accounts.list(false).await.unwrap(); + write( + &file, + &serde_json::json!({ "openai-codex": openai_entry("b@example.com", "acct-b") }).to_string(), + ); + let pi = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + let a_id = pi.iter().find(|r| r.email.as_deref() == Some("a@example.com")).unwrap().id.clone(); + // Pi refreshes b's login (a single-use refresh token, rotated) — and + // zeron switches before any list sees it. + let mut rotated = openai_entry("b@example.com", "acct-b"); + rotated["refresh"] = serde_json::json!("refresh-acct-b-ROTATED"); + write(&file, &serde_json::json!({ "openai-codex": rotated }).to_string()); + accounts.activate(HarnessId::Pi, &a_id).await.unwrap(); + // b's slot holds the rotated token, not the spent one. + let b_slot = accounts + .read_slots(HarnessId::Pi) + .into_iter() + .find(|s| s.profile.email == "b@example.com") + .unwrap(); + assert_eq!(b_slot.credentials["refresh"], "refresh-acct-b-ROTATED"); +} + +#[tokio::test] +async fn claude_for_pi_signs_in_as_pis_own_login_on_this_device_or_for_another() { + let server = MockServer::start(|method, path, body| match (method, path) { + ("POST", "/v1/oauth/token") => { + assert!(body.contains(r#""grant_type":"authorization_code""#), "{body}"); + assert!(body.contains(r#""client_id":"9d1c250a-e61b-44d9-88ed-5944d1962f5e""#), "{body}"); + assert!(body.contains(r#""code_verifier""#), "{body}"); + ( + 200, + r#"{"access_token":"at-pi","refresh_token":"rt-pi","expires_in":28800}"#.into(), + ) + } + ("GET", "/api/oauth/profile") => ( + 200, + r#"{"account":{"uuid":"u-9","email_address":"ada@claude.test"},"organization":{"organization_type":"claude_max","rate_limit_tier":"default_claude_max_20x"}}"#.into(), + ), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let routes = zeron_preview::login::CallbackRoutes::default(); + let config = AgentAccountsConfig::isolated(tmp.path()); + let accounts = AgentAccounts::with_endpoints(config.clone(), mocked(&server.base), routes.clone()); + let file = config.pi_agent_dir.join("auth.json"); + let chatgpt = openai_entry("a@example.com", "acct-a"); + write(&file, &serde_json::json!({ "openai-codex": chatgpt }).to_string()); + // Started for another device (its browser finishes it): its callback is + // served to that device alone, and the provider rode with the request. + let start = accounts + .start_login_with(HarnessId::Pi, Some("anthropic"), Some("device-a")) + .await + .unwrap(); + assert!(start.url.starts_with("https://claude.ai/oauth/authorize?"), "{}", start.url); + let port = start.callback_port.expect("a loopback port"); + assert_eq!(loopback_port(&start.url), Some(port)); + assert!(routes.is_registered(&start.login_id)); + let state = query_param(&start.url, "state"); + // The device that caught the browser's redirect replays it here. + let relayed = accounts + .relay_callback(&start.login_id, "device-a", &format!("/callback?code=c-1&state={state}")) + .await + .unwrap(); + assert_eq!(relayed.status, 200); + let polls = settle(&accounts, &start.login_id).await; + assert_eq!(polls.last().unwrap().status, AgentLoginStatus::Done, "{polls:?}"); + // Pi's own entry shape; the ChatGPT login beside it untouched. + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["anthropic"]["type"], "oauth"); + assert_eq!(live["anthropic"]["refresh"], "rt-pi"); + assert_eq!(live["anthropic"]["access"], "at-pi"); + assert!(live["anthropic"]["expires"].as_i64().unwrap() > now_ms()); + assert_eq!(live["openai-codex"], chatgpt); + let pi = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + let claude = pi.iter().find(|a| a.provider.as_deref() == Some("anthropic")).unwrap(); + assert_eq!(claude.email.as_deref(), Some("ada@claude.test")); + assert!(claude.active); + // Another device can't replay a login that isn't its own. + assert!(!routes.is_registered(&start.login_id) || accounts.relay_callback(&start.login_id, "device-b", "/callback").await.is_err()); +} + +/// Anthropic's profile endpoint rate limited (a 429, as it answered on a +/// real sign-in): the token response names the account, so Pi's Claude +/// sign-in still finishes, and is still that account on the next list. +#[tokio::test] +async fn claude_for_pi_signs_in_when_the_profile_is_rate_limited() { + let server = MockServer::start(|method, path, _body| match (method, path) { + ("POST", "/v1/oauth/token") => ( + 200, + r#"{"access_token":"at-pi","refresh_token":"rt-pi","expires_in":28800,"account":{"uuid":"u-9","email_address":"ada@claude.test"},"organization":{"uuid":"o-1","name":"Ada's Org"}}"#.into(), + ), + ("GET", "/api/oauth/profile") => (429, r#"{"error":"rate_limited"}"#.into()), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let routes = zeron_preview::login::CallbackRoutes::default(); + let config = AgentAccountsConfig::isolated(tmp.path()); + let accounts = AgentAccounts::with_endpoints(config.clone(), mocked(&server.base), routes.clone()); + let start = accounts + .start_login_with(HarnessId::Pi, Some("anthropic"), Some("device-a")) + .await + .unwrap(); + let state = query_param(&start.url, "state"); + accounts + .relay_callback(&start.login_id, "device-a", &format!("/callback?code=c-1&state={state}")) + .await + .unwrap(); + let polls = settle(&accounts, &start.login_id).await; + assert_eq!(polls.last().unwrap().status, AgentLoginStatus::Done, "{polls:?}"); + let live: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(config.pi_agent_dir.join("auth.json")).unwrap(), + ) + .unwrap(); + assert_eq!(live["anthropic"]["refresh"], "rt-pi"); + let pi = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + let claude: Vec<_> = pi.iter().filter(|a| a.provider.as_deref() == Some("anthropic")).collect(); + assert_eq!(claude.len(), 1, "{claude:?}"); + assert_eq!(claude[0].email.as_deref(), Some("ada@claude.test")); + assert!(claude[0].active); +} + +#[tokio::test] +async fn keys_are_named_by_default_or_as_asked_renamed_and_two_keys_stay_two_rows() { + let server = key_server().await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let second = "sk-or-v1-9876543210fedcbaZEROTESTkeyA1B2"; + // The first unnamed: its provider and last four. The second named. + accounts.add_api_key(HarnessId::Pi, "openrouter", OR_KEY, None).await.unwrap(); + let snapshot = accounts + .add_api_key(HarnessId::Pi, "openrouter", second, Some(" Work ")) + .await + .unwrap(); + let keys: Vec<_> = rows(&snapshot, HarnessId::Pi) + .into_iter() + .filter(|a| a.provider.as_deref() == Some("openrouter")) + .collect(); + assert_eq!(keys.len(), 2, "two keys of one provider are two rows"); + let first = keys.iter().find(|a| a.email.as_deref() == Some("API key ···WXYZ")).unwrap(); + assert_eq!(first.plan_label.as_deref(), Some("OpenRouter")); + let work = keys.iter().find(|a| a.email.as_deref() == Some("Work")).unwrap(); + // Named: the last four nowhere (the name tells it apart). + assert_eq!(work.plan_label.as_deref(), Some("OpenRouter · API key")); + // One in use for the provider (the first: the second came beside it). + assert!(first.active && !work.active); + // Live, the second is still the first's (the name changes nothing live). + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(config.pi_agent_dir.join("auth.json")).unwrap()).unwrap(); + assert_eq!(live["openrouter"]["key"], OR_KEY); + + // Renamed, no key asked; kept across lists (the agent's store has no + // name, the slot does). + let renamed = accounts.rename_account(HarnessId::Pi, &first.id, "Personal").await.unwrap(); + assert!(rows(&renamed, HarnessId::Pi).iter().any(|a| a.id == first.id && a.email.as_deref() == Some("Personal"))); + let again = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + assert!(again.iter().any(|a| a.id == first.id && a.email.as_deref() == Some("Personal"))); + // A name never looks like a key — whichever key (the check never reads + // this one: a refusal must say nothing about it). + for keylike in ["my sk-or-v1-0123 key", "ZEROTESTkeyWXYZ0123456", OR_KEY, "AIzaSyB", "work xai-123"] { + let err = accounts.rename_account(HarnessId::Pi, &first.id, keylike).await.unwrap_err(); + assert!(err.to_string().contains("looks like a key"), "{keylike}: {err}"); + } + assert!(accounts.add_api_key(HarnessId::Pi, "openrouter", OR_KEY, Some("sk-or-test")).await.is_err()); + // A short run that happens to be in the key is just a name: no answer + // depends on the key's contents. + for short in ["0123", "v1-0123", "WXYZ team"] { + accounts.rename_account(HarnessId::Pi, &first.id, short).await.unwrap(); + } + // Emptied: its default name again. + let reset = accounts.rename_account(HarnessId::Pi, &first.id, " ").await.unwrap(); + assert!(rows(&reset, HarnessId::Pi).iter().any(|a| a.id == first.id + && a.email.as_deref() == Some("API key ···WXYZ") + && a.plan_label.as_deref() == Some("OpenRouter"))); + // A login isn't renamed (it goes by its own address); a stranger's id + // is no path. + write( + &config.pi_agent_dir.join("auth.json"), + &serde_json::json!({ "openai-codex": openai_entry("a@example.com", "acct-a"), "openrouter": { "type": "api_key", "key": OR_KEY } }).to_string(), + ); + let pi = rows(&accounts.list(false).await.unwrap(), HarnessId::Pi); + let login = pi.iter().find(|a| a.provider.as_deref() == Some("openai-codex")).unwrap(); + assert!(accounts.rename_account(HarnessId::Pi, &login.id, "Mine").await.is_err()); + assert!(accounts.rename_account(HarnessId::Pi, "../../etc/passwd", "x").await.is_err()); + // The names travel in the list; no key ever does. + let wire = serde_json::to_string(&accounts.list(false).await.unwrap()).unwrap(); + assert!(!wire.contains("ZEROTESTkey"), "{wire}"); +} + +#[cfg(unix)] +#[tokio::test] +async fn a_hermes_key_is_named_by_hermes_own_label() { + let server = key_server().await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, _config) = accounts_with(tmp.path(), mocked(&server.base)); + let cli = script( + tmp.path(), + "hermes", + r#"#!/bin/sh +[ "$*" = "auth add openrouter --type api-key --label=Work" ] || { echo "bad args: $*" >&2; exit 3; } +IFS= read -r key +mkdir -p "$HERMES_HOME" +printf '{"credential_pool":{"openrouter":[{"id":"k9","label":"Work","auth_type":"api_key","priority":0,"source":"manual","access_token":"%s"}]}}' "$key" > "$HERMES_HOME/auth.json" +"#, + ); + accounts.override_cli(HarnessId::Hermes, cli); + let snapshot = accounts + .add_api_key(HarnessId::Hermes, "openrouter", OR_KEY, Some("Work")) + .await + .unwrap(); + let hermes = rows(&snapshot, HarnessId::Hermes); + assert_eq!(hermes[0].email.as_deref(), Some("Work")); + // Hermes names its own: not renamed here. + assert!(accounts.rename_account(HarnessId::Hermes, &hermes[0].id, "Other").await.is_err()); +} + +#[tokio::test] +async fn hermes_lists_only_what_hermes_itself_would_use() { + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), ProbeEndpoints::default()); + write( + &config.hermes_home.join("auth.json"), + &serde_json::json!({ + "active_provider": "openai-codex", + "credential_pool": { + "openai-codex": [ + { "id": "c1", "label": "first@example.com", "auth_type": "oauth", "priority": 0, + "source": "device_code", + "access_token": chatgpt_access("first@example.com", "acct-1", "pro") }, + ], + // Borrowed from the GitHub CLI: Hermes never picks it. + "copilot": [ + { "id": "g1", "label": "gh auth token", "auth_type": "oauth", "priority": 0, + "source": "gh_cli", "access_token": "gho_borrowed" }, + ], + // Seeded from a variable: counted only while it holds a key. + "deepseek": [ + { "id": "d1", "label": "DEEPSEEK_API_KEY", "auth_type": "api_key", "priority": 0, + "source": "env:ZERON_TEST_HERMES_DEEPSEEK", "access_token": "sk-ds" }, + ], + "xai": [ + { "id": "x1", "label": "XAI_API_KEY", "auth_type": "api_key", "priority": 0, + "source": "env:ZERON_TEST_HERMES_GONE", "access_token": "xai-gone" }, + ], + } + }) + .to_string(), + ); + write(&config.hermes_home.join(".env"), "ZERON_TEST_HERMES_DEEPSEEK=sk-live\nZERON_TEST_HERMES_GONE=\n"); + let hermes = rows(&accounts.list(false).await.unwrap(), HarnessId::Hermes); + let providers: Vec<_> = hermes.iter().map(|a| a.provider.clone().unwrap()).collect(); + assert_eq!(providers, ["openai-codex", "deepseek"]); + // One per provider, each in use for its provider's models; none switchable. + assert!(hermes.iter().all(|a| a.active && !a.switchable)); +} + +#[test] +fn a_keys_last_four_show_once_and_an_environment_variable_never() { + let key = "sk-or-v1-0123456789abcdefWXYZ"; + assert_eq!( + key_rows("OpenRouter", Some(key), None, false), + ("API key ···WXYZ".to_string(), "OpenRouter".to_string()) + ); + assert_eq!( + key_rows("OpenRouter", Some(key), Some("Work"), false), + ("Work".to_string(), "OpenRouter · API key".to_string()) + ); + assert_eq!( + key_rows("OpenRouter", Some(key), Some("OPENROUTER_API_KEY"), true), + ("API key ···WXYZ".to_string(), "OpenRouter · from environment".to_string()) + ); +} + +#[tokio::test] +async fn a_hermes_key_from_the_environment_never_shows_its_variable() { + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), ProbeEndpoints::default()); + write( + &config.hermes_home.join("auth.json"), + &serde_json::json!({ "credential_pool": { "openrouter": [ + { "id": "e1", "label": "OPENROUTER_API_KEY", "auth_type": "api_key", "priority": 0, + "source": "env:OPENROUTER_API_KEY", "access_token": "sk-or-v1-envKEY0000ab12" }, + ]}}) + .to_string(), + ); + write(&config.hermes_home.join(".env"), "OPENROUTER_API_KEY=sk-or-v1-envKEY0000ab12\n"); + let hermes = rows(&accounts.list(false).await.unwrap(), HarnessId::Hermes); + assert_eq!(hermes[0].email.as_deref(), Some("API key ···ab12")); + assert_eq!(hermes[0].plan_label.as_deref(), Some("OpenRouter · from environment")); +} + +#[test] +fn a_keys_name_is_judged_without_the_key() { + use super::api_keys::key_name; + assert_eq!(key_name(" Work ").unwrap().as_deref(), Some("Work")); + assert_eq!(key_name("").unwrap(), None); + for keylike in ["sk-ant-api03", "Personal SK-OR-xyz", "abcdefghijklmnop", "ghp_abc", "a_b-c_d-e_f-g_h-i"] { + assert!(key_name(keylike).is_err(), "{keylike}"); + } + for fine in ["Work", "Personal 2", "OpenRouter team", "my-org/prod key"] { + assert!(key_name(fine).is_ok(), "{fine}"); + } +} + +#[tokio::test] +async fn a_switch_over_a_login_it_cant_identify_is_refused_and_the_login_kept() { + // Claude's profile call rate limited: the live login goes unidentified. + let server = MockServer::start(|method, path, _| match (method, path) { + ("GET", "/v1/models") => (200, r#"{"data":[]}"#.into()), + ("GET", "/api/oauth/profile") => (429, r#"{"error":"rate_limited"}"#.into()), + _ => (404, String::new()), + }) + .await; + let tmp = tempfile::tempdir().unwrap(); + let (accounts, config) = accounts_with(tmp.path(), mocked(&server.base)); + let file = config.pi_agent_dir.join("auth.json"); + let claude = serde_json::json!({ "type": "oauth", "refresh": "rt-only-here", "access": "at-1", "expires": 1 }); + write(&file, &serde_json::json!({ "anthropic": claude }).to_string()); + let snapshot = accounts + .add_api_key(HarnessId::Pi, "anthropic", "sk-ant-api03-ZEROTESTkeyLOCK0000", None) + .await + .unwrap(); + let key_row = rows(&snapshot, HarnessId::Pi) + .into_iter() + .find(|a| a.auth_kind == Some(AgentAuthKind::ApiKey)) + .unwrap(); + let err = accounts.activate(HarnessId::Pi, &key_row.id).await.unwrap_err(); + assert!(err.to_string().contains("Couldn't confirm the login in use"), "{err}"); + // The login no slot holds is still Pi's, untouched. + let live: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(live["anthropic"], claude); +} diff --git a/crates/engine/src/agent_accounts/stores.rs b/crates/engine/src/agent_accounts/stores.rs index 922dadd13..623d6bc83 100644 --- a/crates/engine/src/agent_accounts/stores.rs +++ b/crates/engine/src/agent_accounts/stores.rs @@ -25,24 +25,35 @@ //! key}`), re-read on every request. zeron manages the OAuth entries of //! `openai` (ChatGPT) and `github-copilot`; a swap rewrites that one entry //! and leaves every other provider byte-for-byte. OpenCode has no lock of -//! its own. API-key entries aren't accounts and are left alone. +//! its own. API keys are `{type: "api", key}` entries ([`super::api_keys`]), +//! listed and switched like any login (OpenCode 2.x keeps its logins in +//! its own database instead: zeron says so and adds none there). //! Anthropic OAuth was removed from OpenCode upstream and is not offered. //! - **Pi** — `$PI_CODING_AGENT_DIR/auth.json` (default `~/.pi/agent`, //! 0600, guarded by proper-lockfile's `auth.json.lock` DIRECTORY): the //! same per-provider shape (`openai-codex`, `anthropic`, `github-copilot`), //! hot-reloaded by running agents. Swap = rewrite one entry under that -//! lock. Add account = ChatGPT only (zeron's own loopback, see -//! [`super::oauth`]); Claude and Copilot logins stay with pi's `/login` — -//! minting Claude Code OAuth for a third-party agent is not something -//! zeron should do, and pi's Copilot login is an internal token exchange. +//! lock (Pi refreshes under the same lock; a switch saves the login it +//! replaces with the tokens it has then, and refuses over one it can't +//! identify). Add account = ChatGPT and Claude (zeron's own loopback, +//! Claude being Pi's own Claude Pro/Max sign-in, a grant of its own) and +//! GitHub Copilot (device code, then pi's own Copilot exchange) — see +//! [`super::oauth`]; API keys as `{type: "api_key", key}` entries (see +//! [`super::api_keys`]). Pi's other OAuth logins (xAI, Kimi, Meta, +//! OpenRouter, ChatGPT-direct `openai`) aren't listed: zeron can't tell +//! their accounts apart yet. //! - **Hermes** — `$HERMES_HOME/auth.json` (default `~/.hermes`): Hermes //! keeps EVERY account itself, in `credential_pool[provider]`, and picks //! (fill-first by `priority`, or round-robin) and refreshes them on its //! own. A running Hermes writes its in-memory pool back over the file, so -//! a zeron reorder would be silently undone — zeron lists the pool (the -//! active provider's first entry is "in use"), probes usage, and adds -//! accounts through `hermes auth add` (device code; Hermes appends to its -//! own pool under its own lock). It never rewrites the pool. +//! a zeron reorder would be silently undone — zeron lists the pool (each +//! provider's first entry by priority is that provider's "in use": a run +//! on one of its models fills from it first), probes usage, and adds +//! accounts through `hermes auth add` (device code, or an API key on its +//! stdin; Hermes appends to its own pool under its own lock). It never +//! rewrites the pool. Only entries Hermes itself would use are listed +//! (its `_pool_entry_is_explicit`): one it borrowed — the GitHub CLI's +//! token, Claude Code's login — Hermes never picks, so neither is shown. //! //! Opaque tokens (Pi's Claude login, Copilot tokens) carry no identity: a //! live entry is matched to its slot by token, else identified ONCE per token @@ -158,14 +169,16 @@ pub(super) fn upstream_vendor(store_key: &str) -> &'static str { } } -/// The logins `hermes auth add` can run unattended (device codes). -pub(super) const HERMES_LOGINS: &[&str] = &["openai-codex", "nous"]; +/// The logins `hermes auth add` can run unattended (device codes): its +/// ChatGPT, Nous Portal and xAI flows print a page and a code, then poll. +/// (Its Claude flow wants a pasted code; Qwen imports Qwen CLI's login; +/// OpenRouter mints an API key; MiniMax wasn't verified.) +pub(super) const HERMES_LOGINS: &[&str] = &["openai-codex", "nous", "xai-oauth"]; pub(super) fn unsupported_login(harness: HarnessId, provider: &str) -> EngineError { let reason = match (harness, provider) { - (HarnessId::Pi, "anthropic") => { - "Claude logins for Pi stay with pi's own /login — zeron only mints Claude Code \ - logins for Claude Code." + (HarnessId::Opencode, "anthropic") => { + "OpenCode has no Claude sign-in of its own — add an Anthropic API key instead." .to_string() } _ => format!( @@ -585,6 +598,19 @@ pub(super) fn merge_json_entry( key: &str, entry: Option<&serde_json::Value>, lock: StoreLock, +) -> Result<(), EngineError> { + merge_json_entry_with(file, key, entry, lock, &mut |_| Ok(())) +} + +/// [`merge_json_entry`], showing `before_write` the entry being replaced +/// (under the lock, on the read the write is compared against); its error +/// stops the write, the store untouched. +pub(super) fn merge_json_entry_with( + file: &Path, + key: &str, + entry: Option<&serde_json::Value>, + lock: StoreLock, + before_write: &mut dyn FnMut(Option<&serde_json::Value>) -> Result<(), EngineError>, ) -> Result<(), EngineError> { // Held for its Drop (the unlock) only. #[allow(dead_code)] @@ -618,6 +644,7 @@ pub(super) fn merge_json_entry( })?, None => serde_json::json!({}), }; + before_write(store.get(key))?; if let Some(map) = store.as_object_mut() { match entry { Some(entry) => { @@ -833,7 +860,7 @@ impl AgentAccounts { } } - /// The live entry under `store_key`, if it's an OAuth login. + /// The live entry under `store_key`, if it's an OAuth login or an API key. pub(super) fn live_keyed_entry( &self, harness: HarnessId, @@ -841,10 +868,40 @@ impl AgentAccounts { ) -> Option { read_json(&self.keyed_file(harness))? .get(store_key) - .filter(|entry| oauth_entry(entry)) + .filter(|entry| { + oauth_entry(entry) || api_keys::key_entry_secret(harness, entry).is_some() + }) .cloned() } + /// [`Self::write_keyed_entry`] for a switch: `before_write` sees the + /// entry being replaced, under the agent's own lock, right before the + /// write — and refuses it if that isn't the login the switch saved. + pub(super) fn swap_keyed_entry( + &self, + harness: HarnessId, + store_key: &str, + entry: &serde_json::Value, + before_write: &mut dyn FnMut(Option<&serde_json::Value>) -> Result<(), EngineError>, + ) -> Result<(), EngineError> { + let file = self.keyed_file(harness); + merge_json_entry_with( + &file, + store_key, + Some(entry), + self.keyed_lock(harness), + before_write, + ) + } + + fn keyed_lock(&self, harness: HarnessId) -> StoreLock { + let file = self.keyed_file(harness); + match harness { + HarnessId::Pi => StoreLock::Dir(lock_path(&file)), + _ => StoreLock::File(file.with_file_name("auth.json.zeron-lock")), + } + } + /// Replace ONE provider's entry in OpenCode's / Pi's store, keeping every /// other key as it is (see [`merge_json_entry`]). Pi: under its own /// proper-lockfile lock. OpenCode takes no lock of its own, so zeron @@ -857,11 +914,7 @@ impl AgentAccounts { entry: Option<&serde_json::Value>, ) -> Result<(), EngineError> { let file = self.keyed_file(harness); - let lock = match harness { - HarnessId::Pi => StoreLock::Dir(lock_path(&file)), - _ => StoreLock::File(file.with_file_name("auth.json.zeron-lock")), - }; - merge_json_entry(&file, store_key, entry, lock) + merge_json_entry(&file, store_key, entry, self.keyed_lock(harness)) } /// The live per-provider logins of OpenCode / Pi: `(identified, @@ -885,6 +938,15 @@ impl AgentAccounts { None => unidentified.push(unresolved(store_key, upstream)), } } + // API keys, whichever provider: identified locally by a digest of + // the key, never by sending it anywhere. + if let Some(map) = store.as_object() { + for (store_key, entry) in map { + if let Some(detected) = api_keys::key_detected(harness, store_key, entry) { + resolved.push(detected); + } + } + } (resolved, unidentified) } @@ -895,8 +957,11 @@ impl AgentAccounts { harness: HarnessId, store_key: &str, ) -> Option> { - let upstream = upstream_of(harness, store_key)?; let entry = self.live_keyed_entry(harness, store_key)?; + if api_keys::key_entry_secret(harness, &entry).is_some() { + return Some(api_keys::key_detected(harness, store_key, &entry)); + } + let upstream = upstream_of(harness, store_key)?; Some( self.identify_entry(harness, store_key, upstream, &entry) .await, @@ -977,24 +1042,32 @@ impl AgentAccounts { } /// Claude's profile for a live access token (`user:profile` scope). - async fn anthropic_identity( + pub(super) async fn anthropic_identity( &self, store_key: &str, access_token: &str, ) -> Option<(String, SlotProfile)> { - let profile: serde_json::Value = self + let response = self .inner .http .get(&self.inner.endpoints.claude_profile) .bearer_auth(access_token) .header("anthropic-beta", "oauth-2025-04-20") .send() - .await - .ok() - .filter(|res| res.status().is_success())? - .json() - .await - .ok()?; + .await; + // (The status only: never the body or the token.) + let response = match response { + Ok(res) if res.status().is_success() => res, + Ok(res) => { + tracing::warn!(status = %res.status(), "Claude profile lookup refused"); + return None; + } + Err(error) => { + tracing::warn!(error = %error.without_url(), "Claude profile lookup failed"); + return None; + } + }; + let profile: serde_json::Value = response.json().await.ok()?; let account = profile.get("account")?; let org = profile.get("organization").cloned().unwrap_or_default(); let email = str_field(account, "email_address")?; @@ -1086,8 +1159,10 @@ impl AgentAccounts { // ── Hermes ────────────────────────────────────────────────────────────── /// Hermes' credential pool as rows (never persisted as slots — the pool - /// is Hermes' own), plus the account keys in use: the active provider's - /// first entry by priority (fill-first, Hermes' default strategy). + /// is Hermes' own), plus the account keys in use: each provider's first + /// entry by priority (fill-first, Hermes' default strategy — a model of + /// that provider runs on it). The active provider's rows come first, so + /// an app reading one "in use" for all of Hermes still finds its own. pub(super) fn hermes_slots(&self) -> (Vec, HashSet) { let mut slots = Vec::new(); let mut active = HashSet::new(); @@ -1106,9 +1181,12 @@ impl AgentAccounts { let Some(entries) = pool.get(provider).and_then(|e| e.as_array()) else { continue; }; + // Only what Hermes itself would use: an entry it borrowed (the + // GitHub CLI's token, Claude Code's login) it never picks. let mut entries: Vec<&serde_json::Value> = entries .iter() .filter(|e| str_field(e, "id").is_some()) + .filter(|e| hermes_entry_is_explicit(e, &self.inner.config.hermes_home)) .collect(); entries.sort_by_key(|e| { e.get("priority") @@ -1118,7 +1196,7 @@ impl AgentAccounts { for (ix, entry) in entries.iter().enumerate() { let id = str_field(entry, "id").unwrap_or_default(); let account_key = format!("{provider}:{id}"); - if ix == 0 && active_provider.as_deref() == Some(provider.as_str()) { + if ix == 0 { active.insert(account_key.clone()); } slots.push(Slot { @@ -1177,7 +1255,7 @@ impl AgentAccounts { Ok(dirs) } - async fn cli_command( + pub(super) async fn cli_command( &self, harness: HarnessId, args: &[&str], @@ -1399,6 +1477,64 @@ pub(super) struct DevinLoginDirs { pub(super) url_file: PathBuf, } +/// The pool sources Hermes counts as the user's own (hermes_cli/auth.py +/// `_EXPLICIT_POOL_SOURCES`): what a Hermes sign-in or `hermes auth add` +/// made. Anything else it found itself (`gh_cli`, `claude_code`, +/// `qwen-cli`) is "ambient borrowed": Hermes never offers or picks it. +const HERMES_EXPLICIT_SOURCES: &[&str] = &["device_code", "loopback_pkce", "hermes_pkce", "manual"]; + +/// Hermes' own `_pool_entry_is_explicit`: an entry it made, or one seeded +/// from an environment variable that still holds a key — in Hermes' `.env` +/// (read first, as Hermes reads it) or the environment. +pub(super) fn hermes_entry_is_explicit(entry: &serde_json::Value, hermes_home: &Path) -> bool { + let raw = str_field(entry, "source").unwrap_or_default(); + let source = raw.trim().to_ascii_lowercase(); + if source.starts_with("env:") { + // (The variable as written: names are case-sensitive.) + let var = raw.trim().get(4..).unwrap_or_default().trim(); + return !var.is_empty() && hermes_env_secret(var, hermes_home); + } + !source.is_empty() + && (HERMES_EXPLICIT_SOURCES.contains(&source.as_str()) || source.starts_with("manual:")) +} + +/// Whether `var` holds a key for Hermes: its `.env` first, then the +/// environment (Hermes' `get_env_value_prefer_dotenv`). +fn hermes_env_secret(var: &str, hermes_home: &Path) -> bool { + let usable = |value: &str| { + let value = value.trim().trim_matches(['"', '\'']).trim(); + !value.is_empty() + }; + // (Only a regular file of a sane size: no FIFO or runaway file is read + // while the accounts are listed.) + let env_file = hermes_home.join(".env"); + let readable = std::fs::metadata(&env_file).is_ok_and(|m| m.is_file() && m.len() <= 1 << 20); + if readable && let Ok(text) = std::fs::read_to_string(&env_file) { + for line in text.lines() { + let line = line.trim(); + let line = line.strip_prefix("export ").unwrap_or(line); + if let Some((name, value)) = line.split_once('=') + && name.trim() == var + { + return usable(value); + } + } + } + std::env::var(var).is_ok_and(|value| usable(&value)) +} + +/// The label `hermes auth add` gives a key nobody named ("api-key-2"). +fn is_hermes_default_key_label(label: &str) -> bool { + label + .strip_prefix("api-key-") + .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + +/// A Hermes pool entry's secret (`access_token`, an API key's too). +fn access_key(entry: &serde_json::Value) -> Option { + str_field(entry, "access_token") +} + fn hermes_profile(provider: &str, entry: &serde_json::Value, ix: usize) -> SlotProfile { let access = str_field(entry, "access_token") .and_then(|t| jwt_claims(&t)) @@ -1416,8 +1552,27 @@ fn hermes_profile(provider: &str, entry: &serde_json::Value, ix: usize) -> SlotP other => title_words(other), }; let api_key = str_field(entry, "auth_type").as_deref() == Some("api_key"); + // A key reads as Zeron's own do ([`api_keys::key_rows`]): its label + // only when someone named it — never Hermes' "api-key-N", never the + // variable an env-seeded one came from. + let (label, plan) = if api_key { + let source = str_field(entry, "source").unwrap_or_default(); + let from_env = source.trim().to_ascii_lowercase().starts_with("env:"); + let named = str_field(entry, "label") + .filter(|label| !from_env && !is_hermes_default_key_label(label)); + let key = access_key(entry).filter(|key| api_keys::valid_key(key)); + let (title, line) = api_keys::key_rows( + &zeron_proto::providers::account_group_label(HarnessId::Hermes, provider), + key.as_deref(), + named.as_deref(), + from_env, + ); + (Some(title), Some(line)) + } else { + (str_field(entry, "label"), plan) + }; SlotProfile { - email: str_field(entry, "label") + email: label .or_else(|| { access .get("https://api.openai.com/profile") @@ -1441,7 +1596,7 @@ pub(super) fn scan_grok_url(output: &str) -> Option { } pub(super) fn scan_hermes_url(output: &str) -> Option { - scan_https_url(output, &["nousresearch.com", "openai.com"]) + scan_https_url(output, &["nousresearch.com", "openai.com", "x.ai"]) } /// Devin's sign-in page — its CLI-auth page (`/auth/cli/…`) or the Windsurf diff --git a/crates/engine/src/agent_accounts/usage.rs b/crates/engine/src/agent_accounts/usage.rs index af00d9586..4dd93b920 100644 --- a/crates/engine/src/agent_accounts/usage.rs +++ b/crates/engine/src/agent_accounts/usage.rs @@ -261,6 +261,13 @@ impl AgentAccounts { }), }; } + // An API key has no plan to report (and is never sent to a usage + // endpoint). + if api_keys::key_entry_secret(harness, creds).is_some() { + return Err(ProbeError::NoCredentials { + why: NoCredentials::ApiKey, + }); + } match upstream_of(harness, key) { Some(Upstream::OpenAi) => { let access = str_field(creds, "access").ok_or(missing)?; diff --git a/crates/engine/src/chat_persistence.rs b/crates/engine/src/chat_persistence.rs index 9a986bac0..1f9e1d6b6 100644 --- a/crates/engine/src/chat_persistence.rs +++ b/crates/engine/src/chat_persistence.rs @@ -1191,6 +1191,8 @@ mod tests { /// token every 120 ms (an agent writing) beside 14 small chats edited /// every 2 s, through the real 1 s persister, 60 s per mode. "Before" /// refuses deltas, so every save is whole, as it was. + // (Unix only: it reads CPU time with getrusage.) + #[cfg(unix)] #[test] #[ignore = "requires ZERON_DELTA_WHALE; 2 minutes; prints bytes/min and CPU"] fn live_like_bytes_and_cpu_before_and_after() { diff --git a/crates/engine/src/desktop_notify.rs b/crates/engine/src/desktop_notify.rs index c395531a0..e27315b91 100644 --- a/crates/engine/src/desktop_notify.rs +++ b/crates/engine/src/desktop_notify.rs @@ -31,6 +31,14 @@ use zeron_proto::{Chat, ConnectivityState, HarnessUpdatePhase, HarnessUpdateStat static ENABLED: AtomicBool = AtomicBool::new(false); +/// How long a finish waits to stand before it rings. The person's own +/// message often comes with one: a steer or a queued row taken as a turn +/// ends publishes that end with Working (their message carries the turn on), +/// and a send that replaces the runtime marks the old turn's end a moment +/// before the new one starts. Neither is "finished"; a turn that follows +/// within this window takes the finish with it. +const DONE_SETTLE: chrono::Duration = chrono::Duration::seconds(2); + /// This process shows desktop banners: engines assembled from now on post /// them (and advertise [`zeron_proto::capabilities::DESKTOP_NOTIFICATIONS_V1`]). pub fn enable() { @@ -222,7 +230,12 @@ impl Prefs { /// What a banner asked for by something other than a session (a plugin's, /// through `PostNotification`) came to: shown, or why not. -pub(crate) fn asked_outcome(prefs_enabled: bool, background_only: bool, focused: bool, desktop: bool) -> &'static str { +pub(crate) fn asked_outcome( + prefs_enabled: bool, + background_only: bool, + focused: bool, + desktop: bool, +) -> &'static str { if !desktop { "unavailable" } else if !prefs_enabled { @@ -237,7 +250,13 @@ pub(crate) fn asked_outcome(prefs_enabled: bool, background_only: bool, focused: /// A banner asked for (a plugin's): shown as the engine's own are, under /// the same Settings (`notificationsEnabled`, "only when in the /// background"), clicking it opening `target` (a session). What it came to. -pub(crate) fn post_asked(data_dir: &Path, focus: &ViewportFocus, title: &str, body: &str, target: Option<&str>) -> &'static str { +pub(crate) fn post_asked( + data_dir: &Path, + focus: &ViewportFocus, + title: &str, + body: &str, + target: Option<&str>, +) -> &'static str { let prefs = Prefs::read(data_dir); let outcome = asked_outcome(prefs.enabled, prefs.background_only, focus.any(), enabled()); if outcome == "posted" { @@ -261,7 +280,9 @@ pub(crate) fn post_for( std::sync::LazyLock::new(Default::default); let body: String = body.chars().take(500).collect(); let paced = { - let mut pace = PACE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut pace = PACE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); !asked_in_time(pace.entry(source.to_owned()).or_default(), Instant::now()) }; if paced { @@ -273,11 +294,19 @@ pub(crate) fn post_for( /// Whether one more banner from a source may show, given when its last /// ones did: at most [`ASKED_PER_MINUTE`] a minute, [`ASKED_APART`] apart. -pub(crate) fn asked_in_time(history: &mut std::collections::VecDeque, now: Instant) -> bool { - while history.front().is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) { +pub(crate) fn asked_in_time( + history: &mut std::collections::VecDeque, + now: Instant, +) -> bool { + while history + .front() + .is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) + { history.pop_front(); } - let apart = history.back().is_none_or(|at| now.duration_since(*at) >= ASKED_APART); + let apart = history + .back() + .is_none_or(|at| now.duration_since(*at) >= ASKED_APART); if apart && history.len() < ASKED_PER_MINUTE { history.push_back(now); return true; @@ -316,6 +345,9 @@ struct Notifier { focus: ViewportFocus, post: Post, baselines: HashMap, + /// Finishes waiting to stand ([`DONE_SETTLE`]): chat → its title and + /// when it rings. + settling: HashMap)>, connectivity: ConnectivityNotificationState, updates_seen: HashSet, } @@ -328,6 +360,7 @@ impl Notifier { focus, post, baselines: HashMap::new(), + settling: HashMap::new(), connectivity: ConnectivityNotificationState::default(), updates_seen: HashSet::new(), } @@ -356,15 +389,56 @@ impl Notifier { if !chat.is_some_and(Chat::is_top_level) { continue; } + // A turn going on (or asking, or failing) takes a waiting + // finish with it. + if status.indicator != Indicator::None { + self.settling.remove(&session.chat_id); + } if let Some(prev) = prev && let Some(ping) = status.ping_since(&prev, false) { let title = chat .and_then(|chat| chat.title.clone()) .unwrap_or_else(|| "New session".into()); - due.push((title, ping, session.chat_id.clone())); + match ping { + // Published with the next turn already running: the + // person's message carried it on, nothing finished. + Ping::Done if status.indicator == Indicator::Working => {} + Ping::Done => { + self.settling + .insert(session.chat_id.clone(), (title, now + DONE_SETTLE)); + } + _ => due.push((title, ping, session.chat_id.clone())), + } } } + self.post_due(due); + } + + /// When the next waiting finish rings. + fn next_settled(&self) -> Option> { + self.settling.values().map(|(_, at)| *at).min() + } + + /// Ring the finishes that have stood for [`DONE_SETTLE`]. + fn flush(&mut self, now: chrono::DateTime) { + let stood: Vec = self + .settling + .iter() + .filter(|(_, (_, at))| *at <= now) + .map(|(chat, _)| chat.clone()) + .collect(); + let due = stood + .into_iter() + .filter_map(|chat| { + let (title, _) = self.settling.remove(&chat)?; + Some((title, Ping::Done, chat)) + }) + .collect(); + self.post_due(due); + } + + fn post_due(&mut self, due: Vec<(String, Ping, String)>) { if due.is_empty() || self.allowed().is_none() { return; } @@ -464,6 +538,7 @@ pub(crate) fn spawn(core: &crate::EngineCore, data_dir: PathBuf) -> tokio::task: let mut updates_due: Option = Some(tokio::time::Instant::now() + UPDATE_DEBOUNCE); loop { + let settles_at = notifier.next_settled(); tokio::select! { changed = sessions.changed() => { if changed.is_err() { break; } @@ -485,6 +560,17 @@ pub(crate) fn spawn(core: &crate::EngineCore, data_dir: PathBuf) -> tokio::task: updates.borrow_and_update(); updates_due.get_or_insert(tokio::time::Instant::now() + UPDATE_DEBOUNCE); } + _ = async { + match settles_at { + Some(at) => { + let wait = (at - chrono::Utc::now()).to_std().unwrap_or_default(); + tokio::time::sleep(wait).await; + } + None => std::future::pending().await, + } + } => { + notifier.flush(chrono::Utc::now()); + } _ = async { match updates_due { Some(at) => tokio::time::sleep_until(at).await, @@ -505,21 +591,38 @@ mod tests { #[test] fn a_plugin_s_banner_keeps_to_the_settings_and_its_pace() { assert_eq!(asked_outcome(true, false, true, true), "posted"); - assert_eq!(asked_outcome(true, true, true, true), "held", "only when in the background, and a window is in front"); + assert_eq!( + asked_outcome(true, true, true, true), + "held", + "only when in the background, and a window is in front" + ); assert_eq!(asked_outcome(true, true, false, true), "posted"); assert_eq!(asked_outcome(false, false, false, true), "off"); - assert_eq!(asked_outcome(true, false, false, false), "unavailable", "a server never shows banners"); + assert_eq!( + asked_outcome(true, false, false, false), + "unavailable", + "a server never shows banners" + ); let mut history = std::collections::VecDeque::new(); let t0 = Instant::now(); assert!(asked_in_time(&mut history, t0)); - assert!(!asked_in_time(&mut history, t0 + Duration::from_secs(1)), "too soon after the last"); + assert!( + !asked_in_time(&mut history, t0 + Duration::from_secs(1)), + "too soon after the last" + ); let mut at = t0; for _ in 1..ASKED_PER_MINUTE { at += ASKED_APART; assert!(asked_in_time(&mut history, at)); } - assert!(!asked_in_time(&mut history, at + ASKED_APART), "a minute's worth"); - assert!(asked_in_time(&mut history, t0 + Duration::from_secs(61)), "a minute on, one more"); + assert!( + !asked_in_time(&mut history, at + ASKED_APART), + "a minute's worth" + ); + assert!( + asked_in_time(&mut history, t0 + Duration::from_secs(61)), + "a minute on, one more" + ); } use super::*; @@ -782,6 +885,8 @@ mod tests { &chats, now, ); + // (Once it has settled: a finish waits a moment for a turn to follow.) + notifier.flush(now + DONE_SETTLE); assert_eq!( *posted.lock().unwrap(), vec![( @@ -793,6 +898,7 @@ mod tests { // A focused window holds it back (background-only is the default). focus.set("window", true); notifier.sessions(&[session("a", Some("t3"), now)], &chats, now); + notifier.flush(now + DONE_SETTLE); assert_eq!(posted.lock().unwrap().len(), 1); // Banners off: nothing, focused or not. focus.set("window", false); @@ -802,9 +908,68 @@ mod tests { ) .unwrap(); notifier.sessions(&[session("a", Some("t4"), now)], &chats, now); + notifier.flush(now + DONE_SETTLE); assert_eq!(posted.lock().unwrap().len(), 1); } + fn working(chat_id: &str, turn: Option<&str>, now: chrono::DateTime) -> Session { + let mut row = session(chat_id, turn, now); + row.status = zeron_proto::SessionStatus::Working; + row.started_at = Some(now); + row + } + + /// Your own message never rings "finished". These are the rows + /// crates/engine/src/sessions.rs publishes at such a send. + #[test] + fn a_send_steer_or_queued_send_never_rings_finished() { + let dir = tempfile::tempdir().unwrap(); + let (mut notifier, posted, _) = notifier(dir.path()); + let chats = [chat("a", "Fix the build", None)]; + let t0 = chrono::Utc::now(); + let at = |ms: i64| t0 + chrono::Duration::milliseconds(ms); + notifier.sessions(&[session("a", Some("t1"), at(0))], &chats, at(0)); + + // A plain send to an idle chat: Working, the marker as it was. + notifier.sessions(&[working("a", Some("t1"), at(10))], &chats, at(10)); + notifier.flush(at(10_000)); + // A steer (or a queued row taken) as the turn ends: the end is + // published with Working, the person's message carrying it on. + notifier.sessions(&[working("a", Some("t2"), at(20))], &chats, at(20)); + notifier.flush(at(10_000)); + // A send that replaces the runtime: the held end lands Idle, then + // the new turn starts a moment later. + notifier.sessions(&[session("a", Some("t3"), at(30))], &chats, at(30)); + notifier.sessions(&[working("a", Some("t3"), at(200))], &chats, at(200)); + notifier.flush(at(10_000)); + assert!( + posted.lock().unwrap().is_empty(), + "rang on a send: {:?}", + posted.lock().unwrap() + ); + + // The turn your message started finishing: that rings, once. + notifier.sessions(&[session("a", Some("t4"), at(20_000))], &chats, at(20_000)); + notifier.flush(at(30_000)); + notifier.flush(at(40_000)); + assert_eq!(posted.lock().unwrap().len(), 1); + } + + /// A question or a failure doesn't wait: it rings at once. + #[test] + fn a_question_or_failure_rings_at_once() { + let dir = tempfile::tempdir().unwrap(); + let (mut notifier, posted, _) = notifier(dir.path()); + let chats = [chat("a", "Fix the build", None)]; + let now = chrono::Utc::now(); + notifier.sessions(&[working("a", Some("t1"), now)], &chats, now); + let mut asking = working("a", Some("t1"), now); + asking.status = zeron_proto::SessionStatus::AwaitingInput; + notifier.sessions(&[asking], &chats, now); + assert_eq!(posted.lock().unwrap().len(), 1); + assert_eq!(posted.lock().unwrap()[0].1, "Waiting on your input"); + } + #[test] fn agent_updates_banner_once_per_release() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/device_stats.rs b/crates/engine/src/device_stats.rs index a8fb0a28c..4bd0bd3d2 100644 --- a/crates/engine/src/device_stats.rs +++ b/crates/engine/src/device_stats.rs @@ -761,6 +761,8 @@ mod tests { assert!(none.zeron_data.is_none() && none.volumes.is_empty()); } + // (Unix only: its sysfs fixture names files `0000:01:00.0`, which Windows refuses.) + #[cfg(unix)] #[test] fn linux_batteries_and_nvidia_gpus_read_from_sysfs_and_proc() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/hosted_models.rs b/crates/engine/src/hosted_models.rs index da4260e94..bb4e9ac95 100644 --- a/crates/engine/src/hosted_models.rs +++ b/crates/engine/src/hosted_models.rs @@ -311,6 +311,7 @@ pub fn apply( default: false, id: hosted.id.clone(), label: hosted.label.clone().unwrap_or_else(|| hosted.id.clone()), + provider: None, description: hosted.description.clone(), reasoning_levels: ladder, options: hosted.options.iter().filter_map(|o| option(o)).collect(), diff --git a/crates/engine/src/hosted_models_tests.rs b/crates/engine/src/hosted_models_tests.rs index 2fa7c9dcf..7be1d7379 100644 --- a/crates/engine/src/hosted_models_tests.rs +++ b/crates/engine/src/hosted_models_tests.rs @@ -6,6 +6,7 @@ fn row(id: &str, label: &str) -> Model { default: false, id: id.into(), label: label.into(), + provider: None, description: None, reasoning_levels: vec![ReasoningLevel::High], options: vec![], diff --git a/crates/engine/src/model_catalogs.rs b/crates/engine/src/model_catalogs.rs index 93758a630..966d4e162 100644 --- a/crates/engine/src/model_catalogs.rs +++ b/crates/engine/src/model_catalogs.rs @@ -10,6 +10,12 @@ use zeron_harness::{ }; use zeron_proto::Model; +/// The saved catalog's shape. 2: models name their provider (`provider`), +/// and an agent's ` · ` label is split into the two; a +/// catalog an older engine saved has neither, so it's fetched again rather +/// than shown as it was. +const SCHEMA: u32 = 3; + #[derive(Serialize, Deserialize)] struct Saved { schema_version: u32, @@ -26,7 +32,7 @@ fn location(root: &Path, harness: &dyn Harness, context: &ModelContext) -> PathB } fn read(path: &Path, context: &ModelContext) -> Option> { let saved: Saved = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; - (saved.schema_version == 1 + (saved.schema_version == SCHEMA && saved.binary_version == context.binary_version && !saved.catalog.is_empty()) .then_some(saved.catalog) @@ -37,7 +43,7 @@ fn save(path: &Path, context: &ModelContext, models: &[Model]) -> std::io::Resul } std::fs::create_dir_all(path.parent().unwrap())?; let bytes = serde_json::to_vec(&Saved { - schema_version: 1, + schema_version: SCHEMA, fetched_at: SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() @@ -232,6 +238,7 @@ mod tests { default: false, id: "live".into(), label: "Live".into(), + provider: None, description: None, reasoning_levels: vec![], options: vec![], @@ -469,7 +476,7 @@ mod tests { let mut wrong = context.clone(); wrong.binary_version = Some("2.0.0".into()); assert!(read(&path, &wrong).is_none()); - for value in ["broken".to_owned(), serde_json::json!({"schema_version":2,"fetched_at":0,"binary_version":"1.0.0","catalog":models()}).to_string(), serde_json::json!({"schema_version":1,"fetched_at":0,"binary_version":"1.0.0","catalog":[]}).to_string()] { + for value in ["broken".to_owned(), serde_json::json!({"schema_version":SCHEMA + 1,"fetched_at":0,"binary_version":"1.0.0","catalog":models()}).to_string(), serde_json::json!({"schema_version":1,"fetched_at":0,"binary_version":"1.0.0","catalog":models()}).to_string(), serde_json::json!({"schema_version":SCHEMA,"fetched_at":0,"binary_version":"1.0.0","catalog":[]}).to_string()] { std::fs::write(&path, value).unwrap(); assert!(read(&path, &context).is_none()); } } diff --git a/crates/engine/src/plugins/agents_tests.rs b/crates/engine/src/plugins/agents_tests.rs index 67c742b5c..1f27dde4d 100644 --- a/crates/engine/src/plugins/agents_tests.rs +++ b/crates/engine/src/plugins/agents_tests.rs @@ -45,6 +45,7 @@ pub(crate) fn model(id: &str) -> Model { default: false, id: id.into(), label: id.to_uppercase(), + provider: None, description: None, reasoning_levels: vec![ReasoningLevel::Low, ReasoningLevel::High], options: vec![ModelOption { diff --git a/crates/engine/src/plugins/manifest.rs b/crates/engine/src/plugins/manifest.rs index 3a7f68195..5bfd31f57 100644 --- a/crates/engine/src/plugins/manifest.rs +++ b/crates/engine/src/plugins/manifest.rs @@ -28,6 +28,9 @@ pub const KNOWN_PERMISSIONS: &[&str] = &[ "notifications", "navigate", "compose", + // Reading the composer's draft, and taking it and putting it back + // (`zeron.draft`, `take_draft`, `put_draft`). + "draft", "network", "clipboard", "files", diff --git a/crates/engine/src/registry.rs b/crates/engine/src/registry.rs index 4e736fa74..243848e35 100644 --- a/crates/engine/src/registry.rs +++ b/crates/engine/src/registry.rs @@ -866,6 +866,8 @@ fn full_registry() -> HarnessRegistry { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, AgentEvent::ToolCall { @@ -880,6 +882,8 @@ fn full_registry() -> HarnessRegistry { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, AgentEvent::TextDelta { diff --git a/crates/engine/src/rpc.rs b/crates/engine/src/rpc.rs index ebfc39d3d..4914e63ba 100644 --- a/crates/engine/src/rpc.rs +++ b/crates/engine/src/rpc.rs @@ -535,6 +535,30 @@ struct AgentAccountParams { account_id: String, } +/// `AddAgentApiKey`. The key is never logged: this type has no `Debug`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct AddAgentApiKeyParams { + harness: HarnessId, + provider: String, + key: String, + /// What to call it (no secret); none: " ···". + #[serde(default)] + name: Option, + /// The device the app meant: only ever this one (refused otherwise — + /// a key is never forwarded). + #[serde(default)] + target_device_id: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct RenameAgentAccountParams { + harness: HarnessId, + account_id: String, + name: String, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct ConsumeCodexResetCreditParams { @@ -2556,6 +2580,7 @@ fn forwardable(method: &str) -> bool { | methods::LIST_AGENT_ACCOUNTS | methods::ACTIVATE_AGENT_ACCOUNT | methods::FORGET_AGENT_ACCOUNT + | methods::RENAME_AGENT_ACCOUNT | methods::START_AGENT_LOGIN | methods::COMPLETE_AGENT_LOGIN | methods::POLL_AGENT_LOGIN @@ -5533,6 +5558,36 @@ impl RpcService for EngineRpc { .map_err(|e| RpcError::Failed(e.to_string()))?; RpcReply::value(&snapshot) } + methods::ADD_AGENT_API_KEY => { + // (Never `parse_params`'s error: it can quote the input.) + let p: AddAgentApiKeyParams = serde_json::from_value(params) + .map_err(|_| RpcError::BadParams("expected {harness, provider, key}".into()))?; + if p + .target_device_id + .as_deref() + .is_some_and(|target| !target.is_empty() && target != self.doc_host.device_id()) + { + return Err(RpcError::Failed( + "API keys are added on the device that runs the agent — open Zeron there." + .into(), + )); + } + let snapshot = self + .agent_accounts + .add_api_key(p.harness, &p.provider, &p.key, p.name.as_deref()) + .await + .map_err(|e| RpcError::Failed(e.to_string()))?; + RpcReply::value(&snapshot) + } + methods::RENAME_AGENT_ACCOUNT => { + let p: RenameAgentAccountParams = parse_params(params)?; + let snapshot = self + .agent_accounts + .rename_account(p.harness, &p.account_id, &p.name) + .await + .map_err(|e| RpcError::Failed(e.to_string()))?; + RpcReply::value(&snapshot) + } methods::CONSUME_CODEX_RESET_CREDIT => { let p: ConsumeCodexResetCreditParams = parse_params(params)?; let outcome = self @@ -6470,6 +6525,18 @@ mod tests { assert!(!forwardable(methods::ENGINE_READY)); // The bearer is for local clients only, never a remote device's ask. assert!(!forwardable(methods::ACCESS_TOKEN)); + // An API key never leaves the device it was typed on: not forwarded, + // not served to a peer through the relay, not an agent's to call. + assert!(!forwardable(methods::ADD_AGENT_API_KEY)); + assert!(zeron_rpc::local_only(methods::ADD_AGENT_API_KEY)); + assert!(zeron_rpc::peer_refused(methods::ADD_AGENT_API_KEY, &serde_json::json!({}))); + assert!(!zeron_rpc::agent_allowed(methods::ADD_AGENT_API_KEY)); + // Per-provider account actions do travel, provider and all. + assert!(forwardable(methods::START_AGENT_LOGIN)); + assert!(forwardable(methods::ACTIVATE_AGENT_ACCOUNT)); + // A key's name is no secret: renamed wherever the key lives. + assert!(forwardable(methods::RENAME_AGENT_ACCOUNT)); + assert!(!zeron_rpc::local_only(methods::RENAME_AGENT_ACCOUNT)); assert!(forwardable(methods::QUEUE_COMMAND)); assert!(forwardable(methods::SEARCH_FILES)); assert!(forwardable(methods::SEARCH_GIT_HISTORY)); diff --git a/crates/engine/src/runner.rs b/crates/engine/src/runner.rs index c31867a23..657a845f8 100644 --- a/crates/engine/src/runner.rs +++ b/crates/engine/src/runner.rs @@ -489,6 +489,7 @@ fn setup_parts( subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/engine/src/sessions.rs b/crates/engine/src/sessions.rs index c30138f90..6f5f098d1 100644 --- a/crates/engine/src/sessions.rs +++ b/crates/engine/src/sessions.rs @@ -2313,7 +2313,88 @@ impl SessionsEngine { } } +/// The uploads id of a picture a tool result carried: `tool--`, +/// each a SHA-256 in hex, the chat's cut to 16 digits. The same bytes in a +/// chat name one file; a chat's pictures all start `tool--`. +fn tool_image_id(chat_id: &str, bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + let chat = format!("{:x}", Sha256::digest(chat_id.as_bytes())); + format!("tool-{}-{:x}", &chat[..16], Sha256::digest(bytes)) +} + impl Inner { + /// Store image bytes a tool result already carried. The model-supplied + /// path is never opened. A bad payload leaves no preview and does not + /// fail the turn. Each file is named by its chat (a subagent's results + /// are its chat's too) and its bytes: the same picture again in a chat is one file, + /// not a copy per read, and a chat's files can be found by its prefix + /// when it goes (`tool_image_id`). + async fn store_tool_result_images( + &self, + chat_id: &str, + tool_id: &str, + payloads: Vec, + ) -> Vec { + let Some((uploads, _)) = self.generated_images.get() else { + tracing::warn!( + chat = %chat_id, + tool = %tool_id, + "tool image dropped: uploads are not configured" + ); + return Vec::new(); + }; + let uploads = uploads.clone(); + let chat_id = chat_id.to_owned(); + let tool_id = tool_id.to_owned(); + let chat_for_log = chat_id.clone(); + let tool_for_log = tool_id.clone(); + tokio::task::spawn_blocking(move || { + use base64::Engine as _; + let mut paths = Vec::new(); + for (index, payload) in payloads.into_iter().enumerate().take(4) { + let bytes = match base64::engine::general_purpose::STANDARD + .decode(payload.data_base64.trim()) + { + Ok(bytes) => bytes, + Err(err) => { + tracing::warn!( + chat = %chat_id, + tool = %tool_id, + index, + error = %err, + "tool image rejected" + ); + continue; + } + }; + let id = tool_image_id(&chat_id, &bytes); + match uploads.store_shown_image(&id, &payload.name, &bytes) { + Ok(image) => paths.push(image.path), + Err(err) => { + tracing::warn!( + chat = %chat_id, + tool = %tool_id, + index, + error = %err, + "tool image rejected" + ); + } + } + } + paths + }) + .await + .unwrap_or_else(|err| { + tracing::warn!( + chat = %chat_for_log, + tool = %tool_for_log, + error = %err, + "tool image store failed" + ); + Vec::new() + }) + } + /// Journal + broadcast one event (the two unconditional legs of the pipeline). /// Sanitize before ANY journal/publish path, including nested subagent events. async fn prepare_generated_image( @@ -2332,57 +2413,111 @@ impl Inner { parents.push(parent_tool_use_id); leaf = *event; } - let events = if let AgentEvent::GeneratedImage { id, path, .. } = leaf { - let key = std::iter::once(chat_id) - .chain(parents.iter().map(String::as_str)) - .chain(std::iter::once(id.as_str())) - .collect::>() - .join("\0"); - if seen.contains(&key) { - return vec![]; - } - let result = if let Some((uploads, allowed_root)) = self.generated_images.get() { - let uploads = uploads.clone(); - let root = allowed_root.clone(); - let stable_key = key.clone(); - tokio::task::spawn_blocking(move || { - uploads.import_generated_image(std::path::Path::new(&path), &root, &stable_key) - }) - .await - .unwrap_or_else(|err| Err(EngineError::Other(err.to_string()))) - } else { - Err(EngineError::Other( - "Generated image intake is not configured".into(), - )) - }; - match result { - Ok(image) => { - seen.insert(key); - vec![AgentEvent::GeneratedImage { - id, - path: image.path, - name: image.name, - mime_type: image.mime_type, - }] + let events = match leaf { + AgentEvent::GeneratedImage { id, path, .. } => { + let key = std::iter::once(chat_id) + .chain(parents.iter().map(String::as_str)) + .chain(std::iter::once(id.as_str())) + .collect::>() + .join("\0"); + if seen.contains(&key) { + return vec![]; } - Err(err) => { - tracing::warn!(chat = %chat_id, error = %err, "generated image import failed"); - vec![ - AgentEvent::ToolResult { - id: id.strip_suffix(":image").unwrap_or(&id).into(), - is_error: true, - output: None, - diff: None, - exit_code: None, - }, - AgentEvent::Error { - message: "Generated image unavailable".into(), - }, - ] + let result = if let Some((uploads, allowed_root)) = self.generated_images.get() { + let uploads = uploads.clone(); + let root = allowed_root.clone(); + let stable_key = key.clone(); + tokio::task::spawn_blocking(move || { + uploads.import_generated_image( + std::path::Path::new(&path), + &root, + &stable_key, + ) + }) + .await + .unwrap_or_else(|err| Err(EngineError::Other(err.to_string()))) + } else { + Err(EngineError::Other( + "Generated image intake is not configured".into(), + )) + }; + match result { + Ok(image) => { + seen.insert(key); + vec![AgentEvent::GeneratedImage { + id, + path: image.path, + name: image.name, + mime_type: image.mime_type, + }] + } + Err(err) => { + tracing::warn!(chat = %chat_id, error = %err, "generated image import failed"); + vec![ + AgentEvent::ToolResult { + id: id.strip_suffix(":image").unwrap_or(&id).into(), + is_error: true, + output: None, + diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), + exit_code: None, + }, + AgentEvent::Error { + message: "Generated image unavailable".into(), + }, + ] + } } } - } else { - vec![leaf] + // A tool part's preview paths are only ever the engine's own + // copies in uploads: clients read them as pictures as they are + // (zgx reads a local chat's straight from disk), so a path an + // adapter put there (`/dev/zero`, a file elsewhere) never reaches + // the doc. + AgentEvent::ToolResult { + id, + is_error, + output, + diff, + preview_paths: _, + image_payloads, + exit_code, + } if !image_payloads.is_empty() => { + let stored = self + .store_tool_result_images(chat_id, &id, image_payloads) + .await; + vec![AgentEvent::ToolResult { + id, + is_error, + output, + diff, + preview_paths: stored, + image_payloads: Vec::new(), + exit_code, + }] + } + AgentEvent::ToolResult { + id, + is_error, + output, + diff, + preview_paths, + image_payloads, + exit_code, + } if !preview_paths.is_empty() => { + tracing::warn!(chat = %chat_id, tool = %id, "tool preview paths without stored images dropped"); + vec![AgentEvent::ToolResult { + id, + is_error, + output, + diff, + preview_paths: Vec::new(), + image_payloads, + exit_code, + }] + } + other => vec![other], }; events .into_iter() @@ -3832,6 +3967,7 @@ fn render_parts(parts: &[MessagePart]) -> Vec { subagent_ref, subagent_status, subagent_tail, + preview_paths, exit_code, output_truncated, output_lines, @@ -3853,6 +3989,7 @@ fn render_parts(parts: &[MessagePart]) -> Vec { subagent_ref: subagent_ref.clone(), subagent_status: *subagent_status, subagent_tail: subagent_tail.clone(), + preview_paths: preview_paths.clone(), exit_code: *exit_code, output_truncated: *output_truncated, output_lines: *output_lines, @@ -6044,6 +6181,210 @@ mod tests { assert!(!journal.contains("secret")); } + /// A picture read again in a chat (another call, another subagent) is + /// the same file, not a copy per read; another chat's is its own; and a + /// chat's files share its prefix, for whatever clears a chat's away. + #[test] + fn a_chats_tool_pictures_are_one_file_each_under_its_prefix() { + let png = b"\x89PNG one"; + let id = super::tool_image_id("chat-a", png); + assert_eq!(id, super::tool_image_id("chat-a", png)); + assert_ne!(id, super::tool_image_id("chat-a", b"\x89PNG two")); + assert_ne!(id, super::tool_image_id("chat-b", png)); + let prefix = &id[..id.rfind('-').unwrap() + 1]; + assert!(super::tool_image_id("chat-a", b"\x89PNG two").starts_with(prefix)); + assert!(!super::tool_image_id("chat-b", png).starts_with(prefix)); + assert!( + id.bytes() + .all(|b| b.is_ascii_hexdigit() || b == b'-' || b.is_ascii_lowercase()), + "{id}" + ); + } + + #[tokio::test] + async fn tool_result_images_are_stored_inside_uploads() { + use base64::Engine as _; + let dir = tempfile::tempdir().unwrap(); + let uploads_dir = dir.path().join("uploads"); + std::fs::create_dir_all(&uploads_dir).unwrap(); + let sessions = SessionsEngine::new( + "host".into(), + Arc::new(RunJournal::open(dir.path().join("journals")).unwrap()), + Arc::new(HarnessRegistry::new()), + ); + let uploads = crate::uploads::Uploads::from_root(&uploads_dir); + sessions.set_generated_images(uploads.clone(), dir.path().join("generated")); + let png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + let payload = || AgentEvent::Subagent { + parent_tool_use_id: "child".into(), + event: Box::new(AgentEvent::ToolResult { + exit_code: None, + id: "tool-1".into(), + is_error: false, + output: None, + diff: None, + preview_paths: Vec::new(), + image_payloads: vec![zeron_proto::ToolResultImage { + name: "1.png".into(), + data_base64: png_b64.into(), + }], + }), + }; + let events = sessions + .inner + .prepare_generated_image("chat", payload(), &mut std::collections::HashSet::new()) + .await; + assert_eq!(events.len(), 1); + let AgentEvent::Subagent { + parent_tool_use_id, + event, + } = &events[0] + else { + panic!("lost owner"); + }; + assert_eq!(parent_tool_use_id, "child"); + let AgentEvent::ToolResult { + preview_paths, + image_payloads, + is_error, + .. + } = event.as_ref() + else { + panic!("expected a tool result"); + }; + assert!(!*is_error); + assert!(image_payloads.is_empty()); + assert_eq!(preview_paths.len(), 1); + assert!( + std::path::Path::new(&preview_paths[0]).starts_with(&uploads_dir), + "{}", + preview_paths[0] + ); + let chunk = uploads.read_chunk(&preview_paths[0], 0, &[]).unwrap(); + assert!(chunk.done); + assert_eq!( + base64::engine::general_purpose::STANDARD + .decode(chunk.data) + .unwrap(), + base64::engine::general_purpose::STANDARD + .decode(png_b64) + .unwrap() + ); + let again = sessions + .inner + .prepare_generated_image("chat", payload(), &mut std::collections::HashSet::new()) + .await; + let AgentEvent::Subagent { + event: again_event, .. + } = &again[0] + else { + panic!("lost owner"); + }; + let AgentEvent::ToolResult { + preview_paths: again_paths, + .. + } = again_event.as_ref() + else { + panic!("expected a tool result"); + }; + assert_eq!(again_paths, preview_paths); + sessions.inner.publish("chat", &events[0]); + let journal = + serde_json::to_string(&sessions.inner.journal.replay("chat", 0).unwrap()).unwrap(); + assert!(!journal.contains(png_b64)); + // (As the journal's JSON writes it: a Windows path's `\` escaped.) + let stored = serde_json::to_string(&preview_paths[0]).unwrap(); + assert!(journal.contains(stored.trim_matches('"')), "{journal}"); + + let bad = AgentEvent::ToolResult { + exit_code: None, + id: "tool-2".into(), + is_error: false, + output: None, + diff: None, + preview_paths: Vec::new(), + image_payloads: vec![zeron_proto::ToolResultImage { + name: "note.txt".into(), + data_base64: base64::engine::general_purpose::STANDARD + .encode(b"not an image") + .into(), + }], + }; + let rejected = sessions + .inner + .prepare_generated_image("chat", bad, &mut std::collections::HashSet::new()) + .await; + assert!(matches!( + &rejected[..], + [AgentEvent::ToolResult { + preview_paths, + image_payloads, + is_error: false, + .. + }] if preview_paths.is_empty() && image_payloads.is_empty() + )); + + // Paths an adapter put on a result are not the engine's copies: they + // never reach the doc, with stored pictures or without. + for payloads in [ + Vec::new(), + vec![zeron_proto::ToolResultImage { + name: "1.png".into(), + data_base64: png_b64.into(), + }], + ] { + let stored_any = !payloads.is_empty(); + let named = AgentEvent::ToolResult { + exit_code: None, + id: "tool-3".into(), + is_error: false, + output: None, + diff: None, + preview_paths: vec!["/dev/zero".into(), "/etc/hosts".into()], + image_payloads: payloads, + }; + let out = sessions + .inner + .prepare_generated_image("chat", named, &mut std::collections::HashSet::new()) + .await; + let [AgentEvent::ToolResult { preview_paths, .. }] = &out[..] else { + panic!("expected one tool result, got {out:?}"); + }; + assert!( + preview_paths + .iter() + .all(|path| std::path::Path::new(path).starts_with(&uploads_dir)), + "{preview_paths:?}" + ); + assert_eq!( + preview_paths.len(), + usize::from(stored_any), + "{preview_paths:?}" + ); + } + + let bare = SessionsEngine::new( + "host".into(), + Arc::new(RunJournal::open(dir.path().join("journals-bare")).unwrap()), + Arc::new(HarnessRegistry::new()), + ); + let dropped = bare + .inner + .prepare_generated_image("chat", payload(), &mut std::collections::HashSet::new()) + .await; + let AgentEvent::Subagent { event, .. } = &dropped[0] else { + panic!("lost owner"); + }; + assert!(matches!( + event.as_ref(), + AgentEvent::ToolResult { + preview_paths, + image_payloads, + .. + } if preview_paths.is_empty() && image_payloads.is_empty() + )); + } + /// The backwards journal scan must answer exactly what the old full forward /// replay did: newest non-empty id, cwd from the governing `SessionStarted`. #[tokio::test] diff --git a/crates/engine/src/source_control.rs b/crates/engine/src/source_control.rs index 10ac7f3d8..f4f0129e2 100644 --- a/crates/engine/src/source_control.rs +++ b/crates/engine/src/source_control.rs @@ -4840,7 +4840,8 @@ printf '%s\n' '[{"number":90,"title":"Host-resolved pull request","url":"https:/ // coming and going as a list scrolls. Run by hand: // `MEASURE_CHATS=/path[@branch],… MEASURE_SECS=300 cargo test -p zeron-engine --lib // measure_pull_request_watches -- --ignored --nocapture` -#[cfg(test)] +// (Unix only: it reads child CPU time with getrusage.) +#[cfg(all(test, unix))] mod measure { use super::*; use std::collections::HashMap; diff --git a/crates/engine/src/spaces.rs b/crates/engine/src/spaces.rs index 6f733c62d..2c4c23f91 100644 --- a/crates/engine/src/spaces.rs +++ b/crates/engine/src/spaces.rs @@ -660,6 +660,12 @@ mod tests { fn worktree_inputs_follow_its_head() { let tmp = tempfile::tempdir().unwrap(); let root = std::fs::canonicalize(tmp.path()).unwrap(); + // (Windows' canonical path is `\\?\`-verbatim, which `git worktree add` refuses.) + let root = std::path::PathBuf::from( + root.to_string_lossy() + .trim_start_matches(r"\\?\") + .to_string(), + ); let repo = root.join("repo"); std::fs::create_dir_all(&repo).unwrap(); git(&repo, &["init", "-q"]); diff --git a/crates/engine/src/terminals.rs b/crates/engine/src/terminals.rs index c0ab502d8..04cce9079 100644 --- a/crates/engine/src/terminals.rs +++ b/crates/engine/src/terminals.rs @@ -229,7 +229,7 @@ fn clamp_size(cols: u16, rows: u16) -> PtySize { /// The user's interactive shell: `$SHELL`, else the platform default. fn selected_shell() -> String { if cfg!(windows) { - return std::env::var("COMSPEC").unwrap_or_else(|_| "powershell.exe".into()); + return windows_shell(|name| std::env::var_os(name), |path| path.is_file()); } std::env::var("SHELL") .ok() @@ -243,6 +243,44 @@ fn selected_shell() -> String { }) } +/// Windows' interactive shell: PowerShell 7 (`pwsh.exe` on `PATH`), else +/// the Windows PowerShell every Windows has, else `%COMSPEC%` (cmd.exe). +/// PowerShell, not cmd: its prompt ends in a space and PSReadLine colours +/// what's typed, as a terminal on macOS or Linux does. +fn windows_shell( + var: impl Fn(&str) -> Option, + exists: impl Fn(&std::path::Path) -> bool, +) -> String { + let pwsh = var("PATH") + .into_iter() + .flat_map(|path| std::env::split_paths(&path).collect::>()) + .map(|dir| dir.join("pwsh.exe")) + .find(|path| exists(path)); + let windows_powershell = var("SystemRoot") + .map(|root| { + std::path::PathBuf::from(root) + .join("System32") + .join("WindowsPowerShell") + .join("v1.0") + .join("powershell.exe") + }) + .filter(|path| exists(path)); + pwsh.or(windows_powershell) + .map(|path| path.to_string_lossy().into_owned()) + .or_else(|| var("COMSPEC").map(|comspec| comspec.to_string_lossy().into_owned())) + .unwrap_or_else(|| "cmd.exe".into()) +} + +/// Whether `shell` is PowerShell (7's `pwsh` or Windows PowerShell), which +/// prints a banner as it starts unless told `-NoLogo`. Its last part, split +/// at either slash: a Windows path reads the same wherever it's asked +/// (`std::path` splits at `\` only on Windows, and the tests run on all). +fn is_powershell(shell: &str) -> bool { + let file = shell.rsplit(['/', '\\']).next().unwrap_or(shell); + let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem); + matches!(stem.to_ascii_lowercase().as_str(), "pwsh" | "powershell") +} + impl Terminals { /// Requires a tokio runtime (spawns the exited-session reaper). pub fn new() -> Self { @@ -1038,6 +1076,50 @@ mod windows_tests { }); } + /// An engine the app started ignores Ctrl+C (its own process group), as + /// this test makes itself: Ctrl+C in its terminal still interrupts what + /// the shell runs. + #[test] + fn ctrl_c_interrupts_a_program_though_the_engine_ignores_it() { + use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; + // SAFETY: a null handler with TRUE sets this process's ignore flag, + // as CREATE_NEW_PROCESS_GROUP does for a detached engine. + unsafe { SetConsoleCtrlHandler(None, 1) }; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let tmp = tempfile::tempdir().unwrap(); + let terminals = Terminals::new(); + let terminal = terminals + .open_with_shell( + tmp.path().to_str().unwrap(), + 80, + 24, + Some(powershell().to_str().unwrap()), + ) + .unwrap(); + wait_for_shell_prompt(&terminals, &terminal.id).await; + let mut rx = terminals.subscribe(&terminal.id, None).unwrap(); + let mut events = Vec::new(); + write_line(&terminals, &terminal.id, "ping -t localhost"); + collect_until(&mut rx, &mut events, |events| { + decoded(events).contains("Reply from") + }) + .await; + terminals + .write(&terminal.id, &BASE64.encode("\u{3}")) + .unwrap(); + // Interrupted, ping sums up what it sent; left running, it never does. + collect_until(&mut rx, &mut events, |events| { + decoded(events).contains("Ping statistics") + }) + .await; + terminals.close(&terminal.id).unwrap(); + }); + } + fn powershell() -> PathBuf { let path = PathBuf::from(std::env::var_os("SystemRoot").expect("SystemRoot is set")) .join("System32") @@ -1384,6 +1466,69 @@ mod windows_tests { } } +#[cfg(test)] +mod windows_shell_tests { + use super::{is_powershell, windows_shell}; + use std::ffi::OsString; + use std::path::{Path, PathBuf}; + + const ROOT: &str = "root"; + + fn env(path: &[&str], comspec: Option<&str>) -> impl Fn(&str) -> Option { + let path = std::env::join_paths(path.iter().map(PathBuf::from)).unwrap(); + let comspec = comspec.map(OsString::from); + move |name| match name { + "PATH" => Some(path.clone()), + "SystemRoot" => Some(ROOT.into()), + "COMSPEC" => comspec.clone(), + _ => None, + } + } + + fn windows_powershell() -> PathBuf { + Path::new(ROOT) + .join("System32") + .join("WindowsPowerShell") + .join("v1.0") + .join("powershell.exe") + } + + #[test] + fn powershell_7_on_path_comes_first() { + let pwsh = Path::new("pwsh7").join("pwsh.exe"); + let shell = windows_shell(env(&["other", "pwsh7"], Some("cmd.exe")), |p| { + p == pwsh || p == windows_powershell() + }); + assert_eq!(shell, pwsh.to_string_lossy()); + } + + #[test] + fn windows_powershell_without_powershell_7() { + let shell = windows_shell(env(&["other"], Some("cmd.exe")), |p| { + p == windows_powershell() + }); + assert_eq!(shell, windows_powershell().to_string_lossy()); + } + + #[test] + fn comspec_when_there_is_no_powershell() { + assert_eq!( + windows_shell(env(&["other"], Some("C:\\cmd.exe")), |_| false), + "C:\\cmd.exe" + ); + assert_eq!(windows_shell(env(&[], None), |_| false), "cmd.exe"); + } + + #[test] + fn powershell_is_told_no_logo() { + assert!(is_powershell(r"C:\Program Files\PowerShell\7\pwsh.exe")); + assert!(is_powershell("powershell.exe")); + assert!(is_powershell("PWSH")); + assert!(!is_powershell(r"C:\WINDOWS\system32\cmd.exe")); + assert!(!is_powershell("/bin/zsh")); + } +} + #[cfg(all(test, unix))] mod initial_command_tests { use super::*; diff --git a/crates/engine/src/terminals/windows.rs b/crates/engine/src/terminals/windows.rs index a1c4c4992..ea59e4c98 100644 --- a/crates/engine/src/terminals/windows.rs +++ b/crates/engine/src/terminals/windows.rs @@ -12,6 +12,7 @@ use portable_pty::{Child, ChildKiller, CommandBuilder, ExitStatus, MasterPty, Pt use windows_sys::Win32::Foundation::{INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT}; use windows_sys::Win32::System::Console::{ COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON, ResizePseudoConsole, + SetConsoleCtrlHandler, }; use windows_sys::Win32::System::Pipes::CreatePipe; use windows_sys::Win32::System::Threading::{ @@ -386,7 +387,12 @@ pub(super) fn open( let executable = wide(executable.as_os_str())?; let mut command = vec![b'"' as u16]; command.extend_from_slice(&executable[..executable.len() - 1]); - command.extend([b'"' as u16, 0]); + command.push(b'"' as u16); + // PowerShell's prompt alone, as cmd's: no banner on every tab. + if super::is_powershell(shell) { + command.extend(" -NoLogo".encode_utf16()); + } + command.push(0); let cwd = wide(OsStr::new(&plain_current_dir(cwd)?))?; let mut environment = std::collections::BTreeMap::new(); let env_key = |key: &OsStr| -> OsString { @@ -448,6 +454,15 @@ pub(super) fn open( startup.StartupInfo.hStdError = INVALID_HANDLE_VALUE; startup.lpAttributeList = attrs.ptr(); let mut info = PROCESS_INFORMATION::default(); + // The app starts the engine in a process group of its own (crates/launch + // `spawn_detached`, CREATE_NEW_PROCESS_GROUP), which ignores Ctrl+C, and + // a process inherits that from the one creating it: the shell, and what + // it runs, ignored it too, so Ctrl+C in a terminal tab reached the shell as + // a key and never interrupted `ping -t`. Normal handling is put back first, + // as any process started otherwise has it; the engine has no console of + // its own for a Ctrl+C to come from. + // SAFETY: a null handler with FALSE only clears this process's flag. + unsafe { SetConsoleCtrlHandler(None, 0) }; // SAFETY: all buffers and the initialized attribute list remain alive through // CreateProcessW. Job membership is established as part of creation, even // if the owner exits before this call returns. Suspension is only for the diff --git a/crates/engine/src/titles.rs b/crates/engine/src/titles.rs index 9aa603a0a..65bea32b4 100644 --- a/crates/engine/src/titles.rs +++ b/crates/engine/src/titles.rs @@ -346,6 +346,7 @@ mod tests { default: false, id: id.into(), label: label.into(), + provider: None, description: None, reasoning_levels: vec![], options: vec![], diff --git a/crates/engine/src/tool_output.rs b/crates/engine/src/tool_output.rs index b379bda94..3ac9e714c 100644 --- a/crates/engine/src/tool_output.rs +++ b/crates/engine/src/tool_output.rs @@ -115,6 +115,8 @@ mod tests { is_error: exit_code.is_some_and(|c| c != 0), output: Some(output.into()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code, } } diff --git a/crates/engine/src/uploads.rs b/crates/engine/src/uploads.rs index e2b87ffe5..bd8aed720 100644 --- a/crates/engine/src/uploads.rs +++ b/crates/engine/src/uploads.rs @@ -1780,4 +1780,31 @@ mod generated_image_tests { std::fs::write(&source, b"changed").unwrap(); std::fs::rename(&parent, root.path().join("moved")).unwrap(); } + + #[test] + fn shown_image_is_sniffed_idempotent_and_readable_from_uploads() { + let store = tempfile::tempdir().unwrap(); + let uploads = Uploads::from_root(store.path()); + let png = BASE64 + .decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==") + .unwrap(); + let first = uploads.store_shown_image("same-id", "1.png", &png).unwrap(); + let again = uploads.store_shown_image("same-id", "1.png", &png).unwrap(); + assert_eq!(first, again); + assert_eq!(first.mime_type, "image/png"); + assert!(first.path.ends_with("-image.png")); + let chunk = uploads.read_chunk(&first.path, 0, &[]).unwrap(); + assert!(chunk.done); + assert_eq!(BASE64.decode(chunk.data).unwrap(), png); + assert!( + uploads + .store_shown_image("text", "x.bin", b"hello") + .is_err() + ); + assert!( + uploads + .store_shown_image("bad-png", "x.png", b"\x89PNG\r\n\x1a\nnot a png") + .is_err() + ); + } } diff --git a/crates/engine/tests/device_routing.rs b/crates/engine/tests/device_routing.rs index 15c3dd028..cab6a1cc3 100644 --- a/crates/engine/tests/device_routing.rs +++ b/crates/engine/tests/device_routing.rs @@ -50,6 +50,14 @@ struct RelayState { } async fn fake_device_room() -> (String, tokio::task::JoinHandle<()>) { + fake_device_room_recording(None).await +} + +/// [`fake_device_room`], keeping every frame's bytes that passes through +/// it in `seen` (what the edge's relay would have had in memory). +async fn fake_device_room_recording( + seen: Option>>>, +) -> (String, tokio::task::JoinHandle<()>) { let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind relay"); let url = format!( "http://127.0.0.1:{}", @@ -62,6 +70,7 @@ async fn fake_device_room() -> (String, tokio::task::JoinHandle<()>) { break; }; let state = state.clone(); + let seen = seen.clone(); tokio::spawn(async move { let mut uri = String::new(); let Ok(ws) = tokio_tungstenite::accept_hdr_async( @@ -103,6 +112,9 @@ async fn fake_device_room() -> (String, tokio::task::JoinHandle<()>) { let WsMessage::Binary(bytes) = message else { continue; }; + if let Some(seen) = &seen { + seen.lock().expect("lock").extend_from_slice(&bytes); + } let Ok((header, payload)) = decode_device_frame(&bytes) else { break; }; @@ -2832,3 +2844,164 @@ async fn device_stats_of_a_device_that_never_answers_stop_at_the_deadline() { assert!(took >= Duration::from_millis(4900) && took < Duration::from_secs(7), "took {took:?}"); assert!(error.contains("stuck-name didn't answer within 5 s") && error.contains("last seen"), "{error}"); } + + +/// An agent with a login per model provider, on another device: its +/// accounts listed and switched there per provider, and a sign-in to one +/// provider started there with the provider riding along. An API key is +/// never carried there: refused here before anything is sent, refused there +/// if a peer sends one anyway, and in no file, frame or log on either side. +#[tokio::test] +async fn per_provider_accounts_are_managed_on_the_device_that_runs_the_agent() { + use zeron_engine::{AgentAccounts, AgentAccountsConfig}; + const KEY: &str = "sk-or-v1-REMOTEZEROTESTkey0123456789abcd"; + let seen = Arc::new(Mutex::new(Vec::new())); + let (relay_url, _relay) = fake_device_room_recording(Some(seen.clone())).await; + let dirs = tempfile::tempdir().expect("tempdir"); + let jwt = |email: &str, account: &str| { + let claims = serde_json::json!({ + "https://api.openai.com/auth": { "chatgpt_account_id": account, "chatgpt_plan_type": "plus" }, + "https://api.openai.com/profile": { "email": email }, + }); + format!("e30.{}.sig", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())) + }; + let chatgpt = |email: &str, account: &str| { + serde_json::json!({ "type": "oauth", "access": jwt(email, account), + "refresh": format!("refresh-{account}"), "expires": 1, "accountId": account }) + }; + // B: Pi with two ChatGPT logins seen (b in use) and an Anthropic key. + // Every agent store in a temp dir — never this machine's. + let accounts_b = AgentAccountsConfig::isolated(&dirs.path().join("b-agents")); + let pi_b = accounts_b.pi_agent_dir.join("auth.json"); + let mut core_b = assemble(&dirs.path().join("b"), "device-b"); + core_b.agent_accounts = AgentAccounts::new(accounts_b.clone()); + let anthropic_key = serde_json::json!({ "type": "api_key", "key": "sk-ant-api03-keepKEEPkeep" }); + let write_pi = |entry: serde_json::Value| { + std::fs::create_dir_all(pi_b.parent().unwrap()).unwrap(); + std::fs::write( + &pi_b, + serde_json::json!({ "openai-codex": entry, "anthropic": anthropic_key }).to_string(), + ) + .unwrap(); + }; + write_pi(chatgpt("a@example.com", "acct-a")); + core_b.agent_accounts.list(false).await.expect("seed a"); + write_pi(chatgpt("b@example.com", "acct-b")); + let _host = core_b.start_host_relay(&relay_url); + + let mut core_a = assemble(&dirs.path().join("a"), "device-a"); + core_a.agent_accounts = AgentAccounts::new(AgentAccountsConfig::isolated(&dirs.path().join("a-agents"))); + let mut link_config = + LinkCacheConfig::new(relay_url.clone(), Arc::new(StaticToken("test-user".into()))); + link_config.probe_timeout = Duration::from_secs(5); + core_a.set_links(LinkCache::new(link_config)); + let client = zeron_rpc::memory_client(core_a.rpc_service()); + let remote = |extra: serde_json::Value| { + let mut params = serde_json::json!({ "targetDeviceId": "device-b" }); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + params + }; + + // B's accounts, through the relay: grouped by provider, one in use each. + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + let listed = loop { + match client.call(methods::LIST_AGENT_ACCOUNTS, remote(serde_json::json!({}))).await { + Ok(value) => break value, + Err(error) => { + assert!(tokio::time::Instant::now() < deadline, "relay never came up: {error}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + }; + let pi: Vec = listed["accounts"] + .as_array() + .unwrap() + .iter() + .filter(|a| a["harness"] == "pi") + .cloned() + .collect(); + let in_use = |rows: &[serde_json::Value], provider: &str| -> Vec { + rows.iter() + .filter(|a| a["provider"] == provider && a["active"] == true) + .map(|a| a["email"].as_str().unwrap().to_string()) + .collect() + }; + assert_eq!(in_use(&pi, "openai-codex"), ["b@example.com"]); + assert_eq!(in_use(&pi, "anthropic"), ["API key ···keep"]); + assert!(!listed.to_string().contains("keepKEEPkeep"), "a key's secret never leaves B"); + + // Switch B's ChatGPT account from A: B's ChatGPT entry alone changes. + let a_id = pi.iter().find(|a| a["email"] == "a@example.com").unwrap()["id"].clone(); + let switched = client + .call( + methods::ACTIVATE_AGENT_ACCOUNT, + remote(serde_json::json!({ "harness": "pi", "accountId": a_id })), + ) + .await + .expect("remote switch"); + let live: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&pi_b).unwrap()).unwrap(); + assert_eq!(live["openai-codex"]["accountId"], "acct-a"); + assert_eq!(live["anthropic"], anthropic_key); + let pi: Vec = switched["accounts"].as_array().unwrap().iter().filter(|a| a["harness"] == "pi").cloned().collect(); + assert_eq!(in_use(&pi, "openai-codex"), ["a@example.com"]); + assert_eq!(in_use(&pi, "anthropic"), ["API key ···keep"]); + + // A sign-in for one provider of B's agent, from A: the provider rides + // along to B's own handler (B answers for that provider: OpenCode has + // no Claude sign-in, and B says what works instead). The loopback + // sign-ins themselves then finish through the P2P callback tunnel, and + // the browser callback B replays (`relay_callback`) — covered for Pi's + // Claude in agent_accounts' `claude_for_pi_signs_in_…_for_another`. + let refused = client + .call( + methods::START_AGENT_LOGIN, + remote(serde_json::json!({ "harness": "opencode", "provider": "anthropic" })), + ) + .await + .expect_err("B refuses a provider its OpenCode can't sign in to"); + assert!(refused.to_string().contains("Anthropic API key"), "{refused}"); + + // An API key for B's Pi, asked of A: refused here, nothing sent. + let before = seen.lock().unwrap().len(); + let refused = client + .call( + methods::ADD_AGENT_API_KEY, + remote(serde_json::json!({ "harness": "pi", "provider": "openrouter", "key": KEY })), + ) + .await + .expect_err("a key is never carried to another device"); + assert!(refused.to_string().contains("device that runs the agent"), "{refused}"); + assert!(!refused.to_string().contains(KEY)); + assert_eq!(seen.lock().unwrap().len(), before, "nothing went to the relay"); + // A peer that sends one through the relay anyway is refused by B. + let mut peer_config = + LinkCacheConfig::new(relay_url.clone(), Arc::new(StaticToken("test-user".into()))); + peer_config.probe_timeout = Duration::from_secs(5); + let peer_links = LinkCache::new(peer_config); + let peer = peer_links.client("device-b").await.expect("peer link"); + let refused = peer + .call( + methods::ADD_AGENT_API_KEY, + serde_json::json!({ "harness": "pi", "provider": "openrouter", "key": KEY }), + ) + .await + .expect_err("B answers keys over its own IPC only"); + assert!(refused.to_string().contains("local IPC"), "{refused}"); + let live: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&pi_b).unwrap()).unwrap(); + assert!(live.get("openrouter").is_none()); + // In no file on either device (their data, docs, journals, slots and + // the agents' stores). + fn holds(dir: &std::path::Path, needle: &str) -> bool { + std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| { + let path = entry.path(); + if path.is_dir() { + holds(&path, needle) + } else { + std::fs::read(&path).is_ok_and(|bytes| { + bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) + }) + } + }) + } + assert!(!holds(dirs.path(), KEY), "the key is in a file"); +} diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs index 426fa5c5e..4741290df 100644 --- a/crates/engine/tests/e2e.rs +++ b/crates/engine/tests/e2e.rs @@ -79,6 +79,8 @@ fn mock_script() -> Vec { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, done(DoneStatus::Completed), @@ -1336,6 +1338,7 @@ fn spawn_chip(id: &str, status: SubagentStatus) -> MessagePart { subagent_ref: Some(format!("{CHAT}--sub--{id}")), subagent_status: Some(status), subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -2879,6 +2882,8 @@ async fn stale_tool_echo_after_steer_boundary_does_not_split_text() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, AgentEvent::TextDelta { text: "two".into() }, @@ -3283,6 +3288,8 @@ async fn generated_image_is_materialized_before_publication_and_survives_reopen( is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, image.clone(), @@ -3950,6 +3957,8 @@ async fn a_commands_whole_output_is_read_from_its_hosts_journal() { is_error: false, output: Some(output.clone()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: Some(0), }, AgentEvent::ToolCall { @@ -3963,6 +3972,8 @@ async fn a_commands_whole_output_is_read_from_its_hosts_journal() { is_error: false, output: Some("fn main() {}".into()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, done(DoneStatus::Completed), diff --git a/crates/engine/tests/m5c_accounts_uploads_titles.rs b/crates/engine/tests/m5c_accounts_uploads_titles.rs index 1f7c904ed..31d73e8f4 100644 --- a/crates/engine/tests/m5c_accounts_uploads_titles.rs +++ b/crates/engine/tests/m5c_accounts_uploads_titles.rs @@ -633,7 +633,7 @@ async fn grok_devin_opencode_and_pi_logins_swap_round_trip() { snapshot .accounts .iter() - .find(|a| a.harness == harness && a.active) + .find(|a| a.harness == harness && a.active && a.auth_kind != Some(zeron_proto::AgentAuthKind::ApiKey)) .map(|a| a.id.clone()) .expect("live login listed") }; @@ -653,10 +653,11 @@ async fn grok_devin_opencode_and_pi_logins_swap_round_trip() { write(&pi_file, pi("bob")); let second = accounts.list(false).await.expect("list"); for (harness, _) in &ann { + // (OpenCode's OpenRouter key is a login of its own provider.) let rows: Vec<_> = second .accounts .iter() - .filter(|a| a.harness == *harness) + .filter(|a| a.harness == *harness && a.auth_kind != Some(zeron_proto::AgentAuthKind::ApiKey)) .collect(); assert_eq!(rows.len(), 2, "{harness:?} keeps both logins"); assert_eq!(rows.iter().filter(|a| a.active).count(), 1); @@ -716,8 +717,8 @@ async fn hermes_credential_pool_is_listed_read_only() { let pool = serde_json::json!({ "active_provider": "nous", "credential_pool": { "nous": [ - { "id": "b", "label": "second@nous.ai", "auth_type": "oauth", "priority": 1, "access_token": "t2" }, - { "id": "a", "label": "first@nous.ai", "auth_type": "oauth", "priority": 0, "access_token": "t1" }, + { "id": "b", "label": "second@nous.ai", "auth_type": "oauth", "priority": 1, "source": "device_code", "access_token": "t2" }, + { "id": "a", "label": "first@nous.ai", "auth_type": "oauth", "priority": 0, "source": "device_code", "access_token": "t1" }, ]} }) .to_string(); @@ -1174,16 +1175,16 @@ async fn rpc_dispatch_for_m5c_methods() { assert!(snapshot["accounts"].is_array()); assert!(snapshot["warnings"].is_array()); - // The provider param reaches the engine: Pi's Claude login is refused - // with its reason (no port bound, no network). + // The provider param reaches the engine: OpenCode's Claude login (it + // has none) is refused with its reason (no port bound, no network). let refused = client .call( methods::START_AGENT_LOGIN, - serde_json::json!({ "harness": "pi", "provider": "anthropic" }), + serde_json::json!({ "harness": "opencode", "provider": "anthropic" }), ) .await - .expect_err("pi claude login is not offered"); - assert!(refused.to_string().contains("/login"), "{refused}"); + .expect_err("opencode has no claude login"); + assert!(refused.to_string().contains("API key"), "{refused}"); // Login lifecycle: start (loopback browser flow, like the CLI's own // automatic login) → poll pending → cancel → gone. diff --git a/crates/engine/tests/side_chats.rs b/crates/engine/tests/side_chats.rs index 376530054..7b1ab535e 100644 --- a/crates/engine/tests/side_chats.rs +++ b/crates/engine/tests/side_chats.rs @@ -434,6 +434,7 @@ async fn a_fork_settles_the_running_subagent_chips_it_copies() { subagent_ref: Some(format!("main--sub--{id}")), subagent_status: Some(status), subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/engine/tests/steer_now.rs b/crates/engine/tests/steer_now.rs index b4a1f6c63..042bd21c9 100644 --- a/crates/engine/tests/steer_now.rs +++ b/crates/engine/tests/steer_now.rs @@ -176,6 +176,8 @@ impl Harness for StepAgent { is_error: stopped, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }) .await; diff --git a/crates/engine/tests/subagent_idle_reap.rs b/crates/engine/tests/subagent_idle_reap.rs index 8a12cf8b6..e8b4d4a91 100644 --- a/crates/engine/tests/subagent_idle_reap.rs +++ b/crates/engine/tests/subagent_idle_reap.rs @@ -231,6 +231,8 @@ async fn park_after_spawn() -> Parked { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }) .unwrap(); diff --git a/crates/engine/tests/turn_quiesce.rs b/crates/engine/tests/turn_quiesce.rs index efd201770..d04773a5d 100644 --- a/crates/engine/tests/turn_quiesce.rs +++ b/crates/engine/tests/turn_quiesce.rs @@ -440,6 +440,8 @@ async fn open_tool_call_never_quiesces() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }) .unwrap(); @@ -481,6 +483,8 @@ async fn stale_tool_echo_stays_parked() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }) .unwrap(); diff --git a/crates/harness/src/acp/devin_models.rs b/crates/harness/src/acp/devin_models.rs index 7c55d3d3c..b9ea34748 100644 --- a/crates/harness/src/acp/devin_models.rs +++ b/crates/harness/src/acp/devin_models.rs @@ -470,6 +470,7 @@ fn parse_catalog(bytes: &[u8]) -> Result<(Vec, Vec), HarnessError> .id .clone(), label, + provider: None, description, reasoning_levels, options, @@ -496,6 +497,7 @@ fn parse_catalog(bytes: &[u8]) -> Result<(Vec, Vec), HarnessError> default: false, id: FUSION.into(), label: fusion_label.unwrap_or_else(|| "Fusion".into()), + provider: None, description: fusion_description, reasoning_levels: fusion_levels, options, diff --git a/crates/harness/src/acp/hermes_names.rs b/crates/harness/src/acp/hermes_names.rs new file mode 100644 index 000000000..7317e54ab --- /dev/null +++ b/crates/harness/src/acp/hermes_names.rs @@ -0,0 +1,469 @@ +//! Hermes's models by the names its own catalog gives them. +//! +//! Hermes's ACP adapter labels a model with its id (`claude-opus-5-5`), but +//! keeps the models.dev catalog it reads context windows from beside its +//! config (`$HERMES_HOME/models_dev_cache.json`), and that names each model +//! as its maker does ("Claude Opus 5.5"). A model it doesn't list keeps its +//! id. Zeron only reads the file; Hermes refreshes it. +use serde::de::{DeserializeSeed, Deserializer, IgnoredAny, MapAccess, Visitor}; +use std::{ + collections::{HashMap, HashSet}, + fmt, + path::Path, +}; +use zeron_proto::Model; + +/// The models.dev provider a Hermes provider's models are listed under, as +/// Hermes maps them (`agent/models_dev.py`); any other is its own id. +fn catalog_provider(hermes: &str) -> &str { + match hermes { + "openai-codex" | "openai-api" => "openai", + "novita" => "novita-ai", + "kimi" | "kimi-coding" | "kimi-coding-cn" | "moonshot" => "kimi-for-coding", + "minimax-oauth" => "minimax", + "qwen-oauth" => "alibaba", + "ai-gateway" => "vercel", + "opencode-zen" => "opencode", + "kilocode" => "kilo", + "fireworks" => "fireworks-ai", + "gemini" => "google", + "xai-oauth" => "xai", + "meta-ai" => "meta", + other => other, + } +} + +/// Hermes's large-context picker variants (`openai-codex:gpt-6-luna-900k`) +/// as a Context Window choice on their base model rather than rows of +/// their own. Hermes adds `-900k` after each Codex model that has one, a +/// Hermes-side name for the same model with the 900K window; the base runs +/// with Codex's 272K (`hermes_cli/codex_models.py`). A run that picks 900K +/// sends the variant's id (`pick_model_value`). A variant whose base isn't +/// listed stays its own row. +pub(super) fn fold_context_variants(models: &mut Vec) { + const SUFFIX: &str = "-900k"; + let ids: HashSet = models.iter().map(|m| m.id.clone()).collect(); + let folded: HashSet = ids + .iter() + .filter(|id| { + id.strip_suffix(SUFFIX) + .is_some_and(|base| ids.contains(base)) + }) + .cloned() + .collect(); + if folded.is_empty() { + return; + } + models.retain(|m| !folded.contains(&m.id)); + for model in models.iter_mut() { + if folded.contains(&format!("{}{SUFFIX}", model.id)) + && !model.options.iter().any(|o| o.id == "contextWindow") + { + model.options.push(zeron_proto::ModelOption { + id: "contextWindow".into(), + label: "Context Window".into(), + choices: vec![ + zeron_proto::ModelOptionChoice { + id: "272k".into(), + label: "272K".into(), + }, + zeron_proto::ModelOptionChoice { + id: "900k".into(), + label: "900K".into(), + }, + ], + default_choice: "272k".into(), + }); + } + } +} + +/// Renames each Hermes model whose label is still its bare id (the provider +/// already split off) after the catalog in Hermes's home, if there is one. +/// Blocking file work: call off the async runtime. +pub(super) fn name_models(models: &mut [Model]) { + let home = crate::model_context::root( + "HERMES_HOME", + crate::executable::home_or_current_dir().join(".hermes"), + ); + name_models_from(models, &home.join("models_dev_cache.json")); +} + +/// The most of Hermes's catalog read (it's a few MB). +const MAX_CATALOG_BYTES: u64 = 64 << 20; + +/// Catalog key → name, for the models asked about, by catalog provider. +type Names = HashMap>; + +fn name_models_from(models: &mut [Model], catalog: &Path) { + // The keys each model may be listed under: its id, and the id with + // dots as dashes (Hermes writes `claude-fable-5.1`; the catalog keys + // `claude-fable-5-1`). + let mut wanted: HashMap> = HashMap::new(); + for (provider, id) in models.iter().filter_map(named_by_id) { + let keys = wanted + .entry(catalog_provider(provider).to_owned()) + .or_default(); + keys.insert(id.replace('.', "-")); + keys.insert(id.to_owned()); + } + if wanted.is_empty() { + return; + } + // Streamed through a small buffer and kept only where asked for: the + // file is several MB of every provider's models, and holding it (or a + // map of it) would cost far more than the few names wanted. + // Only a regular file of a sane size: a FIFO (or a device) there would + // block the read forever, a runaway file would be parsed for minutes. + let Ok(meta) = std::fs::metadata(catalog) else { + return; + }; + if !meta.is_file() || meta.len() > MAX_CATALOG_BYTES { + tracing::debug!( + "Hermes's model catalog isn't a file of a usable size; models keep their ids" + ); + return; + } + let Ok(file) = std::fs::File::open(catalog) else { + return; + }; + let mut reader = + serde_json::Deserializer::from_reader(std::io::BufReader::with_capacity(64 * 1024, file)); + let names = match (Catalog { wanted: &wanted }).deserialize(&mut reader) { + Ok(names) => names, + Err(error) => { + tracing::debug!(%error, "Hermes's model catalog didn't parse; models keep their ids"); + return; + } + }; + for model in models.iter_mut() { + let Some((provider, id)) = named_by_id(model) else { + continue; + }; + let Some(listed) = names.get(catalog_provider(provider)) else { + continue; + }; + let name = listed + .get(id) + .or_else(|| listed.get(&id.replace('.', "-"))) + .cloned(); + if let Some(name) = name { + model.label = name; + } + } +} + +/// The catalog's top level: provider id → provider, reading only the +/// providers asked for and skipping the rest without keeping anything. +struct Catalog<'a> { + wanted: &'a HashMap>, +} + +impl<'de> DeserializeSeed<'de> for Catalog<'_> { + type Value = Names; + fn deserialize>(self, d: D) -> Result { + d.deserialize_map(self) + } +} + +impl<'de> Visitor<'de> for Catalog<'_> { + type Value = Names; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a models.dev catalog") + } + fn visit_map>(self, mut map: A) -> Result { + let mut names = Names::new(); + while let Some(provider) = map.next_key_seed(pick(|k| self.wanted.contains_key(k)))? { + match provider.and_then(|p| Some((self.wanted.get(&p)?, p))) { + Some((keys, provider)) => { + let found = map.next_value_seed(Provider { keys })?; + if !found.is_empty() { + names.insert(provider, found); + } + } + None => { + map.next_value::()?; + } + } + } + Ok(names) + } +} + +/// A map key, kept (allocated) only if `.0` wants it: the catalog's +/// thousands of other keys are only compared, in the parser's own buffer. +struct Pick(F); + +/// (A function, so a closure's `&str` is taken as any lifetime.) +fn pick bool>(wants: F) -> Pick { + Pick(wants) +} + +impl<'de, F: Fn(&str) -> bool> DeserializeSeed<'de> for Pick { + type Value = Option; + fn deserialize>(self, d: D) -> Result, D::Error> { + d.deserialize_str(self) + } +} + +impl<'de, F: Fn(&str) -> bool> Visitor<'de> for Pick { + type Value = Option; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a key") + } + fn visit_str(self, key: &str) -> Result, E> { + Ok((self.0)(key).then(|| key.to_owned())) + } +} + +/// A provider: its `models`, the rest skipped. +struct Provider<'a> { + keys: &'a HashSet, +} + +impl<'de> DeserializeSeed<'de> for Provider<'_> { + type Value = HashMap; + fn deserialize>(self, d: D) -> Result { + d.deserialize_map(self) + } +} + +impl<'de> Visitor<'de> for Provider<'_> { + type Value = HashMap; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a models.dev provider") + } + fn visit_map>(self, mut map: A) -> Result { + let mut found = HashMap::new(); + while let Some(field) = map.next_key_seed(pick(|k| k == "models"))? { + if field.is_some() { + found = map.next_value_seed(Models { keys: self.keys })?; + } else { + map.next_value::()?; + } + } + Ok(found) + } +} + +/// A provider's models: the name of each asked for, the rest skipped. +struct Models<'a> { + keys: &'a HashSet, +} + +impl<'de> DeserializeSeed<'de> for Models<'_> { + type Value = HashMap; + fn deserialize>(self, d: D) -> Result { + d.deserialize_map(self) + } +} + +impl<'de> Visitor<'de> for Models<'_> { + type Value = HashMap; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a provider's models") + } + fn visit_map>(self, mut map: A) -> Result { + #[derive(serde::Deserialize)] + struct Entry { + #[serde(default)] + name: Option, + } + let mut found = HashMap::new(); + while let Some(key) = map.next_key_seed(pick(|k| self.keys.contains(k)))? { + if let Some(key) = key { + let name = map + .next_value::()? + .name + .map(|n| n.trim().to_owned()) + .filter(|n| !n.is_empty()); + if let Some(name) = name { + found.insert(key, name); + } + } else { + map.next_value::()?; + } + } + Ok(found) + } +} + +/// `(provider, model id)` of a model labelled by its id alone. +fn named_by_id(model: &Model) -> Option<(&str, &str)> { + let provider = model.provider.as_ref()?; + let (_, id) = model.id.split_once(':')?; + (model.label == id).then_some((provider.id.as_str(), id)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn model(id: &str, label: &str, provider: &str) -> Model { + Model { + id: id.into(), + label: label.into(), + provider: Some(zeron_proto::ModelProvider { + id: provider.into(), + name: provider.into(), + }), + description: None, + reasoning_levels: vec![], + options: vec![], + default: false, + } + } + + /// Hermes's `-900k` rows fold into their base's Context Window; one + /// without a listed base stays. + #[test] + fn hermes_large_context_variants_are_a_context_window_choice() { + let mut models = vec![ + model("openai-codex:gpt-6-luna", "gpt-6-luna", "openai-codex"), + model( + "openai-codex:gpt-6-luna-900k", + "gpt-6-luna-900k", + "openai-codex", + ), + model( + "openai-codex:gpt-6.1-terra", + "gpt-6.1-terra", + "openai-codex", + ), + model("openai-codex:gpt-9-900k", "gpt-9-900k", "openai-codex"), + ]; + fold_context_variants(&mut models); + let ids: Vec<_> = models.iter().map(|m| m.id.as_str()).collect(); + assert_eq!( + ids, + [ + "openai-codex:gpt-6-luna", + "openai-codex:gpt-6.1-terra", + "openai-codex:gpt-9-900k" + ] + ); + let window = models[0] + .options + .iter() + .find(|o| o.id == "contextWindow") + .unwrap(); + assert_eq!(window.default_choice, "272k"); + assert_eq!( + window + .choices + .iter() + .map(|c| c.label.as_str()) + .collect::>(), + ["272K", "900K"] + ); + assert!(models[1].options.is_empty()); + // Picking 900K sends the variant; the default sends the model. + let available = ["openai-codex:gpt-6-luna", "openai-codex:gpt-6-luna-900k"]; + assert_eq!( + super::super::pick_model_value("openai-codex:gpt-6-luna", &available, Some("900k")) + .as_deref(), + Some("openai-codex:gpt-6-luna-900k") + ); + assert_eq!( + super::super::pick_model_value("openai-codex:gpt-6-luna", &available, Some("272k")) + .as_deref(), + Some("openai-codex:gpt-6-luna") + ); + // A chat that saved the variant itself still runs it. + assert_eq!( + super::super::pick_model_value("openai-codex:gpt-6-luna-900k", &available, None) + .as_deref(), + Some("openai-codex:gpt-6-luna-900k") + ); + } + + /// A catalog that isn't a regular file of a usable size is passed over + /// at once: a FIFO would block a read forever. + #[cfg(unix)] + #[test] + fn a_catalog_that_isnt_a_plain_file_of_a_usable_size_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("models_dev_cache.json"); + let made = std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap(); + assert!(made.success()); + let mut models = vec![model( + "anthropic:claude-opus-5-5", + "claude-opus-5-5", + "anthropic", + )]; + let started = std::time::Instant::now(); + name_models_from(&mut models, &fifo); + assert!(started.elapsed() < std::time::Duration::from_secs(1)); + assert_eq!(models[0].label, "claude-opus-5-5"); + // Past the size cap (sparse: no disk spent): skipped unread. + let big = dir.path().join("big.json"); + let file = std::fs::File::create(&big).unwrap(); + file.set_len(MAX_CATALOG_BYTES + 1).unwrap(); + name_models_from(&mut models, &big); + assert_eq!(models[0].label, "claude-opus-5-5"); + } + + /// Hermes's own catalog names its models; one it doesn't list keeps + /// its id, and a label Hermes wrote itself is left as it is. + #[test] + fn hermes_models_read_as_its_catalog_names_them() { + let dir = tempfile::tempdir().unwrap(); + let catalog = dir.path().join("models_dev_cache.json"); + // The shape of a real models.dev cache, trimmed. + std::fs::write( + &catalog, + r#"{ + "anthropic": {"id": "anthropic", "name": "Anthropic", "models": { + "claude-opus-5-5": {"id": "claude-opus-5-5", "name": "Claude Opus 5.5", "reasoning": true}, + "claude-fable-5-1": {"id": "claude-fable-5-1", "name": "Claude Fable 5.1"} + }}, + "openai": {"id": "openai", "models": { + "gpt-6-luna": {"id": "gpt-6-luna", "name": "GPT-6 Luna"} + }} + }"#, + ) + .unwrap(); + let mut models = vec![ + model("anthropic:claude-opus-5-5", "claude-opus-5-5", "anthropic"), + model( + "anthropic:claude-fable-5.1", + "claude-fable-5.1", + "anthropic", + ), + model("openai-codex:gpt-6-luna", "gpt-6-luna", "openai-codex"), + model( + "openai-codex:gpt-6-luna-900k", + "gpt-6-luna-900k", + "openai-codex", + ), + model("ollama:llama3", "llama3", "ollama"), + model("anthropic:claude-opus-5-5", "My Opus", "anthropic"), + ]; + name_models_from(&mut models, &catalog); + let labels: Vec<_> = models.iter().map(|m| m.label.as_str()).collect(); + assert_eq!( + labels, + [ + "Claude Opus 5.5", + "Claude Fable 5.1", + "GPT-6 Luna", + "gpt-6-luna-900k", + "llama3", + "My Opus" + ] + ); + // No catalog, or one that doesn't parse: ids, and no error. + let mut models = vec![model( + "anthropic:claude-opus-5-5", + "claude-opus-5-5", + "anthropic", + )]; + name_models_from(&mut models, &dir.path().join("missing.json")); + std::fs::write(&catalog, "not json").unwrap(); + name_models_from(&mut models, &catalog); + assert_eq!(models[0].label, "claude-opus-5-5"); + } +} diff --git a/crates/harness/src/acp/mod.rs b/crates/harness/src/acp/mod.rs index 2925ac26c..a2e0d9a91 100644 --- a/crates/harness/src/acp/mod.rs +++ b/crates/harness/src/acp/mod.rs @@ -34,6 +34,10 @@ mod antigravity_paths; mod devin_models; +mod hermes_names; +/// How long Hermes's model names may take to read before the list goes +/// out with ids. +const HERMES_NAMING_WAIT: std::time::Duration = std::time::Duration::from_secs(5); mod normalize; mod permission; mod subagent; @@ -265,6 +269,7 @@ fn grok_spec() -> AcpAgentSpec { default: false, id: "grok-4.5".into(), label: "Grok 4.5".into(), + provider: None, description: Some("xAI's coding model — 500k context".into()), reasoning_levels: vec![ ReasoningLevel::Low, @@ -343,6 +348,7 @@ fn devin_spec() -> AcpAgentSpec { default: false, id: "swe-1-7-medium".into(), label: "SWE-1.7 Medium".into(), + provider: None, description: Some("Devin's default coding model".into()), reasoning_levels: Vec::new(), options: Vec::new(), @@ -351,6 +357,7 @@ fn devin_spec() -> AcpAgentSpec { default: false, id: "claude-fable-5-1-high".into(), label: "Claude Fable 5.1 High".into(), + provider: None, description: Some("Anthropic's frontier model through Devin".into()), reasoning_levels: Vec::new(), options: Vec::new(), @@ -359,6 +366,7 @@ fn devin_spec() -> AcpAgentSpec { default: false, id: "adaptive".into(), label: "Adaptive".into(), + provider: None, description: Some("Devin picks the model per request".into()), reasoning_levels: Vec::new(), options: Vec::new(), @@ -502,6 +510,7 @@ fn hermes_spec() -> AcpAgentSpec { default: false, id: "hermes-4-405b".into(), label: "Hermes 4 405B".into(), + provider: None, description: Some("Nous Research's hybrid-reasoning flagship".into()), reasoning_levels: Vec::new(), options: Vec::new(), @@ -510,6 +519,7 @@ fn hermes_spec() -> AcpAgentSpec { default: false, id: "hermes-4-70b".into(), label: "Hermes 4 70B".into(), + provider: None, description: Some("Faster Hermes 4 — same post-training, 70B".into()), reasoning_levels: Vec::new(), options: Vec::new(), @@ -1213,6 +1223,7 @@ fn antigravity_spec() -> AcpAgentSpec { default: false, id: "gemini-3.7-flash".into(), label: "Gemini 3.7 Flash".into(), + provider: None, description: None, reasoning_levels: vec![Low, Medium, High], options: Vec::new(), @@ -1221,6 +1232,7 @@ fn antigravity_spec() -> AcpAgentSpec { default: false, id: "gemini-3.1-pro".into(), label: "Gemini 3.1 Pro".into(), + provider: None, description: None, reasoning_levels: vec![Low, High], options: Vec::new(), @@ -2824,6 +2836,9 @@ impl AcpHarness { .request("session/new", json!({ "cwd": cwd, "mcpServers": [] })) .await?; let mut models = models_from_session(&session, &(self.spec.models)()); + if self.spec.id == HarnessId::Hermes { + hermes_names::fold_context_variants(&mut models); + } // Prompt-convention modes (Claude Ultrathink) extend any real // ladder — never an effort-less model's empty one. for model in &mut models { @@ -2845,7 +2860,36 @@ impl AcpHarness { let result = tokio::time::timeout(self.model_discovery_timeout, discovery).await; drain.abort(); client.close_stdin_for_teardown(); - child.shutdown(self.kill_grace).await; + // Hermes's names come from a file, read on a blocking thread while + // the agent shuts down: neither waits on the other, and no async + // worker is held by file reads. + let result = match result { + Ok(Ok(models)) if self.spec.id == HarnessId::Hermes => { + // (Named within a few seconds, or kept as they are: a slow + // disk never holds up the model list.) + let unnamed = models.clone(); + let naming = tokio::task::spawn_blocking(move || { + let mut models = models; + hermes_names::name_models(&mut models); + models + }); + child.shutdown(self.kill_grace).await; + match tokio::time::timeout(HERMES_NAMING_WAIT, naming).await { + Ok(Ok(models)) => Ok(Ok(models)), + Ok(Err(error)) => Ok(Err(HarnessError::Protocol(format!( + "naming Hermes models failed: {error}" + )))), + Err(_) => { + tracing::debug!("naming Hermes models took too long; models keep their ids"); + Ok(Ok(unnamed)) + } + } + } + result => { + child.shutdown(self.kill_grace).await; + result + } + }; match result { Ok(inner) => inner, Err(_) => { @@ -2892,6 +2936,56 @@ fn reasoning_from_value(value: &str) -> Option { /// unmatched models keep fast mode etc.; the catalog only enriches matched /// ids with label/description/per-model ladders. fn models_from_session(session_response: &Value, catalog: &[Model]) -> Vec { + let mut models = models_from_session_wire(session_response, catalog); + for model in &mut models { + split_provider_label(model); + } + models +} + +/// A model an agent names `:` and labels +/// ` · ` (Hermes: `anthropic:claude-fable-5.1`, "Anthropic · +/// claude-fable-5.1"): its label is the model, and its provider rides on +/// `provider`, named as people say it (`openai-codex` → Codex, as for Pi and +/// OpenCode), else as the agent wrote it. The picker shows it beside the +/// name, like every agent that reaches models through several providers. +fn split_provider_label(model: &mut Model) { + if model.provider.is_some() { + return; + } + let Some((pid, _)) = model.id.split_once(':') else { + return; + }; + let Some((written, name)) = model.label.split_once(" \u{b7} ") else { + return; + }; + let (pid, written, name) = (pid.trim(), written.trim(), name.trim()); + if pid.is_empty() || written.is_empty() || name.is_empty() { + return; + } + let known = crate::pi::provider_name(pid); + // (A name the map only spelled out from the id reads worse than the + // agent's own: keep the agent's then.) + let spelled = pid + .split(['-', '_']) + .filter(|w| !w.is_empty()) + .map(|w| { + let mut c = w.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect::()) + .unwrap_or_default() + }) + .collect::>() + .join(" "); + let provider_name = if known == spelled { written.to_owned() } else { known }; + model.label = name.to_owned(); + model.provider = Some(zeron_proto::ModelProvider { + id: pid.to_owned(), + name: provider_name, + }); +} + +fn models_from_session_wire(session_response: &Value, catalog: &[Model]) -> Vec { let config_options = session_response .get("configOptions") .and_then(Value::as_array) @@ -2947,6 +3041,7 @@ fn models_from_session(session_response: &Value, catalog: &[Model]) -> Vec &str { /// variants in either hint spelling. Exact match first (with the 1M compose /// when the run selects the 1M window), then a family-token fallback that /// prefers a variant matching the requested context window. -fn pick_model_value(requested: &str, available: &[&str], context_1m: bool) -> Option { - if context_1m { - for composed in [format!("{requested}[1m]"), format!("{requested}-1m")] { +fn pick_model_value(requested: &str, available: &[&str], window: Option<&str>) -> Option { + // The chosen window's variant when the agent lists one: `[1m]` / + // `-1m` (Claude), `-900k` (Hermes's Codex variants). The + // default window has none, and runs the model itself. + if let Some(window) = window + .map(str::to_ascii_lowercase) + .filter(|w| !w.is_empty()) + { + for composed in [ + format!("{requested}[{window}]"), + format!("{requested}-{window}"), + ] { if available.contains(&composed.as_str()) { return Some(composed); } } } + let context_1m = window.is_some_and(|w| w.eq_ignore_ascii_case("1m")); if available.contains(&requested) { return Some(requested.to_owned()); } @@ -3772,11 +3877,8 @@ fn validate_config_model_selection( .iter() .filter_map(|choice| choice.get("value").and_then(Value::as_str)) .collect(); - let context_1m = model_options - .get("contextWindow") - .and_then(Value::as_str) - .is_some_and(|window| window.eq_ignore_ascii_case("1m")); - if pick_model_value(requested, &available, context_1m).is_some() { + let window = model_options.get("contextWindow").and_then(Value::as_str); + if pick_model_value(requested, &available, window).is_some() { return Ok(()); } Err(HarnessError::Protocol(format!( @@ -3842,10 +3944,7 @@ fn config_option_sets( else { return Vec::new(); }; - let context_1m = model_options - .get("contextWindow") - .and_then(Value::as_str) - .is_some_and(|w| w.eq_ignore_ascii_case("1m")); + let window = model_options.get("contextWindow").and_then(Value::as_str); let mut sets = Vec::new(); for option in options { let Some(config_id) = option.get("id").and_then(Value::as_str) else { @@ -3865,7 +3964,7 @@ fn config_option_sets( let wanted: Option = match (kind, category) { ("select", Some("model")) => model - .and_then(|m| pick_model_value(m, &available, context_1m)) + .and_then(|m| pick_model_value(m, &available, window)) .map(Value::String), // Full access: unattended parity with the retired custom // adapters (claude bypassPermissions / codex approvalPolicy @@ -4668,6 +4767,7 @@ fn group_effort_variants(models: Vec) -> Vec { id: group.id.clone(), label: group.label.to_owned(), // variant descriptions only restate their thinking level + provider: first.provider.clone(), description: None, reasoning_levels: group.variants.iter().map(|(level, _)| *level).collect(), options: first.options.clone(), @@ -7617,6 +7717,44 @@ mod tests { ); } + /// Hermes names a model `:` and labels it ` · + /// `: the picker gets the model as its name and the provider + /// apart, named as people say it; a provider the map doesn't know keeps + /// the agent's own wording. A label without the shape stays as it is. + #[test] + fn a_provider_glued_to_a_models_label_rides_apart() { + let response = json!({ + "sessionId": "s-1", + "configOptions": [ + { + "id": "model", + "category": "model", + "type": "select", + "currentValue": "anthropic:claude-fable-5.1", + "options": [ + { "value": "anthropic:claude-fable-5.1", "name": "Anthropic \u{b7} claude-fable-5.1" }, + { "value": "openai-codex:gpt-6-luna", "name": "ChatGPT or Codex Subscription \u{b7} gpt-6-luna" }, + { "value": "nous-portal:hermes-4-405b", "name": "Nous Portal Plus \u{b7} hermes-4-405b" }, + { "value": "local-model", "name": "Local Model" }, + ], + }, + ], + }); + let models = models_from_session(&response, &[]); + let row = |id: &str| models.iter().find(|m| m.id == id).unwrap_or_else(|| panic!("{id}")); + let fable = row("anthropic:claude-fable-5.1"); + assert_eq!(fable.label, "claude-fable-5.1"); + assert_eq!(fable.provider.as_ref().map(|p| (p.id.as_str(), p.name.as_str())), Some(("anthropic", "Anthropic"))); + let luna = row("openai-codex:gpt-6-luna"); + assert_eq!(luna.label, "gpt-6-luna"); + assert_eq!(luna.provider.as_ref().map(|p| p.name.as_str()), Some("Codex")); + let nous = row("nous-portal:hermes-4-405b"); + assert_eq!(nous.provider.as_ref().map(|p| p.name.as_str()), Some("Nous Portal Plus")); + let plain = row("local-model"); + assert_eq!(plain.label, "Local Model"); + assert!(plain.provider.is_none()); + } + #[test] fn model_1m_variants_collapse_into_a_context_window_trait() { let response = json!({ diff --git a/crates/harness/src/acp/normalize.rs b/crates/harness/src/acp/normalize.rs index a9e33ff77..aa220c53a 100644 --- a/crates/harness/src/acp/normalize.rs +++ b/crates/harness/src/acp/normalize.rs @@ -422,6 +422,8 @@ pub(crate) fn map_update(update: &Value) -> Vec { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] @@ -461,6 +463,8 @@ fn resolved_result(update: &Value, id: String) -> Option { is_error, output: tool_output(update), diff: tool_diff(update), + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }) } @@ -562,6 +566,8 @@ mod tests { is_error: false, output: Some("total 0".into()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] @@ -606,6 +612,8 @@ mod tests { old_text: Some("fn old() {}".into()), new_text: "fn new() {}".into(), }), + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, } ); @@ -645,6 +653,8 @@ mod tests { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }] ); diff --git a/crates/harness/src/acp/subagent.rs b/crates/harness/src/acp/subagent.rs index 27ce5fe91..fe526879b 100644 --- a/crates/harness/src/acp/subagent.rs +++ b/crates/harness/src/acp/subagent.rs @@ -402,6 +402,8 @@ fn entry_events(entry: &Value) -> Vec { is_error: false, output, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); } diff --git a/crates/harness/src/acp/system_message.rs b/crates/harness/src/acp/system_message.rs index fb3bffc9f..233384a36 100644 --- a/crates/harness/src/acp/system_message.rs +++ b/crates/harness/src/acp/system_message.rs @@ -266,6 +266,8 @@ mod tests { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ]; diff --git a/crates/harness/src/catalog.rs b/crates/harness/src/catalog.rs index c7c2bb108..e0fd2ad31 100644 --- a/crates/harness/src/catalog.rs +++ b/crates/harness/src/catalog.rs @@ -203,6 +203,7 @@ mod tests { default: false, id: id.into(), label: id.into(), + provider: None, description: None, reasoning_levels: vec![], options: vec![], diff --git a/crates/harness/src/claude/catalog.rs b/crates/harness/src/claude/catalog.rs index f907188c4..d8ba4e8b8 100644 --- a/crates/harness/src/claude/catalog.rs +++ b/crates/harness/src/claude/catalog.rs @@ -148,6 +148,7 @@ fn model( default: false, id: id.into(), label: label.into(), + provider: None, description: (!description.is_empty()).then(|| description.into()), reasoning_levels: ladder.to_vec(), options, @@ -237,6 +238,7 @@ fn models_with_settings(path: &std::path::Path) -> Vec { default: false, id: id.into(), label: id.into(), + provider: None, description: None, reasoning_levels: FULL_LADDER.to_vec(), options: vec![], @@ -427,6 +429,7 @@ pub(super) fn with_discovered_models_for( default: false, id: id.into(), label: label.unwrap_or(id).into(), + provider: None, description: text("description").map(str::to_owned), reasoning_levels: ladder, options: vec![], diff --git a/crates/harness/src/claude/normalize.rs b/crates/harness/src/claude/normalize.rs index 7fd214b16..1908e969b 100644 --- a/crates/harness/src/claude/normalize.rs +++ b/crates/harness/src/claude/normalize.rs @@ -262,7 +262,11 @@ fn tag(parent: &str, event: AgentEvent) -> AgentEvent { /// arrive only as full blocks on its tagged assistant frames — emit them, in /// block order with the tool calls, or subagent transcripts are /// tool-chips-only. -fn subagent_message(parent: &str, f: &MessageFrame) -> Vec { +fn subagent_message( + paths: &mut std::collections::HashMap, + parent: &str, + f: &MessageFrame, +) -> Vec { let mut out: Vec = f .message .blocks() @@ -279,13 +283,17 @@ fn subagent_message(parent: &str, f: &MessageFrame) -> Vec { text: format!("{}\n\n", b.thinking.trim_end()), }, )), - "tool_use" => Some(tag( - parent, - AgentEvent::ToolCall { - id: b.id.clone(), - call: decode_tool_use(&b.name, &b.input), - }, - )), + "tool_use" => { + let call = decode_tool_use(&b.name, &b.input); + remember_tool_file(paths, &b.id, &call); + Some(tag( + parent, + AgentEvent::ToolCall { + id: b.id.clone(), + call, + }, + )) + } _ => None, }) .collect(); @@ -300,17 +308,37 @@ fn subagent_message(parent: &str, f: &MessageFrame) -> Vec { out } -/// A subagent's tool results, attributed like its calls. -fn subagent_results( - parent: &str, - f: &MessageFrame, - commands: &mut std::collections::HashMap, -) -> Vec { - f.message - .blocks() - .filter(|b: &ContentBlock| b.kind == "tool_result") - .map(|b| tag(parent, tool_result(&b, commands))) - .collect() +fn remember_tool_file( + paths: &mut std::collections::HashMap, + id: &str, + call: &ToolCall, +) { + if id.is_empty() { + return; + } + let path = match call { + ToolCall::ReadFile { path } + | ToolCall::WriteFile { path, .. } + | ToolCall::EditFile { path, .. } => path.as_str(), + _ => return, + }; + let name = file_basename(path); + if name.is_empty() { + return; + } + paths.insert(id.to_owned(), name.to_owned()); +} + +fn empty_tool_result(id: impl Into, is_error: bool) -> AgentEvent { + AgentEvent::ToolResult { + id: id.into(), + is_error, + output: None, + diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), + exit_code: None, + } } /// Records `f`'s Bash calls, so their results carry the command's output. @@ -360,6 +388,8 @@ fn tool_result( is_error, output, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code, } } @@ -398,9 +428,156 @@ fn path_safe(id: &str) -> bool { /// /// Prefix-matched: the CLI ships at least two spellings of the marker /// (`…by user]` and `…by user for tool use]`). +/// +/// Also the CLI's image note, which rides a user frame after a tool result +/// that already carries the pixels: `[Image: source: ]` and +/// `[Image: original WxH, displayed at WxH. …]`. On a tagged frame it must +/// not read as a steer. fn is_synthetic_user_text(text: &str) -> bool { - let text = text.trim_start(); - text.starts_with("") || text.starts_with("[Request interrupted") + let text = text.trim(); + if text.starts_with("") || text.starts_with("[Request interrupted") { + return true; + } + is_image_note(text) +} + +/// The CLI's image note exactly: one line, `[Image: source: ]` (the +/// path may be followed by `, original WxH, displayed at WxH. …`), or +/// `[Image: original WxH, displayed at WxH. …]`. A steer that only starts +/// and ends like one (`[Image: original mockup attached]\nmatch it [urgent]`) +/// is not it. +fn is_image_note(text: &str) -> bool { + if text.contains('\n') { + return false; + } + let Some(rest) = text + .strip_prefix("[Image: ") + .and_then(|rest| rest.strip_suffix(']')) + else { + return false; + }; + if let Some(path) = rest.strip_prefix("source: ") { + return !path.trim().is_empty() && !path.contains(['[', ']']); + } + rest.strip_prefix("original ").is_some_and(sizes_note) +} + +/// `WxH, displayed at WxH` and whatever the CLI says after it. +fn sizes_note(text: &str) -> bool { + fn dimensions(text: &str) -> Option<&str> { + let (width, rest) = text.split_once('x')?; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + (!width.is_empty() && width.bytes().all(|b| b.is_ascii_digit()) && digits > 0) + .then(|| &rest[digits..]) + } + dimensions(text) + .and_then(|rest| rest.strip_prefix(", displayed at ")) + .and_then(dimensions) + .is_some_and(|rest| !rest.contains(['[', ']'])) +} + +/// Images kept from one tool result. Matches the chip preview cap. +const MAX_TOOL_RESULT_IMAGES: usize = 4; + +fn is_base64_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=') +} + +/// Copy `data` when it looks like base64 within the image size cap. +/// Whitespace is removed. Anything else is dropped before it is stored. +fn compact_base64(data: &str) -> Option { + let limit = zeron_proto::IMAGE_MAX_BYTES.div_ceil(3) * 4; + let mut count = 0usize; + for byte in data.bytes() { + if byte.is_ascii_whitespace() { + continue; + } + if !is_base64_byte(byte) { + return None; + } + count += 1; + if count > limit { + return None; + } + } + if count == 0 { + return None; + } + if count == data.len() { + return Some(data.to_owned()); + } + Some( + data.bytes() + .filter(|byte| !byte.is_ascii_whitespace()) + .map(char::from) + .collect(), + ) +} + +fn push_tool_image(out: &mut Vec, name: &str, data: &str) { + if out.len() >= MAX_TOOL_RESULT_IMAGES { + return; + } + let Some(data_base64) = compact_base64(data) else { + return; + }; + out.push(zeron_proto::ToolResultImage { + name: name.to_owned(), + data_base64, + }); +} + +/// Image blocks inside a tool result's `content` array. +fn images_in_content(content: Option<&Value>, name: &str) -> Vec { + let mut out = Vec::new(); + let Some(blocks) = content.and_then(Value::as_array) else { + return out; + }; + for block in blocks { + if out.len() >= MAX_TOOL_RESULT_IMAGES { + break; + } + if block.get("type").and_then(Value::as_str) != Some("image") { + continue; + } + if let Some(kind) = block.pointer("/source/type").and_then(Value::as_str) + && kind != "base64" + { + continue; + } + let Some(data) = block + .pointer("/source/data") + .and_then(Value::as_str) + .or_else(|| block.get("data").and_then(Value::as_str)) + else { + continue; + }; + push_tool_image(&mut out, name, data); + } + out +} + +/// `toolUseResult` image, used only when the content blocks had none. +fn image_from_tool_use_result( + value: Option<&Value>, + name: &str, +) -> Option { + let value = value?; + if value.get("type").and_then(Value::as_str) != Some("image") { + return None; + } + let data = value.pointer("/file/base64").and_then(Value::as_str)?; + let data_base64 = compact_base64(data)?; + Some(zeron_proto::ToolResultImage { + name: name.to_owned(), + data_base64, + }) +} + +fn file_basename(path: &str) -> &str { + path.rsplit(['/', '\\']) + .find(|part| !part.is_empty()) + .unwrap_or("image.png") } /// What `--resume ` would find in Claude's native history. @@ -477,6 +654,10 @@ pub(crate) struct Normalizer { /// which then opened as an empty, never-created subagent doc (user /// report 2026-08-20). agent_spawn_tools: std::collections::HashSet, + /// tool_use id → file basename for Read/Write/Edit, so an image result + /// can be labeled with the file the tool named. Removed when the result + /// arrives. + tool_paths: std::collections::HashMap, /// Bash calls not yet answered, tool_use id → whether it runs in the /// background: their results carry the command's output and exit code. command_calls: std::collections::HashMap, @@ -509,6 +690,7 @@ impl Normalizer { agent_tool_spawns: std::collections::HashMap::new(), skill_calls: std::collections::HashMap::new(), agent_spawn_tools: std::collections::HashSet::new(), + tool_paths: std::collections::HashMap::new(), command_calls: std::collections::HashMap::new(), typed_fork: None, fork_transcripts: true, @@ -519,6 +701,49 @@ impl Normalizer { } } + /// Tool results on a user frame. A Bash call's carries its output tail + /// and exit code ([`tool_result`]). Image bytes ride the result's content + /// blocks (or `toolUseResult` when those blocks have none) and stay off + /// the journal: only `image_payloads` carries them, and the engine strips + /// that before publish. + fn tool_result_events( + &mut self, + frame: &MessageFrame, + clear_inline_skills: bool, + ) -> Vec { + let mut pending = Vec::new(); + for block in frame.message.blocks() { + if block.kind != "tool_result" { + continue; + } + if clear_inline_skills { + self.skill_calls.remove(&block.tool_use_id); + } + let name = self + .tool_paths + .remove(&block.tool_use_id) + .unwrap_or_else(|| "image.png".into()); + let images = images_in_content(Some(&block.content), &name); + let event = tool_result(&block, &mut self.command_calls); + pending.push((event, name, images)); + } + if pending.len() == 1 && pending[0].2.is_empty() { + let name = pending[0].1.clone(); + if let Some(image) = image_from_tool_use_result(frame.tool_use_result.as_ref(), &name) { + pending[0].2.push(image); + } + } + pending + .into_iter() + .map(|(mut event, _name, images)| { + if let AgentEvent::ToolResult { image_payloads, .. } = &mut event { + *image_payloads = images; + } + event + }) + .collect() + } + /// The CLI reported its session (`system:init`). pub fn started(&self) -> bool { self.saw_init @@ -711,13 +936,7 @@ impl Normalizer { session_id: None, }, ), - AgentEvent::ToolResult { - id: fork.chip, - is_error: status == DoneStatus::Errored, - output: None, - diff: None, - exit_code: None, - }, + empty_tool_result(&fork.chip, status == DoneStatus::Errored), ] } @@ -747,10 +966,11 @@ impl Normalizer { /// records) are not conversation. Once the replay has begun, it brings /// the rest. pub(crate) fn fork_record(&mut self, record: Value) -> Vec { - let Some(fork) = self + let Some(chip) = self .typed_fork - .as_mut() + .as_ref() .filter(|fork| fork.replayed.is_none()) + .map(|fork| fork.chip.clone()) else { return Vec::new(); }; @@ -764,12 +984,18 @@ impl Normalizer { }; let events = if assistant { note_commands(&f, &mut self.command_calls); - subagent_message(&fork.chip, &f) + subagent_message(&mut self.tool_paths, &chip, &f) } else { - subagent_results(&fork.chip, &f, &mut self.command_calls) + // Disk replay shows tool results only, the same as before. Image + // bytes on those results are kept; a scale note is not a message. + self.tool_result_events(&f, false) + .into_iter() + .map(|event| tag(&chip, event)) + .collect() }; if !events.is_empty() && let Some(uuid) = f.uuid + && let Some(fork) = self.typed_fork.as_mut() { fork.seen.insert(uuid); } @@ -1058,7 +1284,7 @@ impl Normalizer { if self.fork_repeat(parent, f.uuid.as_deref()) { return Vec::new(); } - return subagent_message(parent, &f); + return subagent_message(&mut self.tool_paths, parent, &f); } // Record spawn tool ids up front: `task_notification` keys on // them; a task may finish before a `task_started` arrives. A @@ -1083,9 +1309,11 @@ impl Normalizer { .blocks() .filter(|b: &ContentBlock| b.kind == "tool_use") .flat_map(|b| { + let decoded = decode_tool_use(&b.name, &b.input); + remember_tool_file(&mut self.tool_paths, &b.id, &decoded); let call = AgentEvent::ToolCall { id: b.id.clone(), - call: decode_tool_use(&b.name, &b.input), + call: decoded, }; // A spawn's `prompt` is the subagent's opening user // message — the wire never echoes it on the child @@ -1178,7 +1406,16 @@ impl Normalizer { } // A subagent's tool results echo on the main channel too; // they belong to its transcript, attributed like its calls. - let mut out = subagent_results(parent, &f, &mut self.command_calls); + let mut out = self + .tool_result_events(&f, false) + .into_iter() + .map(|event| tag(parent, event)) + .collect::>(); + // A meta frame's text is bookkeeping (the image scale note + // is one). It must not read as a steer. + if f.is_meta { + return out; + } // A tagged user frame's TEXT blocks are the parent // steering its subagent (SendMessage-style follow-ups — // tool results ride their own blocks, filtered above). @@ -1209,16 +1446,10 @@ impl Normalizer { ); return out; } - f.message - .blocks() - .filter(|b: &ContentBlock| b.kind == "tool_result") - .map(|b| { - // A skill whose result came back without a task - // start ran inline: it never forks now. - self.skill_calls.remove(&b.tool_use_id); - tool_result(&b, &mut self.command_calls) - }) - .collect() + // A skill whose result came back without a task start ran + // inline: it never forks now. `tool_result_events` drops that + // pending skill when asked. + self.tool_result_events(&f, true) } // A claude.ai plan window was hit. A hard `rejected` blocks the @@ -1726,6 +1957,8 @@ mod tests { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), // (A subagent's Bash too: no `Exit code` lead, it exited 0.) exit_code: Some(0), }), @@ -1798,6 +2031,164 @@ mod tests { ); } + /// Only the CLI's own image notes are bookkeeping: a steer that merely + /// starts with `[Image: ` and ends with `]` still reaches the agent. + #[test] + fn only_the_clis_image_notes_are_synthetic() { + for note in [ + "[Image: source: /tmp/shots/1.png]", + "[Image: source: /tmp/shots/1.png, original 10x10, displayed at 10x10.]", + "[Image: original 1884x2066, displayed at 1824x2000. Multiply coordinates by 1.03 to map to original image.]", + " [Image: original 10x10, displayed at 10x10] ", + ] { + assert!(super::is_synthetic_user_text(note), "{note}"); + } + for steer in [ + "[Image: original mockup attached]\nmatch it exactly [urgent]", + "[Image: original mockup attached]", + "[Image: original 10x10 please]", + "[Image: source: ]", + "[Image: source: a] and also [b]", + "[Image: sourced elsewhere]", + "[Image: original 10x10, displayed at big]", + ] { + assert!(!super::is_synthetic_user_text(steer), "{steer}"); + } + } + + /// A tool that returns an image puts the pixels on the result. The + /// following note about the displayed size is bookkeeping, not a steer, + /// on the main feed and on a subagent feed. + #[test] + fn image_tool_results_keep_bytes_and_the_scale_note_is_not_a_steer() { + const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + let scale = "[Image: original 1884x2066, displayed at 1824x2000. Multiply coordinates by 1.03 to map to original image.]"; + let source = "[Image: source: /tmp/shots/1.png]"; + let combined = "[Image: source: /tmp/shots/1.png, original 10x10, displayed at 10x10.]"; + + let mut norm = Normalizer::new(); + let read = crate::claude::wire::parse_frame( + r#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_read","name":"Read","input":{"file_path":"/tmp/shots/1.png"}}]}}"#, + ) + .expect("parses"); + norm.normalize(read, false); + let result = crate::claude::wire::parse_frame(&format!( + r#"{{"type":"user","message":{{"content":[{{"type":"tool_result","tool_use_id":"toolu_read","content":[{{"type":"image","source":{{"type":"base64","media_type":"image/png","data":"{PNG}"}}}}]}}]}}}}"#, + PNG = PNG + )) + .expect("parses"); + let ev = norm.normalize(result, false); + let AgentEvent::ToolResult { + id, + image_payloads, + preview_paths, + .. + } = &ev[0] + else { + panic!("expected a tool result, got {ev:?}"); + }; + assert_eq!(id, "toolu_read"); + assert!(preview_paths.is_empty()); + assert_eq!(image_payloads.len(), 1); + assert_eq!(image_payloads[0].name, "1.png"); + assert_eq!(image_payloads[0].data_base64, PNG); + let journaled = serde_json::to_string(&ev[0]).unwrap(); + assert!( + !journaled.contains(PNG), + "image bytes must not be serialized" + ); + assert!(!journaled.contains("imagePayloads")); + + // The same bytes on a subagent feed stay on the tool result. + let mut norm = Normalizer::new(); + let read = crate::claude::wire::parse_frame( + r#"{"type":"assistant","parent_tool_use_id":"toolu_sub","message":{"content":[{"type":"tool_use","id":"toolu_child","name":"Read","input":{"file_path":"/tmp/shots/00.png"}}]}}"#, + ) + .expect("parses"); + norm.normalize(read, false); + let result = crate::claude::wire::parse_frame(&format!( + r#"{{"type":"user","parent_tool_use_id":"toolu_sub","message":{{"content":[{{"type":"tool_result","tool_use_id":"toolu_child","content":[{{"type":"image","source":{{"type":"base64","data":"{PNG}"}}}}]}}]}}}}"#, + PNG = PNG + )) + .expect("parses"); + let ev = norm.normalize(result, false); + assert!(matches!( + &ev[..], + [AgentEvent::Subagent { parent_tool_use_id, event }] + if parent_tool_use_id == "toolu_sub" + && matches!(event.as_ref(), AgentEvent::ToolResult { image_payloads, .. } if image_payloads.len() == 1 && image_payloads[0].name == "00.png") + )); + + for note in [scale, source, combined] { + let frame = format!( + r#"{{"type":"user","parent_tool_use_id":"toolu_sub","message":{{"content":[{{"type":"text","text":{text}}}]}}}}"#, + text = serde_json::to_string(note).unwrap() + ); + assert!( + !normalize_one(&frame) + .iter() + .any(|event| matches!(event, AgentEvent::Subagent { .. })), + "{note} leaked as a steer" + ); + let meta = format!( + r#"{{"type":"user","isMeta":true,"parent_tool_use_id":"toolu_sub","message":{{"content":{text}}}}}"#, + text = serde_json::to_string(note).unwrap() + ); + assert!( + normalize_one(&meta).is_empty(), + "string meta note leaked: {note}" + ); + } + // A meta frame cannot resurrect a settled chip, even with ordinary wording. + let meta_steer = r#"{"type":"user","isMeta":true,"parent_tool_use_id":"toolu_sub","message":{"content":[{"type":"text","text":"Keep going."}]}}"#; + assert!(normalize_one(meta_steer).is_empty()); + // A real steer on the same frame shape still arrives. + let real = r#"{"type":"user","parent_tool_use_id":"toolu_sub","message":{"content":[{"type":"text","text":"Keep going."}]}}"#; + assert!(normalize_one(real).iter().any(|event| matches!( + event, + AgentEvent::Subagent { event: inner, .. } + if matches!(inner.as_ref(), AgentEvent::UserMessage { text } if text == "Keep going.") + ))); + + // Fallback when the content block has no image and the frame has one result. + let fallback = crate::claude::wire::parse_frame(&format!( + r#"{{"type":"user","toolUseResult":{{"type":"image","file":{{"base64":"{PNG}","type":"image/png"}}}},"message":{{"content":[{{"type":"tool_result","tool_use_id":"toolu_fb","content":"ok"}}]}}}}"#, + PNG = PNG + )) + .expect("parses"); + let ev = Normalizer::new().normalize(fallback, false); + assert!(matches!( + &ev[..], + [AgentEvent::ToolResult { image_payloads, .. }] if image_payloads.len() == 1 && image_payloads[0].name == "image.png" + )); + // A result that already has the image does not take the fallback as a second copy. + let both = crate::claude::wire::parse_frame(&format!( + r#"{{"type":"user","toolUseResult":{{"type":"image","file":{{"base64":"{PNG}"}}}},"message":{{"content":[{{"type":"tool_result","tool_use_id":"toolu_both","content":[{{"type":"image","source":{{"type":"base64","data":"{PNG}"}}}}]}}]}}}}"#, + PNG = PNG + )) + .expect("parses"); + let ev = Normalizer::new().normalize(both, false); + assert!(matches!( + &ev[..], + [AgentEvent::ToolResult { image_payloads, .. }] if image_payloads.len() == 1 + )); + + // Not an image, or too large to be one: no payload. + let junk = crate::claude::wire::parse_frame( + r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_junk","content":[{"type":"image","source":{"type":"base64","data":"!!!!"}}]}]}}"#, + ) + .expect("parses"); + let ev = Normalizer::new().normalize(junk, false); + assert!(matches!( + &ev[..], + [AgentEvent::ToolResult { image_payloads, .. }] if image_payloads.is_empty() + )); + let mut huge = "A".repeat(zeron_proto::IMAGE_MAX_BYTES.div_ceil(3) * 4 + 1); + assert!(compact_base64(&huge).is_none()); + huge.clear(); + assert_eq!(compact_base64("aGVs\nbG8=").as_deref(), Some("aGVsbG8=")); + } + #[test] fn send_message_steers_rekey_onto_the_spawn_feed() { // Live 2.1.228: the steer NEVER echoes on the child feed; the only @@ -2227,13 +2618,7 @@ mod tests { session_id: None, }, ), - AgentEvent::ToolResult { - id: TYPED_CHIP.into(), - is_error: status == DoneStatus::Errored, - output: None, - diff: None, - exit_code: None, - }, + empty_tool_result(TYPED_CHIP, status == DoneStatus::Errored), ] } diff --git a/crates/harness/src/claude/wire.rs b/crates/harness/src/claude/wire.rs index 8b644a808..c6f7e398f 100644 --- a/crates/harness/src/claude/wire.rs +++ b/crates/harness/src/claude/wire.rs @@ -173,6 +173,16 @@ pub(crate) struct MessageFrame { /// Terse assistant-level error code (`rate_limit`, `billing_error`, …). #[serde(default)] pub error: Option, + /// Bookkeeping frame, not a person typing. Image scale notes ride this. + /// (`isMeta` in a saved transcript; the live stream spells its fields in + /// snake case.) + #[serde(default, rename = "isMeta", alias = "is_meta")] + pub is_meta: bool, + /// Structured tool outcome. An image result repeats its bytes here when + /// the content blocks do not. (`toolUseResult` in a saved transcript, + /// `tool_use_result` on the live stream.) + #[serde(default, rename = "toolUseResult", alias = "tool_use_result")] + pub tool_use_result: Option, } #[derive(Debug, Default, Deserialize)] diff --git a/crates/harness/src/codex/catalog.rs b/crates/harness/src/codex/catalog.rs index c22443bf7..24278493b 100644 --- a/crates/harness/src/codex/catalog.rs +++ b/crates/harness/src/codex/catalog.rs @@ -121,6 +121,7 @@ fn model( default: false, id: id.into(), label: label.into(), + provider: None, description: (!description.is_empty()).then(|| description.into()), reasoning_levels: ladder.to_vec(), options, diff --git a/crates/harness/src/codex/mod.rs b/crates/harness/src/codex/mod.rs index b35f96030..f92c9c62d 100644 --- a/crates/harness/src/codex/mod.rs +++ b/crates/harness/src/codex/mod.rs @@ -639,6 +639,7 @@ fn parse_model_list_page(result: &Value) -> (Vec<(Model, bool)>, Option) default: false, id: id.to_owned(), label, + provider: None, description, reasoning_levels, options, diff --git a/crates/harness/src/codex/normalize.rs b/crates/harness/src/codex/normalize.rs index 63fc8c375..72bd426e2 100644 --- a/crates/harness/src/codex/normalize.rs +++ b/crates/harness/src/codex/normalize.rs @@ -329,6 +329,8 @@ fn tool_lifecycle(phase: Phase, id: String, call: ToolCall, is_error: bool) -> V is_error, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ], @@ -459,6 +461,8 @@ pub(crate) fn map_item(phase: Phase, item: &Value) -> Vec { is_error: error.is_some(), output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ]; @@ -503,6 +507,8 @@ pub(crate) fn map_item(phase: Phase, item: &Value) -> Vec { is_error: status == "failed" || exit_code.is_some_and(|code| code != 0), output, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code, }] } @@ -559,6 +565,8 @@ pub(crate) fn map_item(phase: Phase, item: &Value) -> Vec { is_error: status == "failed", output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }], }, @@ -1038,6 +1046,8 @@ mod tests { }, }, AgentEvent::ToolResult { + image_payloads: Vec::new(), + preview_paths: Vec::new(), id: "m1".into(), is_error: false, output: Some("secret file contents\n".repeat(10)), @@ -1086,6 +1096,8 @@ mod tests { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: Some(2), }] ); @@ -1128,6 +1140,8 @@ mod tests { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] @@ -1173,6 +1187,8 @@ mod tests { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] @@ -1208,6 +1224,8 @@ mod tests { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] diff --git a/crates/harness/src/cursor/mod.rs b/crates/harness/src/cursor/mod.rs index 75f6ffccc..b4957b3c0 100644 --- a/crates/harness/src/cursor/mod.rs +++ b/crates/harness/src/cursor/mod.rs @@ -605,6 +605,7 @@ fn map_model_items(items: &Value) -> Vec { default: false, id, label, + provider: None, description: str_of(item, "description"), reasoning_levels: Vec::new(), options, @@ -1105,6 +1106,8 @@ fn map_shim_frame(frame: &Value, interrupted: bool) -> Vec { is_error, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }), ]; diff --git a/crates/harness/src/mock.rs b/crates/harness/src/mock.rs index 2633e8596..2539b9f3a 100644 --- a/crates/harness/src/mock.rs +++ b/crates/harness/src/mock.rs @@ -106,6 +106,8 @@ fn fanout_settle(i: usize) -> Vec { is_error: failed, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, fanout_tag( @@ -205,6 +207,7 @@ impl Harness for MockHarness { default: false, id: "mock-1".into(), label: "Mock 1".into(), + provider: None, description: None, reasoning_levels: vec![ReasoningLevel::Medium], options: vec![], @@ -215,6 +218,7 @@ impl Harness for MockHarness { default: false, id: "mock-fable-5".into(), label: "Fable 5".into(), + provider: None, description: None, reasoning_levels: vec![ ReasoningLevel::Low, @@ -335,6 +339,8 @@ impl Harness for MockHarness { is_error: false, output: Some("test result: ok. 128 passed; 0 failed".into()), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); send("All 128 tests pass."); @@ -567,6 +573,8 @@ impl Harness for MockHarness { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] @@ -606,6 +614,8 @@ impl Harness for MockHarness { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }; let done = AgentEvent::Done { @@ -772,6 +782,8 @@ impl Harness for MockHarness { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] @@ -829,6 +841,8 @@ impl Harness for MockHarness { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); events.push(AgentEvent::TextDelta { @@ -1007,6 +1021,8 @@ fn background_run( }, }); let _ = tx.send(AgentEvent::ToolResult { + image_payloads: Vec::new(), + preview_paths: Vec::new(), id: format!("{id}-call"), is_error: false, output: Some(format!("Command running in background with ID: {id}")), @@ -1224,6 +1240,8 @@ fn long_tool_run( pid.unwrap_or(0) )), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); turn.set_background_processes(vec![zeron_proto::BackgroundTask { @@ -1285,6 +1303,8 @@ fn long_tool_run( String::new() }), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: (!stopped).then_some(0), }); if stopped { diff --git a/crates/harness/src/muse/catalog.rs b/crates/harness/src/muse/catalog.rs index af0e452ac..37e776436 100644 --- a/crates/harness/src/muse/catalog.rs +++ b/crates/harness/src/muse/catalog.rs @@ -65,6 +65,7 @@ pub(super) fn models(result: &Value) -> Vec { default: false, id: id.into(), label, + provider: None, description: row["description"] .as_str() .filter(|d| !d.trim().is_empty()) diff --git a/crates/harness/src/muse/mod.rs b/crates/harness/src/muse/mod.rs index 2a27db816..5859c173f 100644 --- a/crates/harness/src/muse/mod.rs +++ b/crates/harness/src/muse/mod.rs @@ -270,6 +270,7 @@ impl Harness for MuseHarness { default: false, id: "muse-spark-1.2".into(), label: "Muse Spark 1.2".into(), + provider: None, description: Some("Muse Code's default coding model".into()), reasoning_levels: vec![ ReasoningLevel::Low, diff --git a/crates/harness/src/muse/normalize.rs b/crates/harness/src/muse/normalize.rs index 4f98e5ab2..ce85cf08d 100644 --- a/crates/harness/src/muse/normalize.rs +++ b/crates/harness/src/muse/normalize.rs @@ -159,6 +159,8 @@ impl Normalizer { || item["exitCode"].as_i64().is_some_and(|c| c != 0), output, diff, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); } @@ -202,6 +204,8 @@ impl Normalizer { is_error: status != "completed", output, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); } @@ -235,6 +239,8 @@ impl Normalizer { .or_else(|| item["failureReason"].as_str()) .map(|text| cap(text, 16384)), diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); } diff --git a/crates/harness/src/opencode/mod.rs b/crates/harness/src/opencode/mod.rs index dc965d664..716c62f9c 100644 --- a/crates/harness/src/opencode/mod.rs +++ b/crates/harness/src/opencode/mod.rs @@ -81,7 +81,7 @@ use serde_json::{Value, json}; use tokio::sync::mpsc; use zeron_proto::{ - AccessMode, AgentEvent, DoneStatus, HarnessId, Model, ModelOption, ModelOptionChoice, + AccessMode, AgentEvent, DoneStatus, HarnessId, Model, ModelOption, ModelOptionChoice, ModelProvider, ReasoningLevel, RunRequest, SlashCommand, SteeringMode, TodoItem, TodoStatus, ToolCall, UserInputAnswer, UserInputQuestion, }; @@ -1662,6 +1662,10 @@ fn models_from_providers(providers: &ProviderCatalog) -> Vec { default: false, id: format!("{provider_id}/{model_id}"), label, + provider: Some(ModelProvider { + id: provider_id.to_owned(), + name: provider_name.to_owned(), + }), description: Some(provider_name.to_owned()), reasoning_levels: levels, options: Vec::new(), @@ -4551,6 +4555,8 @@ fn part_snapshot_events( is_error: status == "error", output, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); } diff --git a/crates/harness/src/opencode/tests.rs b/crates/harness/src/opencode/tests.rs index 12bfbe7ff..95f3629d5 100644 --- a/crates/harness/src/opencode/tests.rs +++ b/crates/harness/src/opencode/tests.rs @@ -1073,6 +1073,14 @@ fn models_map_provider_catalog_with_variant_ladders() { .iter() .find(|m| m.id == "anthropic/claude-opus-5") .expect("opus"); + // Its provider rides along typed, so the picker can tell namesakes apart. + assert_eq!( + opus.provider, + Some(zeron_proto::ModelProvider { + id: "anthropic".into(), + name: "Anthropic".into(), + }) + ); assert_eq!(opus.label, "Claude Opus 5"); assert_eq!(opus.description.as_deref(), Some("Anthropic")); assert_eq!( diff --git a/crates/harness/src/pi/catalog.rs b/crates/harness/src/pi/catalog.rs index b7954c887..4549fe915 100644 --- a/crates/harness/src/pi/catalog.rs +++ b/crates/harness/src/pi/catalog.rs @@ -1,7 +1,9 @@ use super::{Process, normalize::string}; use crate::HarnessError; use serde_json::{Value, json}; -use zeron_proto::{Model, ModelOption, ModelOptionChoice, ReasoningLevel, SlashCommand}; +use zeron_proto::{ + Model, ModelOption, ModelOptionChoice, ModelProvider, ReasoningLevel, SlashCommand, +}; pub(super) fn levels(data: &Value) -> Vec { data["levels"] @@ -36,6 +38,10 @@ pub(super) async fn models(process: &mut Process) -> Result, HarnessE default: false, id: format!("{provider}/{id}"), label: model["name"].as_str().unwrap_or(id).into(), + provider: (!provider.is_empty()).then(|| ModelProvider { + id: provider.into(), + name: provider_name(provider), + }), description: Some(provider.into()), reasoning_levels: levels(&supported), options: thinking_option(&supported), @@ -44,6 +50,50 @@ pub(super) async fn models(process: &mut Process) -> Result, HarnessE } Ok(result) } +/// A Pi provider's name as people say it. Pi reports only its id +/// (`openai-codex`); a provider not listed here reads as its id in words +/// (`foo-bar` → `Foo Bar`). +pub(crate) fn provider_name(id: &str) -> String { + let known = match id { + "openai-codex" => "Codex", + "opencode" => "OpenCode", + "opencode-go" => "OpenCode Go", + "anthropic" => "Anthropic", + "openai" => "OpenAI", + "azure-openai-responses" => "Azure OpenAI", + "github-copilot" => "Copilot", + "google" => "Google", + "google-gemini-cli" => "Gemini CLI", + "google-antigravity" => "Antigravity", + "google-vertex" => "Vertex AI", + "amazon-bedrock" => "Bedrock", + "openrouter" => "OpenRouter", + "vercel-ai-gateway" => "Vercel AI Gateway", + "xai" => "xAI", + "groq" => "Groq", + "cerebras" => "Cerebras", + "mistral" => "Mistral", + "minimax" => "MiniMax", + "minimax-cn" => "MiniMax China", + "huggingface" => "Hugging Face", + "zai" => "Z.ai", + "kimi-coding" => "Kimi", + _ => "", + }; + if !known.is_empty() { + return known.into(); + } + id.split(['-', '_']) + .filter(|w| !w.is_empty()) + .map(|w| { + let mut c = w.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect::()) + .unwrap_or_default() + }) + .collect::>() + .join(" ") +} fn thinking_option(data: &Value) -> Vec { if !data["levels"] .as_array() @@ -124,3 +174,18 @@ pub(super) fn builtin(text: &str, auto: bool) -> Option { _ => return None, }) } + +#[cfg(test)] +mod tests { + use super::provider_name; + + #[test] + fn provider_names_read_as_people_say_them() { + assert_eq!(provider_name("openai-codex"), "Codex"); + assert_eq!(provider_name("opencode"), "OpenCode"); + assert_eq!(provider_name("github-copilot"), "Copilot"); + // Unknown: the id in words, never empty. + assert_eq!(provider_name("my-local_llm"), "My Local Llm"); + assert_eq!(provider_name("ollama"), "Ollama"); + } +} diff --git a/crates/harness/src/pi/mod.rs b/crates/harness/src/pi/mod.rs index eb25fb038..a22fb610b 100644 --- a/crates/harness/src/pi/mod.rs +++ b/crates/harness/src/pi/mod.rs @@ -1,5 +1,8 @@ //! Native Pi JSONL RPC driver. See PROTOCOL.md for the legacy ACK barrier. mod catalog; +/// A provider's name as people say it (`openai-codex` → Codex), for every +/// agent that reaches models through several providers. +pub(crate) use catalog::provider_name; mod mcp; mod normalize; mod rpc; @@ -362,6 +365,7 @@ impl Harness for PiHarness { default: false, id: "default".into(), label: "Pi default".into(), + provider: None, description: Some("Model configured in Pi".into()), reasoning_levels: vec![], options: vec![], diff --git a/crates/harness/src/pi/normalize.rs b/crates/harness/src/pi/normalize.rs index b82976f88..c75dacc00 100644 --- a/crates/harness/src/pi/normalize.rs +++ b/crates/harness/src/pi/normalize.rs @@ -144,6 +144,8 @@ impl Normalizer { is_error: frame["isError"].as_bool().unwrap_or(false), output: output.map(|s| cap(&s, 16384)), diff, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }); } diff --git a/crates/harness/tests/claude.rs b/crates/harness/tests/claude.rs index d2e54ae9d..4dd6d978b 100644 --- a/crates/harness/tests/claude.rs +++ b/crates/harness/tests/claude.rs @@ -170,6 +170,8 @@ async fn happy_path_normalizes_events_and_tags_subagents() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: Some(0), }), })); @@ -199,6 +201,8 @@ async fn happy_path_normalizes_events_and_tags_subagents() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: Some(0), })); assert!(events.contains(&AgentEvent::ToolResult { @@ -206,6 +210,8 @@ async fn happy_path_normalizes_events_and_tags_subagents() { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, })); diff --git a/crates/harness/tests/codex.rs b/crates/harness/tests/codex.rs index 5ef5c3be5..d110934ee 100644 --- a/crates/harness/tests/codex.rs +++ b/crates/harness/tests/codex.rs @@ -240,6 +240,8 @@ async fn happy_path_maps_deltas_items_usage_and_done() { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: Some(1), })); @@ -263,6 +265,8 @@ async fn happy_path_maps_deltas_items_usage_and_done() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, })); @@ -280,6 +284,8 @@ async fn happy_path_maps_deltas_items_usage_and_done() { is_error: true, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, })); @@ -295,6 +301,8 @@ async fn happy_path_maps_deltas_items_usage_and_done() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, })); @@ -313,6 +321,8 @@ async fn happy_path_maps_deltas_items_usage_and_done() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, })); @@ -1499,6 +1509,8 @@ async fn child_thread_routing_tags_and_never_settles_parent() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: Some(0), }), })); @@ -1915,6 +1927,8 @@ async fn view_image_reads_as_a_file_read() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, }, ] diff --git a/crates/harness/tests/cursor.rs b/crates/harness/tests/cursor.rs index 6c4b4c4c1..d56ac8e99 100644 --- a/crates/harness/tests/cursor.rs +++ b/crates/harness/tests/cursor.rs @@ -306,6 +306,8 @@ async fn happy_path_maps_shim_frames_and_tags_subagents() { is_error: false, output: None, diff: None, + preview_paths: Vec::new(), + image_payloads: Vec::new(), exit_code: None, })); diff --git a/crates/mcp/src/tools/plugins.rs b/crates/mcp/src/tools/plugins.rs index 8bdc7d7fd..d8d585bd6 100644 --- a/crates/mcp/src/tools/plugins.rs +++ b/crates/mcp/src/tools/plugins.rs @@ -164,7 +164,7 @@ pub(super) fn catalog() -> Vec { vec![ ToolDef { name: CREATE_PLUGIN, - description: "Create a Zeron plugin on this device: a folder with a manifest (zeron-plugin.json), init.luau to edit, and zeron.luau, the SDK. Zeron signs it as yours and loads it, and re-signs and reloads it as you save; the person allows once, in Zeron, any permissions it asks for. `id` is lowercase letters, digits and dashes (2-40). `permissions` are what the plugin may do (ui.add, ui.change, ui.replace, profile.read, sessions.read, messages.read, account.email, files.read, panel.tabs, pages.add, github, github.write, navigate, compose, network, clipboard, files, web, windows, tools, devices, native, commands: with a manifest `commands` list of programs it runs, as you). The reply links the authoring guide (`guide`): read it before writing.", + description: "Create a Zeron plugin on this device: a folder with a manifest (zeron-plugin.json), init.luau to edit, and zeron.luau, the SDK. Zeron signs it as yours and loads it, and re-signs and reloads it as you save; the person allows once, in Zeron, any permissions it asks for. `id` is lowercase letters, digits and dashes (2-40). `permissions` are what the plugin may do (ui.add, ui.change, ui.replace, profile.read, sessions.read, messages.read, account.email, files.read, panel.tabs, pages.add, github, github.write, navigate, compose, draft, network, clipboard, files, web, windows, tools, devices, native, commands: with a manifest `commands` list of programs it runs, as you). The reply links the authoring guide (`guide`): read it before writing.", input_schema: json!({ "type": "object", "properties": { diff --git a/crates/mcp/src/transcript.rs b/crates/mcp/src/transcript.rs index 015bf5126..5c24ac3ad 100644 --- a/crates/mcp/src/transcript.rs +++ b/crates/mcp/src/transcript.rs @@ -284,6 +284,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/mobile/src/layout/tests.rs b/crates/mobile/src/layout/tests.rs index 537b2da1a..5ee450734 100644 --- a/crates/mobile/src/layout/tests.rs +++ b/crates/mobile/src/layout/tests.rs @@ -161,6 +161,7 @@ fn messages_the_agent_sent_show_as_one_line_naming_the_recipient() { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -683,6 +684,7 @@ fn running_subagent_shows_a_spinner_after_its_spawn_resolves() { subagent_ref: Some("sub-1".into()), subagent_status: Some(status), subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/proto/src/agent.rs b/crates/proto/src/agent.rs index 3e1e53704..2ac0ee609 100644 --- a/crates/proto/src/agent.rs +++ b/crates/proto/src/agent.rs @@ -505,6 +505,11 @@ pub struct Model { /// mirroring the Electron app's `ModelInfo.description`. #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, + /// Where the model is served from, for a harness that reaches models + /// through several providers (Pi signed in to both Codex and OpenCode + /// can list the same model twice). `None` for a harness with one source. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, #[serde(default)] pub reasoning_levels: Vec, #[serde(default)] @@ -517,6 +522,15 @@ pub struct Model { pub default: bool, } +/// A model's provider: its stable id as the harness names it (`openai-codex`, +/// `opencode`) and its name as people say it (`Codex`, `OpenCode`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelProvider { + pub id: String, + pub name: String, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelOption { @@ -985,6 +999,14 @@ pub struct SlashCommand { pub input_hint: Option, } +/// One image embedded in a tool result, held only until the engine stores +/// a copy under the profile uploads directory. Never journaled. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ToolResultImage { + pub name: String, + pub data_base64: String, +} + /// A file modification carried inline on a tool result (ACP /// `ToolCallContent::Diff`). `old_text: None` means a new file. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -1091,6 +1113,13 @@ pub enum AgentEvent { /// Inline file diff for edit-shaped tools (ACP `Diff` content). #[serde(default, skip_serializing_if = "Option::is_none")] diff: Option, + /// Uploads paths of images that were embedded in this result. The + /// engine fills this before journaling; adapters leave it empty. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + preview_paths: Vec, + /// In-memory image bytes for the engine to store. Never serialized. + #[serde(skip)] + image_payloads: Vec, /// A command's exit status, when the harness reported one (Claude /// Code's Bash, Codex's command execution). Absent for other tools, /// a command still running in the background, or one that never ran. diff --git a/crates/proto/src/providers.rs b/crates/proto/src/providers.rs index a0c817e74..08e175617 100644 --- a/crates/proto/src/providers.rs +++ b/crates/proto/src/providers.rs @@ -81,6 +81,16 @@ pub struct LoginOption { } /// The sign-ins zeron offers for `harness`, in button order. Pure. +/// +/// For an agent that keeps a login per model provider, these are the +/// providers its own auth supports AND zeron can sign in to unattended +/// (engine `agent_accounts::oauth` / `stores` say how): Pi's Claude is the +/// same Claude Pro/Max sign-in Pi's own `/login` runs. Left out: OpenCode's +/// Claude (OpenCode has no Anthropic OAuth — removed upstream, absent from +/// 2.x); Pi's xAI, Kimi, Meta and OpenRouter logins (zeron can't tell their +/// accounts apart yet); and Hermes' Claude, Qwen, MiniMax and OpenRouter +/// (not unattended device codes: a pasted code, another CLI's login, a +/// minted API key, unverified). API keys are [`api_key_options`]. pub fn login_options(harness: HarnessId) -> Vec { let option = |provider, label| LoginOption { provider: Some(provider), @@ -91,10 +101,15 @@ pub fn login_options(harness: HarnessId) -> Vec { option("openai", "ChatGPT"), option("github-copilot", "GitHub Copilot"), ], - HarnessId::Pi => vec![option("openai-codex", "ChatGPT")], + HarnessId::Pi => vec![ + option("openai-codex", "ChatGPT"), + option("anthropic", "Claude"), + option("github-copilot", "GitHub Copilot"), + ], HarnessId::Hermes => vec![ option("openai-codex", "ChatGPT"), option("nous", "Nous Portal"), + option("xai-oauth", "xAI"), ], _ => vec![LoginOption { provider: None, @@ -103,6 +118,143 @@ pub fn login_options(harness: HarnessId) -> Vec { } } +/// A provider an agent reaches with an API key Zeron can add for it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ApiKeyOption { + /// The agent's own id for the provider: its store key (Pi's and + /// OpenCode's `auth.json`) or Hermes' pool / `hermes auth add` name. + pub provider: &'static str, + /// Who issues the key ("OpenRouter", "OpenAI"). + pub label: &'static str, +} + +/// The providers whose API key Zeron adds for `harness`, as the agent's own +/// CLI would store it (engine `agent_accounts::api_keys`), each checked +/// with the provider before it's saved. Pure. +pub fn api_key_options(harness: HarnessId) -> Vec { + let key = |provider, label| ApiKeyOption { provider, label }; + match harness { + HarnessId::Pi | HarnessId::Opencode => vec![ + key("anthropic", "Anthropic"), + key("openai", "OpenAI"), + key("openrouter", "OpenRouter"), + key("google", "Google Gemini"), + key("xai", "xAI"), + key("deepseek", "DeepSeek"), + ], + HarnessId::Hermes => vec![ + key("anthropic", "Anthropic"), + key("openai-api", "OpenAI"), + key("openrouter", "OpenRouter"), + key("gemini", "Google Gemini"), + key("xai", "xAI"), + key("deepseek", "DeepSeek"), + ], + _ => Vec::new(), + } +} + +/// The API key Zeron adds for `provider` of `harness`, if it adds one. +pub fn api_key_option(harness: HarnessId, provider: &str) -> Option { + api_key_options(harness) + .into_iter() + .find(|option| option.provider == provider) +} + +/// What adding one says: "Add OpenRouter API key" (or, inside the +/// provider's own group, "Add API key"). Pure. +pub fn add_key_label(option: ApiKeyOption, in_group: bool) -> String { + if in_group { + "Add API key".to_string() + } else { + format!("Add {} API key", option.label) + } +} + +/// Whether `harness` keeps one login PER model provider (OpenCode, Pi, +/// Hermes): its accounts show grouped by provider, each group with its own +/// account in use, and a run uses the account of its model's provider. +/// Every other agent has one group: its own. Pure. +pub fn groups_by_provider(harness: HarnessId) -> bool { + matches!( + harness, + HarnessId::Opencode | HarnessId::Pi | HarnessId::Hermes + ) +} + +/// The sign-in zeron offers for `provider` of `harness`, if it offers one. +pub fn login_option(harness: HarnessId, provider: &str) -> Option { + login_options(harness) + .into_iter() + .find(|option| option.provider == Some(provider)) +} + +/// What a provider group of a per-provider agent is called (its heading in +/// Settings, the model picker's " account"): the provider its models +/// come from — "ChatGPT" for the ChatGPT-only `openai-codex`, "OpenAI" for +/// `openai` (ChatGPT sign-ins and API keys alike), "Anthropic" for +/// `anthropic` (Claude sign-ins and API keys). An id zeron doesn't know +/// reads as its words. Pure. +pub fn account_group_label(harness: HarnessId, provider: &str) -> String { + let known = match provider { + "openai-codex" => "ChatGPT", + "openai" | "openai-api" => "OpenAI", + "anthropic" => "Anthropic", + "github-copilot" | "copilot" => "GitHub Copilot", + "nous" => "Nous Portal", + "xai" | "xai-oauth" => "xAI", + "openrouter" => "OpenRouter", + "google" | "gemini" => "Google Gemini", + "google-gemini-cli" => "Gemini", + "groq" => "Groq", + "deepseek" => "DeepSeek", + "mistral" => "Mistral", + "kimi-coding" => "Kimi", + "qwen-oauth" => "Qwen", + "minimax-oauth" => "MiniMax", + "meta" => "Meta", + _ => "", + }; + if !known.is_empty() { + return known.to_string(); + } + if let Some(option) = login_option(harness, provider) { + return option.label.to_string(); + } + provider + .split(['-', '_']) + .filter(|w| !w.is_empty()) + .map(|w| { + let mut c = w.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect::()) + .unwrap_or_default() + }) + .collect::>() + .join(" ") +} + +/// How to add another account to a provider group zeron can neither sign +/// in to nor add a key for (a Pi login zeron can't run, a Hermes provider +/// without a device code or key): the agent's own way, said under the +/// group. `None` where zeron adds one itself. Pure. +pub fn account_group_hint(harness: HarnessId, provider: &str) -> Option { + if login_option(harness, provider).is_some() || api_key_option(harness, provider).is_some() { + return None; + } + let label = account_group_label(harness, provider); + match harness { + HarnessId::Pi => Some(format!("To add another {label} account, run /login in Pi.")), + HarnessId::Opencode => Some(format!( + "To add another {label} account, run `opencode auth login`." + )), + HarnessId::Hermes => Some(format!( + "To add another {label} account, run `hermes auth add {provider}`." + )), + _ => None, + } +} + /// The list's last row: connect the first account, or add another. Pure. pub fn add_account_label(harness: HarnessId, empty: bool) -> String { if empty { @@ -121,3 +273,97 @@ pub fn add_option_label(harness: HarnessId, option: LoginOption, empty: bool) -> Some(_) => format!("Add {} account", option.label), } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn per_provider_agents_group_and_offer_a_sign_in_per_provider() { + for harness in [HarnessId::Opencode, HarnessId::Pi, HarnessId::Hermes] { + assert!(groups_by_provider(harness), "{harness:?}"); + assert!( + login_options(harness).iter().all(|o| o.provider.is_some()), + "{harness:?} names each provider" + ); + assert!(!api_key_options(harness).is_empty(), "{harness:?}"); + } + for harness in [HarnessId::ClaudeCode, HarnessId::Codex, HarnessId::Grok] { + assert!(!groups_by_provider(harness), "{harness:?}"); + assert!(api_key_options(harness).is_empty(), "{harness:?}"); + } + let pi: Vec<_> = login_options(HarnessId::Pi) + .iter() + .map(|o| (o.provider.unwrap(), o.label)) + .collect(); + assert_eq!( + pi, + [ + ("openai-codex", "ChatGPT"), + ("anthropic", "Claude"), + ("github-copilot", "GitHub Copilot") + ] + ); + let hermes: Vec<_> = login_options(HarnessId::Hermes) + .iter() + .map(|o| o.provider.unwrap()) + .collect(); + assert_eq!(hermes, ["openai-codex", "nous", "xai-oauth"]); + // OpenCode has no Claude sign-in of its own: none offered. + assert!(login_option(HarnessId::Opencode, "anthropic").is_none()); + let copilot = login_option(HarnessId::Pi, "github-copilot").unwrap(); + assert_eq!( + add_option_label(HarnessId::Pi, copilot, false), + "Add GitHub Copilot account" + ); + assert_eq!( + add_option_label(HarnessId::Pi, copilot, true), + "Connect GitHub Copilot" + ); + let openrouter = api_key_option(HarnessId::Hermes, "openrouter").unwrap(); + assert_eq!(add_key_label(openrouter, false), "Add OpenRouter API key"); + assert_eq!(add_key_label(openrouter, true), "Add API key"); + assert!(api_key_option(HarnessId::Hermes, "openai").is_none()); + assert!(api_key_option(HarnessId::Hermes, "openai-api").is_some()); + } + + #[test] + fn provider_groups_are_named_for_the_provider() { + assert_eq!( + account_group_label(HarnessId::Pi, "openai-codex"), + "ChatGPT" + ); + assert_eq!(account_group_label(HarnessId::Opencode, "openai"), "OpenAI"); + assert_eq!(account_group_label(HarnessId::Pi, "anthropic"), "Anthropic"); + assert_eq!( + account_group_label(HarnessId::Hermes, "github-copilot"), + "GitHub Copilot" + ); + assert_eq!(account_group_label(HarnessId::Hermes, "xai-oauth"), "xAI"); + assert_eq!( + account_group_label(HarnessId::Hermes, "gemini"), + "Google Gemini" + ); + assert_eq!( + account_group_label(HarnessId::Hermes, "my-local_llm"), + "My Local Llm" + ); + } + + #[test] + fn a_group_zeron_cant_add_to_says_the_agents_own_way() { + assert_eq!( + account_group_hint(HarnessId::Pi, "kimi-coding").as_deref(), + Some("To add another Kimi account, run /login in Pi.") + ); + assert_eq!( + account_group_hint(HarnessId::Hermes, "minimax-oauth").as_deref(), + Some("To add another MiniMax account, run `hermes auth add minimax-oauth`.") + ); + // Zeron adds these itself (a sign-in, a key): no hint. + assert!(account_group_hint(HarnessId::Pi, "anthropic").is_none()); + assert!(account_group_hint(HarnessId::Hermes, "openrouter").is_none()); + assert!(account_group_hint(HarnessId::Opencode, "github-copilot").is_none()); + assert!(account_group_hint(HarnessId::ClaudeCode, "anthropic").is_none()); + } +} diff --git a/crates/rpc/src/lib.rs b/crates/rpc/src/lib.rs index d36e7988c..132dd6e49 100644 --- a/crates/rpc/src/lib.rs +++ b/crates/rpc/src/lib.rs @@ -330,6 +330,18 @@ pub mod methods { pub const LIST_AGENT_ACCOUNTS: &str = "ListAgentAccounts"; pub const ACTIVATE_AGENT_ACCOUNT: &str = "ActivateAgentAccount"; pub const FORGET_AGENT_ACCOUNT: &str = "ForgetAgentAccount"; + /// `{harness, provider, key}`: an API key for one model provider of an + /// agent that keeps a login per provider (Pi, OpenCode, Hermes), checked + /// with the provider and stored as the agent's own CLI stores it. This + /// device's own IPC only ([`local_only`]): never forwarded to, or + /// accepted from, another device — the key goes nowhere but its agent's + /// store and its provider. Answers the snapshot (keys shown by their + /// last four characters). + pub const ADD_AGENT_API_KEY: &str = "AddAgentApiKey"; + /// `{harness, accountId, name}`: an API key's name (no secret: it + /// travels to the device that holds the key like any account action). + /// An empty name restores its default ("OpenRouter ···a1b2"). + pub const RENAME_AGENT_ACCOUNT: &str = "RenameAgentAccount"; pub const START_AGENT_LOGIN: &str = "StartAgentLogin"; /// `{loginId, requesterDeviceId, path}`: replay a sign-in's browser /// callback the requesting device caught on its own loopback (a phone @@ -680,6 +692,8 @@ pub fn local_only(method: &str) -> bool { method, methods::ACCESS_TOKEN | methods::STEP_UP + // An API key typed into this device's app: stored here alone. + | methods::ADD_AGENT_API_KEY | methods::DELETE_ACCOUNT | methods::REVIEW_TEMPLATE // Plugins: authoring, tools and the window's channel stay this diff --git a/crates/ui/src/pickers.rs b/crates/ui/src/pickers.rs index f682bd24e..e15b5c807 100644 --- a/crates/ui/src/pickers.rs +++ b/crates/ui/src/pickers.rs @@ -2820,6 +2820,7 @@ impl Pickers { default: false, id: id.into(), label, + provider: None, description: Some( "Selected in this chat; absent from the current model list".into(), ), @@ -8944,6 +8945,7 @@ mod tests { default: false, id: id.into(), label: label.into(), + provider: None, description: None, reasoning_levels: Vec::new(), options: Vec::new(), @@ -11138,6 +11140,7 @@ mod tests { default: false, id: "flagship".into(), label: "Flagship".into(), + provider: None, description: None, reasoning_levels: vec![], options: vec![], @@ -11146,6 +11149,7 @@ mod tests { default: false, id: "fast".into(), label: "Fast".into(), + provider: None, description: None, reasoning_levels: vec![], options: vec![], diff --git a/crates/ui/src/settings/accounts.rs b/crates/ui/src/settings/accounts.rs index 61c0e950a..7bb117913 100644 --- a/crates/ui/src/settings/accounts.rs +++ b/crates/ui/src/settings/accounts.rs @@ -2521,7 +2521,7 @@ mod tests { .iter() .map(|o| o.provider.unwrap()) .collect(); - assert_eq!(providers, ["openai-codex", "nous"]); + assert_eq!(providers, ["openai-codex", "nous", "xai-oauth"]); let flow = LoginFlow { provider: Some("openai-codex"), ..waiting(HarnessId::Pi, 1) diff --git a/crates/ui/src/shell/session_lanes.rs b/crates/ui/src/shell/session_lanes.rs index 4ccd65571..8a9708e8f 100644 --- a/crates/ui/src/shell/session_lanes.rs +++ b/crates/ui/src/shell/session_lanes.rs @@ -741,6 +741,7 @@ mod tests { subagent_ref: doc.map(str::to_owned), subagent_status: status, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/ui/src/sound.rs b/crates/ui/src/sound.rs index 39a7e2ad4..362ad0dd6 100644 --- a/crates/ui/src/sound.rs +++ b/crates/ui/src/sound.rs @@ -5,9 +5,11 @@ //! the start and end of a voice call; //! - macOS Appshots use a preloaded native player; other cues write to a //! temp file and use the system player on a -//! background thread: `afplay` (macOS), PowerShell `Media.SoundPlayer` -//! (Windows), first of `paplay`/`pw-play`/`aplay`/`ffplay`/`mpv` (Linux — -//! WAV, so even bare ALSA `aplay` decodes it); +//! background thread: the System Sound server (macOS, see +//! `macos_system_sound` for why not `afplay`), PowerShell +//! `Media.SoundPlayer` (Windows), first of +//! `paplay`/`pw-play`/`aplay`/`ffplay`/`mpv` (Linux — WAV, so even bare +//! ALSA `aplay` decodes it); //! - `ZERON_DISABLE_SOUND` env kill-switch + the `soundEnabled` ui-setting; //! - failures are logged and swallowed — a missing player must never bother //! the session flow. @@ -235,7 +237,97 @@ fn create_temp_file() -> std::io::Result<(std::fs::File, TempSoundFile)> { #[cfg(target_os = "macos")] fn run_player(path: &Path) -> Result<(), String> { - run_checked("afplay", &[], path) + macos_system_sound::play(path) +} + +/// Chimes play in the System Sound server, not in a process of ours. +/// +/// Whoever plays audio holds a CoreAudio assertion for as long as it sounds. +/// While a game holds the foreground macOS keeps every other app's process +/// coalition in the background, and the assertion of an `afplay` child lifts +/// the whole coalition out and drops it back when the sound ends. +/// AVAudioPlayer and NSSound take the same assertion, in the app. On macOS +/// 27.2 such a change can deadlock in the kernel against a process of the +/// same coalition that is in `exec`, and agents exec all the time: the window +/// server hangs behind it and the machine needs a reboot. The sound server +/// holds the assertion itself, so a chime leaves this app's processes alone. +#[cfg(target_os = "macos")] +mod macos_system_sound { + use core_foundation::base::TCFType; + use core_foundation::url::{CFURL, CFURLRef}; + use std::ffi::c_void; + use std::path::Path; + use std::sync::mpsc; + use std::time::Duration; + + type SystemSoundId = u32; + + const PROPERTY_IS_UI_SOUND: u32 = u32::from_be_bytes(*b"isui"); + + #[link(name = "AudioToolbox", kind = "framework")] + unsafe extern "C" { + fn AudioServicesCreateSystemSoundID(url: CFURLRef, id: *mut SystemSoundId) -> i32; + fn AudioServicesDisposeSystemSoundID(id: SystemSoundId) -> i32; + fn AudioServicesSetProperty( + property: u32, + specifier_size: u32, + specifier: *const c_void, + data_size: u32, + data: *const c_void, + ) -> i32; + fn AudioServicesPlaySystemSoundWithCompletion( + id: SystemSoundId, + completion: &block2::Block, + ); + } + + pub(super) struct SystemSound(SystemSoundId); + + impl Drop for SystemSound { + fn drop(&mut self) { + unsafe { + AudioServicesDisposeSystemSoundID(self.0); + } + } + } + + pub(super) fn register(path: &Path) -> Result { + let url = CFURL::from_path(path, false) + .ok_or_else(|| format!("no file URL for {}", path.display()))?; + let mut id: SystemSoundId = 0; + let status = unsafe { AudioServicesCreateSystemSoundID(url.as_concrete_TypeRef(), &mut id) }; + if status != 0 { + return Err(format!("system sound server refused the chime ({status})")); + } + let sound = SystemSound(id); + // System sounds default to interface feedback, silent when the user + // turns interface sound effects off. A chime has its own setting. + let ui_sound: u32 = 0; + unsafe { + AudioServicesSetProperty( + PROPERTY_IS_UI_SOUND, + size_of::() as u32, + (&raw const sound.0).cast(), + size_of::() as u32, + (&raw const ui_sound).cast(), + ); + } + Ok(sound) + } + + pub(super) fn play(path: &Path) -> Result<(), String> { + let sound = register(path)?; + let (finished, wait) = mpsc::channel(); + let completion = block2::RcBlock::new(move || { + let _ = finished.send(()); + }); + unsafe { AudioServicesPlaySystemSoundWithCompletion(sound.0, &completion) }; + // The caller deletes the file when this returns, so wait the chime + // out. Bounded like the other players: a wedged sound server must not + // accumulate threads. + wait.recv_timeout(Duration::from_secs(10)) + .map_err(|_| "system sound timed out".to_string()) + } } #[cfg(windows)] @@ -285,6 +377,7 @@ fn run_player(path: &Path) -> Result<(), String> { Err(format!("no audio player available: {}", errors.join("; "))) } +#[cfg(not(target_os = "macos"))] fn run_checked(program: &str, args: &[&str], path: &Path) -> Result<(), String> { // Bounded wait: a wedged audio daemon must not accumulate zombie threads. let mut child = std::process::Command::new(program) @@ -395,6 +488,26 @@ mod tests { } } + // Registering is everything short of sounding: the server opens and + // accepts the file a chime is written to. + #[cfg(target_os = "macos")] + #[test] + fn embedded_chimes_register_with_the_system_sound_server_without_playback() { + for data in [ + SOUND_DONE, + SOUND_REQUEST, + SOUND_ATTENTION, + SOUND_VOICE_START, + SOUND_VOICE_END, + SOUND_APPSHOT, + ] { + let (mut file, tmp) = create_temp_file().expect("reserve temp file"); + file.write_all(data).expect("write chime"); + drop(file); + macos_system_sound::register(&tmp.path).expect("chime should register"); + } + } + #[test] fn attention_gate_coalesces_session_and_connectivity_watch_callbacks() { let t0 = Instant::now(); diff --git a/crates/ui/src/state.rs b/crates/ui/src/state.rs index edbb18fc8..428dbb1e2 100644 --- a/crates/ui/src/state.rs +++ b/crates/ui/src/state.rs @@ -2211,6 +2211,7 @@ impl AppState { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -5984,7 +5985,7 @@ mod tests { assert_eq!(state.transcript[0].id, "new-authoritative-row"); // An authoritative empty reset must still be honored. state - .apply_transcript_frame(TranscriptFrame::reset(&[])) + .apply_transcript_frame(TranscriptFrame::reset::(&[])) .unwrap(); assert!(state.transcript.is_empty()); }); diff --git a/crates/ui/src/todo_panel.rs b/crates/ui/src/todo_panel.rs index 772e6cef6..edf5edd9b 100644 --- a/crates/ui/src/todo_panel.rs +++ b/crates/ui/src/todo_panel.rs @@ -732,6 +732,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -991,6 +992,7 @@ mod composer_tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/ui/src/transcript.rs b/crates/ui/src/transcript.rs index 8c59dc6b1..8dd2f25ec 100644 --- a/crates/ui/src/transcript.rs +++ b/crates/ui/src/transcript.rs @@ -12344,7 +12344,7 @@ mod tests { state .receive_transcript_update( zeron_doc::TranscriptUpdate { - frame: zeron_doc::TranscriptFrame::reset(&[]), + frame: zeron_doc::TranscriptFrame::reset::(&[]), context_usage: None, replay_baseline: Some(Default::default()), }, @@ -13353,6 +13353,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -14551,6 +14552,7 @@ mod tests { subagent_ref: None, subagent_status: None, subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, @@ -14676,6 +14678,7 @@ mod tests { subagent_ref: Some(format!("chat--sub--{id}")), subagent_status: Some(SubagentStatus::Running), subagent_tail: None, + preview_paths: Vec::new(), exit_code: None, output_truncated: false, output_lines: None, diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index d698dbe58..067653bbd 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -1248,10 +1248,11 @@ fn on_cloud() -> bool { on_cloud_platform(std::env::var("ZERON_DEVICE_PLATFORM").ok().as_deref()) } -/// Release files a Cloud machine never runs: the desktop app's background -/// engine (78 MB). A Cloud machine runs `zeron headless`, which links the -/// engine, and its disk is copied back in on every wake. -pub const CLOUD_UNUSED_FILES: &[&str] = &["zeron-engine"]; +/// Release files a Cloud machine never runs: none. (`zeron-engine` was here +/// until 2026-11-15, when `zeron headless` linked the engine. Since 0.3.0 the +/// release's `zeron` is the zgx app, whose `zeron headless` runs the +/// `zeron-engine` beside it: a machine without it never came online.) +pub const CLOUD_UNUSED_FILES: &[&str] = &[]; /// Remove [`CLOUD_UNUSED_FILES`] from the version folder `dir`. pub fn strip_cloud_unused(dir: &Path) { @@ -3692,9 +3693,11 @@ mod tests { assert_eq!(folders(&app_root), ["0.2.10", "0.2.11", "0.2.12", "current"]); } + /// `zeron headless` runs the `zeron-engine` beside it: a Cloud machine + /// keeps it in every version (it once left it out, and never came online). #[cfg(unix)] #[test] - fn a_cloud_machine_keeps_no_desktop_engine() { + fn a_cloud_machine_keeps_the_engine_its_headless_runs() { let tmp = tempfile::tempdir().unwrap(); let app_root = tmp.path().join("app"); versions_installed(&app_root, &["0.2.10", "0.2.11"]); @@ -3708,7 +3711,7 @@ mod tests { strip_unused_from_versions(&app_root); for ver in ["0.2.10", "0.2.11"] { - assert!(!app_root.join(ver).join("zeron-engine").exists(), "{ver}"); + assert!(app_root.join(ver).join("zeron-engine").exists(), "{ver}"); assert!(app_root.join(ver).join("zeron").exists(), "{ver}"); } assert!(app_root.join("notes").join("zeron-engine").exists()); @@ -4169,11 +4172,11 @@ mod tests { assert!(staged.join("zeron").is_file()); } - /// The release carries the desktop's background engine; a Cloud machine - /// stages the release without it, anywhere else keeps it. + /// The release carries `zeron-engine`, which `zeron headless` runs: a + /// Cloud machine stages it as anywhere else does. #[cfg(unix)] #[tokio::test] - async fn a_cloud_machine_stages_a_release_without_the_desktop_engine() { + async fn a_cloud_machine_stages_a_release_with_its_engine() { let tmp = tempfile::tempdir().unwrap(); let pkg = tmp.path().join("pkg"); std::fs::create_dir_all(pkg.join("zeron-pkg")).unwrap(); @@ -4190,7 +4193,7 @@ mod tests { .into(), ..Manifest::default() }; - for (cloud, kept) in [(true, false), (false, true)] { + for (cloud, kept) in [(true, true), (false, true)] { let app_root = tmp.path().join(format!("app-{cloud}")); std::fs::create_dir_all(&app_root).unwrap(); let (base, server) = serve_forever(bytes.clone()).await; diff --git a/crates/update/tests/update_transaction.rs b/crates/update/tests/update_transaction.rs index 3a50d6bb3..882ab5210 100644 --- a/crates/update/tests/update_transaction.rs +++ b/crates/update/tests/update_transaction.rs @@ -489,7 +489,7 @@ mod versioned { let mut rig = Rig::new("ok"); rig.platform = platform; rig.install_old(&["0.8.0", "0.9.0"]); - // The desktop's background engine, as the release ships it. + // The engine `zeron headless` runs, as the release ships it. for version in ["1.0.0", "2.0.0"] { std::fs::write(rig.app.join(version).join("zeron-engine"), "desktop").unwrap(); } @@ -497,12 +497,9 @@ mod versioned { rig.run_until_settled(); rig.assert_updated(&id); rig.app_settles_to(expected); - // A Cloud machine never runs it, and copies it back in on every wake. - assert_eq!( - rig.app.join("2.0.0/zeron-engine").exists(), - platform.is_none(), - "platform {platform:?}" - ); + // Kept everywhere, Cloud too: `zeron headless` runs it (a Cloud + // machine once left it out, and never came online). + assert!(rig.app.join("2.0.0/zeron-engine").exists(), "platform {platform:?}"); } } diff --git a/crates/voice/src/lib.rs b/crates/voice/src/lib.rs index e475e93c2..59b259b51 100644 --- a/crates/voice/src/lib.rs +++ b/crates/voice/src/lib.rs @@ -184,14 +184,41 @@ pub fn input_devices() -> Vec { .filter_map(|device| { Some(InputDevice { id: device.id().ok()?.to_string(), - name: device.description().ok()?.name().to_owned(), + name: display_name(&device.description().ok()?), }) }) .collect(); devices.dedup_by(|a, b| a.id == b.id); + disambiguate(&mut devices); devices } +/// What to show for a device. WASAPI's `name()` is the endpoint description +/// ("Microphone", "Line"), the same for every device of that kind; the +/// friendly name that includes the hardware ("Microphone (Realtek Audio)") is +/// kept by cpal as the first extended line when it differs. +fn display_name(description: &cpal::DeviceDescription) -> String { + friendly(description.name(), description.extended()) +} + +fn friendly(name: &str, extended: &[String]) -> String { + extended + .first() + .filter(|line| cfg!(windows) && line.contains(name) && !line.trim().is_empty()) + .map_or_else(|| name.to_owned(), |line| line.trim().to_owned()) +} + +/// Two devices with the same name stay tell-apart-able: "Mic", "Mic (2)". +fn disambiguate(devices: &mut [InputDevice]) { + let names: Vec = devices.iter().map(|d| d.name.clone()).collect(); + for (i, device) in devices.iter_mut().enumerate() { + let seen = names[..i].iter().filter(|n| **n == device.name).count(); + if seen > 0 { + device.name = format!("{} ({})", device.name, seen + 1); + } + } +} + /// The id of the device the system currently records from by default. pub fn default_input_device() -> Option { Some( @@ -531,6 +558,35 @@ pub fn unload() { mod tests { use super::*; use cpal::Sample; + + #[test] + fn friendly_name_replaces_the_generic_endpoint_description() { + let extended = vec!["Microphone (Realtek High Definition Audio)".to_owned()]; + let got = friendly("Microphone", &extended); + assert_eq!( + got, + if cfg!(windows) { + "Microphone (Realtek High Definition Audio)" + } else { + "Microphone" + } + ); + // Never swapped for an unrelated extended line. + assert_eq!(friendly("Line", &["Driver 1.2".to_owned()]), "Line"); + assert_eq!(friendly("USB Mic", &[]), "USB Mic"); + } + + #[test] + fn duplicate_names_are_numbered() { + let dev = |id: &str, name: &str| InputDevice { + id: id.into(), + name: name.into(), + }; + let mut devices = vec![dev("a", "Mic"), dev("b", "Line"), dev("c", "Mic")]; + disambiguate(&mut devices); + let names: Vec<_> = devices.iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, ["Mic", "Line", "Mic (2)"]); + } #[test] fn native_sample_formats_preserve_levels_and_downmix_channels() { fn check>() diff --git a/docs/design/cloud-device.md b/docs/design/cloud-device.md index df22d29af..994867f73 100644 --- a/docs/design/cloud-device.md +++ b/docs/design/cloud-device.md @@ -431,12 +431,12 @@ machine (`ZERON_DEVICE_PLATFORM=cloud`) keeps none of them: going back there is downloads anyway. Other Linux installs keep the newest older one, to go back to by hand. Never `current`, the running executable's folder, or a newer version (an update being staged). -A Cloud machine doesn't keep the release's `zeron-engine` either: it's the desktop app's background -engine (78 MB), and the unit runs `zeron headless`, which links the engine. The installer and the -updater leave it out, and the tidy and the pre-sleep cleanup remove it from versions installed before. -Measured on staging (send to first output, n=8 each), a machine on one version went from a median of -17.5 s to 14.2 s once neither it nor Codex's downloads came back with each wake; its wake downloaded -225 MB, 205 of them the engine it runs. +A Cloud machine keeps the release's `zeron-engine` (78 MB). From 2026-11-07 to 2026-11-15 the +installer, the updater and the tidy left it out, when the unit's `zeron headless` linked the engine; +since 0.3.0 the release's `zeron` is the zgx app, whose `zeron headless` runs that `zeron-engine`, so +a machine without it exited at once and never enrolled. The installer keeps it now, and a repair +(`~/.zeron/repair-engine`, the unit's `ExecStartPre=-`, set up by the installer and every wake) puts +it back before each start if an older updater left it out (edge/src/cloud/install-script.ts). A longer wake reads as updating: the engine says so (`POST /runner/wake-stage`), `CloudSession.stage` is `updating` while it lasts (a stage nobody clears stops showing after 10 minutes), the desktop's diff --git a/docs/image-preview.md b/docs/image-preview.md index 00d1c9ec0..a0c9edfa5 100644 --- a/docs/image-preview.md +++ b/docs/image-preview.md @@ -23,7 +23,7 @@ Each Files image surface admits at most 64 MiB of retained image resources, incl ## Tool-call image previews -A tool chip whose call or output names an image file (PNG, JPEG, GIF, WebP, BMP, SVG, TIFF; at most four per chip) previews it when the chip is expanded. Relative paths resolve against the chat's cwd on the owning host. Bytes arrive through `ReadAttachmentChunk`, so its jail applies: the owning host's uploads directory (plus any read-only legacy uploads roots) and the working directory of every chat in the workspace on that host, not just the chat that ran the tool. A projectless chat's working directory is the home directory, so any image under home on that host is readable. Other paths show *Image unavailable*. Network and device paths (UNC `\\host\share`, `//host/share`, `\\?\UNC\…`, `\\.\…`) and drive-relative paths (`C:x.png`) are never previewed. The engine also jails each path lexically, resolving `.`/`..` without touching the filesystem, before it canonicalizes the path, so a path outside every root is refused without being opened. +A tool chip whose call or output names an image file (PNG, JPEG, GIF, WebP, BMP, SVG, TIFF; at most four per chip) previews it when the chip is expanded. Relative paths resolve against the chat's cwd on the owning host. Bytes arrive through `ReadAttachmentChunk`, so its jail applies: the owning host's uploads directory (plus any read-only legacy uploads roots) and the working directory of every chat in the workspace on that host, not just the chat that ran the tool. A projectless chat's working directory is the home directory, so any image under home on that host is readable. When the tool result itself embeds image bytes, the engine stores a copy in the profile uploads directory (named by the chat and the bytes, so the same picture again in a chat is one file) and names it on the tool part as `previewPaths`; a client that reads `previewPaths` (the zgx app) previews that copy, so a scratch path named by the call does not have to be readable. Claude Code's note that only describes an image's displayed size (`[Image: original WxH, displayed at WxH. …]`, `[Image: source: …]`) is not taken as a subagent message. Paths with no embedded bytes, and bytes the store rejects, still show *Image unavailable*. Network and device paths (UNC `\\host\share`, `//host/share`, `\\?\UNC\…`, `\\.\…`) and drive-relative paths (`C:x.png`) are never previewed. The engine also jails each path lexically, resolving `.`/`..` without touching the filesystem, before it canonicalizes the path, so a path outside every root is refused without being opened. `tool_images.rs` decodes one static frame on the background executor within the shared raster limits (4096 pixels per side, 64 MiB decoder allocation), downsamples it to at most 1120×440 and hands BGRA pixels straight to GPUI as a `RenderImage` (no re-encode, no asset cache). Nothing is read or decoded for collapsed chips or hidden groups. Collapsing starts a 600 ms grace; then the CPU frame and the sprite-atlas tiles are released. Reopening inside the grace reuses the texture, so rapid toggling never re-reads or re-decodes. Previews that are expanded but unpainted for 2 s count against a 64 MiB budget; painted ones are never evicted. Chat switches and transcript disposal release everything. diff --git a/edge/src/cloud/install-script.ts b/edge/src/cloud/install-script.ts index eed6fe562..b6c96c15d 100644 --- a/edge/src/cloud/install-script.ts +++ b/edge/src/cloud/install-script.ts @@ -48,6 +48,60 @@ ExecStart=/bin/systemctl start --no-block ${CLOUD_UNIT_NAME} WantedBy=multi-user.target `; +/** + * Puts back the release's `zeron-engine` beside the `zeron` the unit runs, when + * it's missing. Since 0.3.0 the release's `zeron` is the zgx app, whose + * `zeron headless` hands off to that engine: without it the unit exits at + * once, restarts every second and never enrolls. Machines lost it to the + * installer, the engine's own updater and the pre-sleep tidy, which all left + * it out on Cloud (0.3.5's still do), so the unit runs this before every start + * (`ExecStartPre=-`: it never fails a start). Downloads only while it's + * missing, the version `current` names, from the edge's own releases. + */ +export const REPAIR_ENGINE_SCRIPT = `#!/bin/sh +# Zeron Cloud: put back a missing zeron-engine (edge/src/cloud/install-script.ts). +home="\${ZERON_CLOUD_HOME:-$HOME}" +cur="$home/.zeron/app/current" +[ -x "$cur/zeron" ] || exit 0 +[ -f "$cur/zeron-engine" ] && exit 0 +dest="$(readlink -f "$cur")" || exit 0 +ver="$(basename "$dest")" +case "$ver" in + "" | *[!A-Za-z0-9._+-]*) exit 0 ;; +esac +case "$(uname -m)" in + x86_64 | amd64) arch=x86_64 ;; + aarch64 | arm64) arch=aarch64 ;; + *) exit 0 ;; +esac +[ -n "\${ZERON_EDGE_URL:-}" ] || exit 0 +tmp="$(mktemp -d "$home/.zeron/.repair.XXXXXX")" || exit 0 +trap 'rm -rf "$tmp"' EXIT +curl -fsSL --retry 3 --connect-timeout 15 --speed-limit 1048576 --speed-time 15 \\ + -o "$tmp/zeron.tar.gz" "$ZERON_EDGE_URL/releases/zeron-$ver-linux-$arch.tar.gz" || exit 0 +tar -xzf "$tmp/zeron.tar.gz" -C "$tmp" "zeron-$ver-linux-$arch/zeron-engine" || exit 0 +chmod 755 "$tmp/zeron-$ver-linux-$arch/zeron-engine" +mv -f "$tmp/zeron-$ver-linux-$arch/zeron-engine" "$dest/zeron-engine" +echo "zeron cloud: put back zeron-engine for $ver" +`; + +/** + * Writes the repair script (`REPAIR_ENGINE_SCRIPT`) to `~/.zeron/repair-engine` + * and a drop-in running it before the engine's unit starts, each only when it + * differs, reloading systemd only then. Run by the installer and by every + * wake's first command, so machines set up before it get it as they wake. + * Best effort: a failure here never stops what follows. + * `ZERON_CLOUD_HOME` / `ZERON_CLOUD_UNIT_DIR` exist for the unit tier. + */ +export const ENSURE_REPAIR = + `{ h="\${ZERON_CLOUD_HOME:-$HOME}"; r="$h/.zeron/repair-engine"; ` + + `dd="\${ZERON_CLOUD_UNIT_DIR:-/etc/systemd/system}/${CLOUD_UNIT_NAME}.d"; ` + + `t="$(mktemp)" && printf %s '${btoa(REPAIR_ENGINE_SCRIPT)}' | base64 -d >"$t" && ` + + `{ cmp -s "$t" "$r" || install -m 0700 "$t" "$r"; } && ` + + `printf '[Service]\\nExecStartPre=-%s\\n' "$r" >"$t" && ` + + `{ cmp -s "$t" "$dd/repair-engine.conf" || { sudo mkdir -p "$dd" && sudo install -m 0644 "$t" "$dd/repair-engine.conf" && sudo systemctl daemon-reload; }; }; ` + + `rm -f "$t"; } >/dev/null 2>&1 || true`; + export const CLOUD_INSTALL_SCRIPT = `#!/bin/sh # Zeron Cloud engine installer (edge/src/cloud/install-script.ts). # POSIX sh, idempotent, provider-neutral. @@ -85,7 +139,9 @@ esac restart=0 dest="$app/$ver" -if [ -x "$dest/zeron" ]; then +# (Whole, its zeron-engine too: \`zeron headless\` runs it, and installs +# made before 2026-11-15 left it out.) +if [ -x "$dest/zeron" ] && [ -f "$dest/zeron-engine" ]; then echo "zeron $ver already installed" else tmp="$(mktemp -d "$data/.download.XXXXXX")" @@ -99,10 +155,8 @@ else tar -xzf "$tmp/zeron.tar.gz" -C "$tmp/unpacked" --strip-components=1 # Probe before switching: a binary that cannot start must not replace one that can. "$tmp/unpacked/zeron" --version >/dev/null - # The desktop app's background engine (78 MB): never run here (the unit runs - # \`zeron headless\`, which links the engine), and every byte on this disk is - # copied back in on every wake. The engine's updater leaves it out too. - rm -f "$tmp/unpacked/zeron-engine" + # (zeron-engine stays: \`zeron headless\` runs it. Without it the unit + # exits at once and the machine never enrolls.) rm -rf "$dest" mv "$tmp/unpacked" "$dest" fi @@ -172,6 +226,8 @@ else rm -f "$boot_new" fi +# A zeron-engine an update leaves out is put back before each start. +${ENSURE_REPAIR} sudo systemctl daemon-reload sudo systemctl enable ${CLOUD_UNIT_NAME} ${CLOUD_BOOT_UNIT_NAME} >/dev/null sudo systemctl start ${CLOUD_BOOT_UNIT_NAME} @@ -253,6 +309,9 @@ export const RESTART_ENGINE_COMMAND = `sudo systemctl restart ${CLOUD_UNIT_NAME} * systemd hasn't read yet gets one reload. `--no-block` answers at once (the * engine's first token says it's up). Idempotent: a no-op when it's running. */ export const START_ENGINE_COMMAND = + // (First, the repair of a missing zeron-engine before each start, for + // machines set up before it: a no-op once it's there.) + `${ENSURE_REPAIR}; ` + `sudo systemctl start --no-block ${CLOUD_UNIT_NAME} || ` + `{ sudo systemctl daemon-reload; sudo systemctl start --no-block ${CLOUD_UNIT_NAME}; }`; diff --git a/edge/test/unit/install-script.test.ts b/edge/test/unit/install-script.test.ts index b96da8ce3..a4b8420ec 100644 --- a/edge/test/unit/install-script.test.ts +++ b/edge/test/unit/install-script.test.ts @@ -13,6 +13,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { CLOUD_BOOT_UNIT, CLOUD_INSTALL_SCRIPT, + REPAIR_ENGINE_SCRIPT, START_ENGINE_COMMAND, STOP_ENGINE_COMMAND, installCommand, @@ -110,8 +111,15 @@ describe("cloud install script", { timeout: 60_000 }, () => { const data = join(home, ".zeron"); expect(readlinkSync(join(data, "app", "current"))).toBe(join(data, "app", "1.2.3")); expect(existsSync(join(data, "app", "1.2.3", "zeron"))).toBe(true); - // Never run on Cloud, and copied back in on every wake if kept. - expect(existsSync(join(data, "app", "1.2.3", "zeron-engine"))).toBe(false); + // Kept: `zeron headless` runs it (without it the unit exits at once and + // the machine never enrolls). + expect(existsSync(join(data, "app", "1.2.3", "zeron-engine"))).toBe(true); + // And put back before each start, should an update leave it out. + expect(statSync(join(data, "repair-engine")).mode & 0o777).toBe(0o700); + expect(readFileSync(join(data, "repair-engine"), "utf8")).toBe(REPAIR_ENGINE_SCRIPT); + expect(readFileSync(join(units, "zeron-cloud.service.d", "repair-engine.conf"), "utf8")).toBe( + `[Service]\nExecStartPre=-${join(data, "repair-engine")}\n` + ); const envFile = join(data, "env"); expect(statSync(envFile).mode & 0o777).toBe(0o600); expect(readFileSync(envFile, "utf8")).toBe( @@ -159,6 +167,45 @@ describe("cloud install script", { timeout: 60_000 }, () => { expect(calls()).toContain("systemctl restart zeron-cloud.service"); }); + it("downloads again a version installed without its zeron-engine", () => { + const { home, run, calls, clearCalls } = setup(); + run("org.user.cloud-1.codeA"); + const engine = join(home, ".zeron", "app", "1.2.3", "zeron-engine"); + rmSync(engine); + clearCalls(); + run("org.user.cloud-1.codeA"); + expect(existsSync(engine)).toBe(true); + expect(calls().filter((c) => c.includes(".tar.gz"))).toHaveLength(1); + }); + + it("puts back a zeron-engine an update left out, and does nothing once it's there", () => { + const { home, run, calls, clearCalls } = setup(); + run("org.user.cloud-1.codeA"); + const data = join(home, ".zeron"); + const engine = join(data, "app", "1.2.3", "zeron-engine"); + const repair = () => + execFileSync("sh", [join(data, "repair-engine")], { + env: { PATH: `${join(root, "bin")}:/usr/bin:/bin`, ZERON_CLOUD_HOME: home, ZERON_EDGE_URL: "https://edge.test" }, + encoding: "utf8" + }); + rmSync(engine); + clearCalls(); + expect(repair()).toContain("put back zeron-engine for 1.2.3"); + expect(existsSync(engine)).toBe(true); + expect(statSync(engine).mode & 0o111).not.toBe(0); + expect(calls().filter((c) => c.includes("/releases/zeron-1.2.3-linux-x86_64.tar.gz"))).toHaveLength(1); + // There: no download. + clearCalls(); + repair(); + expect(calls().filter((c) => c.startsWith("curl"))).toHaveLength(0); + // A download that fails leaves the start to go on (it never fails it). + rmSync(engine); + writeFileSync(join(root, "bin", "curl"), "#!/bin/sh\nexit 22\n"); + chmodSync(join(root, "bin", "curl"), 0o755); + expect(() => repair()).not.toThrow(); + expect(existsSync(engine)).toBe(false); + }); + it("doesn't wait for the network to start the engine, and starts it on boot without being asked", () => { const { units, run } = setup(); run("org.user.cloud-1.codeA"); @@ -237,9 +284,19 @@ describe("cloud install script", { timeout: 60_000 }, () => { }); it("starts the engine without waiting on it, and reloads once for a unit systemd hasn't read", () => { - const { calls, clearCalls } = setup(); + const { home, units, calls, clearCalls } = setup(); + mkdirSync(join(home, ".zeron"), { recursive: true }); const start = () => - execFileSync("sh", ["-c", START_ENGINE_COMMAND], { env: { PATH: `${join(root, "bin")}:/usr/bin:/bin` }, encoding: "utf8" }); + execFileSync("sh", ["-c", START_ENGINE_COMMAND], { + env: { PATH: `${join(root, "bin")}:/usr/bin:/bin`, ZERON_CLOUD_HOME: home, ZERON_CLOUD_UNIT_DIR: units }, + encoding: "utf8" + }); + // A machine set up before the repair: its first wake writes it, once. + clearCalls(); + start(); + expect(calls()).toEqual(["systemctl daemon-reload", "systemctl start --no-block zeron-cloud.service"]); + expect(readFileSync(join(home, ".zeron", "repair-engine"), "utf8")).toBe(REPAIR_ENGINE_SCRIPT); + expect(readFileSync(join(units, "zeron-cloud.service.d", "repair-engine.conf"), "utf8")).toContain("ExecStartPre=-"); clearCalls(); start(); expect(calls()).toEqual(["systemctl start --no-block zeron-cloud.service"]); diff --git a/edge/wrangler.jsonc b/edge/wrangler.jsonc index 15d5cdc79..9cc83c8c8 100644 --- a/edge/wrangler.jsonc +++ b/edge/wrangler.jsonc @@ -178,6 +178,14 @@ // snapshot.read. Unset ⇒ every session installs the engine (~30–60 s). "WORKOS_CLIENT_ID": "client_01KWD0EAKZKD50YCQJNYSRE4BY", "AUTH_MODE": "workos", + // Who the chat rooms offer the relay layer to (docs/design/relay-layer.md): + // "1" for everyone, a comma-separated list of WorkOS user ids (each room + // checks its owner), or "" (or unset) for nobody. Now: everyone. Taking a + // user off is safe at any time: each of their hosts, as it next opens a + // chat, stores a checkpoint and moves the chat back to stored rows. + // Never deploy edge code older than this release while any room may still + // hold a relay queue or an unhealed chat (14 days after turning it off). + "CHAT_RELAY_LAYER": "1", // Sandbox provider for NEW Cloud devices (src/cloud/providers): "boat". // Existing sandboxes keep the provider they were created on. "SANDBOX_PROVIDER": "boat",