Resolve merge conflicts

This commit is contained in:
Kevin van Dijk
2026-02-18 13:33:40 +01:00
31 changed files with 729 additions and 304 deletions
+3 -1
View File
@@ -66,9 +66,11 @@ jobs:
run: |
COMMENT=$(bun script/duplicate-pr.ts -f pr_info.txt "Check the attached file for PR details and search for duplicates")
gh pr comment "$PR_NUMBER" --body "_The following comment was made by an LLM, it may be inaccurate:_
if [ "$COMMENT" != "No duplicate PRs found" ]; then
gh pr comment "$PR_NUMBER" --body "_The following comment was made by an LLM, it may be inaccurate:_
$COMMENT"
fi
add-contributor-label:
runs-on: blacksmith-2vcpu-ubuntu-2404 # kilocode_change
+6 -22
View File
@@ -435,7 +435,7 @@
"@kobalte/core": "0.13.11",
"@octokit/rest": "22.0.0",
"@openauthjs/openauth": "0.0.0-20250322224806",
"@pierre/diffs": "1.0.2",
"@pierre/diffs": "1.1.0-beta.13",
"@playwright/test": "1.51.0",
"@solid-primitives/storage": "4.3.3",
"@solidjs/meta": "0.29.4",
@@ -1067,7 +1067,7 @@
"@parcel/watcher-win32-x64": ["@parcel/watcher-win32-x64@2.5.1", "", { "os": "win32", "cpu": "x64" }, "sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA=="],
"@pierre/diffs": ["@pierre/diffs@1.0.2", "", { "dependencies": { "@shikijs/core": "^3.0.0", "@shikijs/engine-javascript": "3.19.0", "@shikijs/transformers": "3.19.0", "diff": "8.0.2", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "3.19.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-RkFSDD5X/U+8QjyilPViYGJfmJNWXR17zTL8zw48+DcVC1Ujbh6I1edyuRnFfgRzpft05x2DSCkz2cjoIAxPvQ=="],
"@pierre/diffs": ["@pierre/diffs@1.1.0-beta.13", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-D35rxDu5V7XHX5aVGU6PF12GhscL+I+9QYgxK/i3h0d2XSirAxDdVNm49aYwlOhgmdvL0NbS1IHxPswVB5yJvw=="],
"@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="],
@@ -1133,9 +1133,9 @@
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.57.1", "", { "os": "win32", "cpu": "x64" }, "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA=="],
"@shikijs/core": ["@shikijs/core@3.22.0", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-iAlTtSDDbJiRpvgL5ugKEATDtHdUVkqgHDm/gbD2ZS9c88mx7G1zSYjjOxp5Qa0eaW0MAQosFRmJSk354PRoQA=="],
"@shikijs/core": ["@shikijs/core@3.9.2", "", { "dependencies": { "@shikijs/types": "3.9.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-3q/mzmw09B2B6PgFNeiaN8pkNOixWS726IHmJEpjDAcneDPMQmUg2cweT9cWXY4XcyQS3i6mOOUgQz9RRUP6HA=="],
"@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.19.0", "", { "dependencies": { "@shikijs/types": "3.19.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-ZfWJNm2VMhKkQIKT9qXbs76RRcT0SF/CAvEz0+RkpUDAoDaCx0uFdCGzSRiD9gSlhm6AHkjdieOBJMaO2eC1rQ=="],
"@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-OFx8fHAZuk7I42Z9YAdZ95To6jDePQ9Rnfbw9uSRTSbBhYBp1kEOKv/3jOimcj3VRUKusDYM6DswLauwfhboLg=="],
"@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-Yx3gy7xLzM0ZOjqoxciHjA7dAt5tyzJE3L4uQoM83agahy+PlW244XJSrmJRSBvGYELDhYXPacD4R/cauV5bzQ=="],
@@ -2999,13 +2999,11 @@
"@pierre/diffs/@shikijs/transformers": ["@shikijs/transformers@3.19.0", "", { "dependencies": { "@shikijs/core": "3.19.0", "@shikijs/types": "3.19.0" } }, "sha512-e6vwrsyw+wx4OkcrDbL+FVCxwx8jgKiCoXzakVur++mIWVcgpzIi8vxf4/b4dVTYrV/nUx5RjinMf4tq8YV8Fw=="],
"@pierre/diffs/shiki": ["shiki@3.19.0", "", { "dependencies": { "@shikijs/core": "3.19.0", "@shikijs/engine-javascript": "3.19.0", "@shikijs/engine-oniguruma": "3.19.0", "@shikijs/langs": "3.19.0", "@shikijs/themes": "3.19.0", "@shikijs/types": "3.19.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-77VJr3OR/VUZzPiStyRhADmO2jApMM0V2b1qf0RpfWya8Zr1PeZev5AEpPGAAKWdiYUtcZGBE4F5QvJml1PvWA=="],
"@pierre/diffs/diff": ["diff@8.0.3", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
"@protobuf-ts/plugin/typescript": ["typescript@3.9.10", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q=="],
"@shikijs/core/@shikijs/types": ["@shikijs/types@3.22.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-491iAekgKDBFE67z70Ok5a8KBMsQ2IJwOWw3us/7ffQkIBCyOQfm/aNwVMBUriP02QshIfgHCBSIYAl3u2eWjg=="],
"@shikijs/engine-javascript/@shikijs/types": ["@shikijs/types@3.19.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-Z2hdeEQlzuntf/BZpFG8a+Fsw9UVXdML7w0o3TgSXV3yNESGon+bs9ITkQb3Ki7zxoXOOu5oJWqZ2uto06V9iQ=="],
"@shikijs/engine-javascript/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
"@shikijs/engine-oniguruma/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
@@ -3013,8 +3011,6 @@
"@shikijs/themes/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
"@shikijs/transformers/@shikijs/core": ["@shikijs/core@3.9.2", "", { "dependencies": { "@shikijs/types": "3.9.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-3q/mzmw09B2B6PgFNeiaN8pkNOixWS726IHmJEpjDAcneDPMQmUg2cweT9cWXY4XcyQS3i6mOOUgQz9RRUP6HA=="],
"@smithy/eventstream-serde-universal/@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.2.8", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.12.0", "@smithy/util-hex-encoding": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-jS/O5Q14UsufqoGhov7dHLOPCzkYJl9QDzusI2Psh4wyYx/izhzvX9P4D69aTxcdfVhEPhjK+wYyn/PzLjKbbw=="],
"@tailwindcss/oxide/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
@@ -3181,8 +3177,6 @@
"shiki/@shikijs/core": ["@shikijs/core@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-f2ED7HYV4JEk827mtMDwe/yQ25pRiXZmtHjWF8uzZKuKiEsJR7Ce1nuQ+HhV9FzDcbIo4ObBCD9GPTzNuy9S1g=="],
"shiki/@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-OFx8fHAZuk7I42Z9YAdZ95To6jDePQ9Rnfbw9uSRTSbBhYBp1kEOKv/3jOimcj3VRUKusDYM6DswLauwfhboLg=="],
"shiki/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="],
"string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
@@ -3301,16 +3295,6 @@
"@pierre/diffs/@shikijs/transformers/@shikijs/types": ["@shikijs/types@3.19.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-Z2hdeEQlzuntf/BZpFG8a+Fsw9UVXdML7w0o3TgSXV3yNESGon+bs9ITkQb3Ki7zxoXOOu5oJWqZ2uto06V9iQ=="],
"@pierre/diffs/shiki/@shikijs/core": ["@shikijs/core@3.19.0", "", { "dependencies": { "@shikijs/types": "3.19.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-L7SrRibU7ZoYi1/TrZsJOFAnnHyLTE1SwHG1yNWjZIVCqjOEmCSuK2ZO9thnRbJG6TOkPp+Z963JmpCNw5nzvA=="],
"@pierre/diffs/shiki/@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@3.19.0", "", { "dependencies": { "@shikijs/types": "3.19.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-1hRxtYIJfJSZeM5ivbUXv9hcJP3PWRo5prG/V2sWwiubUKTa+7P62d2qxCW8jiVFX4pgRHhnHNp+qeR7Xl+6kg=="],
"@pierre/diffs/shiki/@shikijs/langs": ["@shikijs/langs@3.19.0", "", { "dependencies": { "@shikijs/types": "3.19.0" } }, "sha512-dBMFzzg1QiXqCVQ5ONc0z2ebyoi5BKz+MtfByLm0o5/nbUu3Iz8uaTCa5uzGiscQKm7lVShfZHU1+OG3t5hgwg=="],
"@pierre/diffs/shiki/@shikijs/themes": ["@shikijs/themes@3.19.0", "", { "dependencies": { "@shikijs/types": "3.19.0" } }, "sha512-H36qw+oh91Y0s6OlFfdSuQ0Ld+5CgB/VE6gNPK+Hk4VRbVG/XQgkjnt4KzfnnoO6tZPtKJKHPjwebOCfjd6F8A=="],
"@pierre/diffs/shiki/@shikijs/types": ["@shikijs/types@3.19.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-Z2hdeEQlzuntf/BZpFG8a+Fsw9UVXdML7w0o3TgSXV3yNESGon+bs9ITkQb3Ki7zxoXOOu5oJWqZ2uto06V9iQ=="],
"@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
"@vscode/test-cli/chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
+1 -1
View File
@@ -33,7 +33,7 @@
"@tsconfig/bun": "1.0.9",
"@cloudflare/workers-types": "4.20251008.0",
"@openauthjs/openauth": "0.0.0-20250322224806",
"@pierre/diffs": "1.0.2",
"@pierre/diffs": "1.1.0-beta.13",
"@solid-primitives/storage": "4.3.3",
"@tailwindcss/vite": "4.1.11",
"diff": "8.0.2",
@@ -139,7 +139,7 @@ export function SessionReviewTab(props: SessionReviewTabProps) {
open={props.view().review.open()}
onOpenChange={props.view().review.setOpen}
classes={{
root: props.classes?.root ?? "pb-40",
root: props.classes?.root ?? "pb-6",
header: props.classes?.header ?? "px-6",
container: props.classes?.container ?? "px-6",
}}
+13
View File
@@ -3117,6 +3117,7 @@ dependencies = [
"tauri-plugin-window-state",
"tauri-specta",
"tokio",
"tokio-stream",
"tracing",
"tracing-appender",
"tracing-subscriber",
@@ -5631,6 +5632,18 @@ dependencies = [
"tokio",
]
[[package]]
name = "tokio-stream"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
"tokio-util",
]
[[package]]
name = "tokio-util"
version = "0.7.17"
+1
View File
@@ -51,6 +51,7 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-appender = "0.2"
chrono = "0.4"
tokio-stream = { version = "0.1.18", features = ["sync"] }
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18.2"
+117 -46
View File
@@ -1,35 +1,46 @@
use futures::{FutureExt, Stream, StreamExt, future};
use tauri::{AppHandle, Manager, path::BaseDirectory};
use tauri_plugin_shell::{
ShellExt,
process::{Command, CommandChild, CommandEvent, TerminatedPayload},
process::{CommandChild, CommandEvent, TerminatedPayload},
};
use tauri_plugin_store::StoreExt;
use tauri_specta::Event;
use tokio::sync::oneshot;
use tracing::Instrument;
use crate::constants::{SETTINGS_STORE, WSL_ENABLED_KEY};
const CLI_INSTALL_DIR: &str = ".kilo/bin";
const CLI_BINARY_NAME: &str = "opencode";
#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Debug)]
pub struct ServerConfig {
pub hostname: Option<String>,
pub port: Option<u32>,
}
#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Debug)]
pub struct Config {
pub server: Option<ServerConfig>,
}
pub async fn get_config(app: &AppHandle) -> Option<Config> {
create_command(app, "debug config", &[])
.output()
let (events, _) = spawn_command(app, "debug config", &[]).ok()?;
events
.fold(String::new(), async |mut config_str, event| {
if let CommandEvent::Stdout(stdout) = event
&& let Ok(s) = str::from_utf8(&stdout)
{
config_str += s
}
config_str
})
.map(|v| serde_json::from_str::<Config>(&v))
.await
.inspect_err(|e| tracing::warn!("Failed to read OC config: {e}"))
.ok()
.and_then(|out| String::from_utf8(out.stdout.to_vec()).ok())
.and_then(|s| serde_json::from_str::<Config>(&s).ok())
}
fn get_cli_install_path() -> Option<std::path::PathBuf> {
@@ -175,7 +186,11 @@ fn shell_escape(input: &str) -> String {
escaped
}
pub fn create_command(app: &tauri::AppHandle, args: &str, extra_env: &[(&str, String)]) -> Command {
pub fn spawn_command(
app: &tauri::AppHandle,
args: &str,
extra_env: &[(&str, String)],
) -> Result<(impl Stream<Item = CommandEvent> + 'static, CommandChild), tauri_plugin_shell::Error> {
let state_dir = app
.path()
.resolve("", BaseDirectory::AppLocalData)
@@ -202,7 +217,7 @@ pub fn create_command(app: &tauri::AppHandle, args: &str, extra_env: &[(&str, St
.map(|(key, value)| (key.to_string(), value.clone())),
);
if cfg!(windows) {
let cmd = if cfg!(windows) {
if is_wsl_enabled(app) {
tracing::info!("WSL is enabled, spawning CLI server in WSL");
let version = app.package_info().version.to_string();
@@ -234,10 +249,9 @@ pub fn create_command(app: &tauri::AppHandle, args: &str, extra_env: &[(&str, St
script.push(format!("{} exec \"$BIN\" {}", env_prefix.join(" "), args));
return app
.shell()
app.shell()
.command("wsl")
.args(["-e", "bash", "-lc", &script.join("\n")]);
.args(["-e", "bash", "-lc", &script.join("\n")])
} else {
let mut cmd = app
.shell()
@@ -249,7 +263,7 @@ pub fn create_command(app: &tauri::AppHandle, args: &str, extra_env: &[(&str, St
cmd = cmd.env(key, value);
}
return cmd;
cmd
}
} else {
let sidecar = get_sidecar_path(app);
@@ -268,7 +282,13 @@ pub fn create_command(app: &tauri::AppHandle, args: &str, extra_env: &[(&str, St
}
cmd
}
};
let (rx, child) = cmd.spawn()?;
let event_stream = tokio_stream::wrappers::ReceiverStream::new(rx);
let event_stream = sqlite_migration::logs_middleware(app.clone(), event_stream);
Ok((event_stream, child))
}
pub fn serve(
@@ -286,45 +306,96 @@ pub fn serve(
("KILO_SERVER_PASSWORD", password.to_string()),
];
let (mut rx, child) = create_command(
let (events, child) = spawn_command(
app,
format!("--print-logs --log-level WARN serve --hostname {hostname} --port {port}").as_str(),
&envs,
)
.spawn()
.expect("Failed to spawn opencode");
tokio::spawn(async move {
let mut exit_tx = Some(exit_tx);
while let Some(event) = rx.recv().await {
match event {
CommandEvent::Stdout(line_bytes) => {
let line = String::from_utf8_lossy(&line_bytes);
tracing::info!(target: "sidecar", "{line}");
}
CommandEvent::Stderr(line_bytes) => {
let line = String::from_utf8_lossy(&line_bytes);
tracing::info!(target: "sidecar", "{line}");
}
CommandEvent::Error(err) => {
tracing::error!(target: "sidecar", "{err}");
}
CommandEvent::Terminated(payload) => {
tracing::info!(
target: "sidecar",
code = ?payload.code,
signal = ?payload.signal,
"Sidecar terminated"
);
if let Some(tx) = exit_tx.take() {
let _ = tx.send(payload);
let mut exit_tx = Some(exit_tx);
tokio::spawn(
events
.for_each(move |event| {
match event {
CommandEvent::Stdout(line_bytes) => {
let line = String::from_utf8_lossy(&line_bytes);
tracing::info!("{line}");
}
CommandEvent::Stderr(line_bytes) => {
let line = String::from_utf8_lossy(&line_bytes);
tracing::info!("{line}");
}
CommandEvent::Error(err) => {
tracing::error!("{err}");
}
CommandEvent::Terminated(payload) => {
tracing::info!(
code = ?payload.code,
signal = ?payload.signal,
"Sidecar terminated"
);
if let Some(tx) = exit_tx.take() {
let _ = tx.send(payload);
}
}
_ => {}
}
_ => {}
}
}
});
future::ready(())
})
.instrument(tracing::info_span!("sidecar")),
);
(child, exit_rx)
}
pub mod sqlite_migration {
use super::*;
#[derive(
tauri_specta::Event, serde::Serialize, serde::Deserialize, Clone, Copy, Debug, specta::Type,
)]
#[serde(tag = "type", content = "value")]
pub enum SqliteMigrationProgress {
InProgress(u8),
Done,
}
pub(super) fn logs_middleware(
app: AppHandle,
stream: impl Stream<Item = CommandEvent>,
) -> impl Stream<Item = CommandEvent> {
let app = app.clone();
let mut done = false;
stream.filter_map(move |event| {
if done {
return future::ready(Some(event));
}
future::ready(match &event {
CommandEvent::Stdout(stdout) => {
let Ok(s) = str::from_utf8(stdout) else {
return future::ready(None);
};
if let Some(s) = s.strip_prefix("sqlite-migration:").map(|s| s.trim()) {
if let Ok(progress) = s.parse::<u8>() {
let _ = SqliteMigrationProgress::InProgress(progress).emit(&app);
} else if s == "done" {
done = true;
let _ = SqliteMigrationProgress::Done.emit(&app);
}
None
} else {
Some(event)
}
}
_ => Some(event),
})
})
}
}
+130 -46
View File
@@ -24,16 +24,17 @@ use std::{
sync::{Arc, Mutex},
time::Duration,
};
use tauri::{AppHandle, Manager, RunEvent, State, ipc::Channel};
use tauri::{AppHandle, Listener, Manager, RunEvent, State, ipc::Channel};
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_shell::process::CommandChild;
use tauri_specta::Event;
use tokio::{
sync::{oneshot, watch},
time::{sleep, timeout},
};
use crate::cli::sync_cli;
use crate::cli::{sqlite_migration::SqliteMigrationProgress, sync_cli};
use crate::constants::*;
use crate::server::get_saved_server_url;
use crate::windows::{LoadingWindow, MainWindow};
@@ -52,6 +53,13 @@ enum InitStep {
Done,
}
#[derive(serde::Deserialize, specta::Type)]
#[serde(rename_all = "snake_case")]
enum WslPathMode {
Windows,
Linux,
}
struct InitState {
current: watch::Receiver<InitStep>,
}
@@ -115,8 +123,8 @@ async fn await_initialization(
let mut rx = init_state.current.clone();
let events = async {
let e = (*rx.borrow()).clone();
let _ = events.send(e).unwrap();
let e = *rx.borrow();
let _ = events.send(e);
while rx.changed().await.is_ok() {
let step = *rx.borrow_and_update();
@@ -382,32 +390,50 @@ fn check_linux_app(app_name: &str) -> bool {
return true;
}
#[tauri::command]
#[specta::specta]
fn wsl_path(path: String, mode: Option<WslPathMode>) -> Result<String, String> {
if !cfg!(windows) {
return Ok(path);
}
let flag = match mode.unwrap_or(WslPathMode::Linux) {
WslPathMode::Windows => "-w",
WslPathMode::Linux => "-u",
};
let output = if path.starts_with('~') {
let suffix = path.strip_prefix('~').unwrap_or("");
let escaped = suffix.replace('"', "\\\"");
let cmd = format!("wslpath {flag} \"$HOME{escaped}\"");
Command::new("wsl")
.args(["-e", "sh", "-lc", &cmd])
.output()
.map_err(|e| format!("Failed to run wslpath: {e}"))?
} else {
Command::new("wsl")
.args(["-e", "wslpath", flag, &path])
.output()
.map_err(|e| format!("Failed to run wslpath: {e}"))?
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if stderr.is_empty() {
return Err("wslpath failed".to_string());
}
return Err(stderr);
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let builder = tauri_specta::Builder::<tauri::Wry>::new()
// Then register them (separated by a comma)
.commands(tauri_specta::collect_commands![
kill_sidecar,
cli::install_cli,
await_initialization,
server::get_default_server_url,
server::set_default_server_url,
get_display_backend,
set_display_backend,
markdown::parse_markdown_command,
check_app_exists,
resolve_app_path
])
.events(tauri_specta::collect_events![LoadingWindowComplete])
.error_handling(tauri_specta::ErrorHandlingMode::Throw);
let builder = make_specta_builder();
#[cfg(debug_assertions)] // <- Only export on non-release builds
builder
.export(
specta_typescript::Typescript::default(),
"../src/bindings.ts",
)
.expect("Failed to export typescript bindings");
export_types(&builder);
#[cfg(all(target_os = "macos", not(debug_assertions)))]
let _ = std::process::Command::new("killall")
@@ -474,6 +500,47 @@ pub fn run() {
});
}
fn make_specta_builder() -> tauri_specta::Builder<tauri::Wry> {
tauri_specta::Builder::<tauri::Wry>::new()
// Then register them (separated by a comma)
.commands(tauri_specta::collect_commands![
kill_sidecar,
cli::install_cli,
await_initialization,
server::get_default_server_url,
server::set_default_server_url,
server::get_wsl_config,
server::set_wsl_config,
get_display_backend,
set_display_backend,
markdown::parse_markdown_command,
check_app_exists,
wsl_path,
resolve_app_path
])
.events(tauri_specta::collect_events![
LoadingWindowComplete,
SqliteMigrationProgress
])
.error_handling(tauri_specta::ErrorHandlingMode::Throw)
}
fn export_types(builder: &tauri_specta::Builder<tauri::Wry>) {
builder
.export(
specta_typescript::Typescript::default(),
"../src/bindings.ts",
)
.expect("Failed to export typescript bindings");
}
#[cfg(test)]
#[test]
fn test_export_types() {
let builder = make_specta_builder();
export_types(&builder);
}
#[derive(tauri_specta::Event, serde::Deserialize, specta::Type)]
struct LoadingWindowComplete;
@@ -493,17 +560,46 @@ async fn initialize(app: AppHandle) {
tracing::info!("Main and loading windows created");
// SQLite migration handling:
// We only do this if the sqlite db doesn't exist, and we're expecting the sidecar to create it
// First, we spawn a task that listens for SqliteMigrationProgress events that can
// come from any invocation of the sidecar CLI. The progress is captured by a stdout stream interceptor.
// Then in the loading task, we wait for sqlite migration to complete before
// starting our health check against the server, otherwise long migrations could result in a timeout.
let sqlite_enabled = option_env!("KILO_SQLITE").is_some();
let sqlite_done = (sqlite_enabled && !sqlite_file_exists()).then(|| {
tracing::info!(
path = %opencode_db_path().expect("failed to get db path").display(),
"Sqlite file not found, waiting for it to be generated"
);
let (done_tx, done_rx) = oneshot::channel::<()>();
let done_tx = Arc::new(Mutex::new(Some(done_tx)));
let init_tx = init_tx.clone();
let id = SqliteMigrationProgress::listen(&app, move |e| {
let _ = init_tx.send(InitStep::SqliteWaiting);
if matches!(e.payload, SqliteMigrationProgress::Done)
&& let Some(done_tx) = done_tx.lock().unwrap().take()
{
let _ = done_tx.send(());
}
});
let app = app.clone();
tokio::spawn(done_rx.map(async move |_| {
app.unlisten(id);
}))
});
let loading_task = tokio::spawn({
let init_tx = init_tx.clone();
let app = app.clone();
async move {
let mut sqlite_exists = sqlite_file_exists();
tracing::info!("Setting up server connection");
let server_connection = setup_server_connection(app.clone()).await;
tracing::info!("Server connection setup");
// we delay spawning this future so that the timeout is created lazily
let cli_health_check = match server_connection {
@@ -559,23 +655,12 @@ async fn initialize(app: AppHandle) {
}
};
tracing::info!("server connection started");
if let Some(cli_health_check) = cli_health_check {
if sqlite_enabled {
tracing::debug!(sqlite_exists, "Checking sqlite file existence");
if !sqlite_exists {
tracing::info!(
path = %opencode_db_path().expect("failed to get db path").display(),
"Sqlite file not found, waiting for it to be generated"
);
let _ = init_tx.send(InitStep::SqliteWaiting);
while !sqlite_exists {
sleep(Duration::from_secs(1)).await;
sqlite_exists = sqlite_file_exists();
}
}
if let Some(sqlite_done_rx) = sqlite_done {
let _ = sqlite_done_rx.await;
}
tokio::spawn(cli_health_check);
}
@@ -591,11 +676,11 @@ async fn initialize(app: AppHandle) {
.is_err()
{
tracing::debug!("Loading task timed out, showing loading window");
let app = app.clone();
let loading_window = LoadingWindow::create(&app).expect("Failed to create loading window");
sleep(Duration::from_secs(1)).await;
Some(loading_window)
} else {
tracing::debug!("Showing main window without loading window");
MainWindow::create(&app).expect("Failed to create main window");
None
@@ -604,7 +689,6 @@ async fn initialize(app: AppHandle) {
let _ = loading_task.await;
tracing::info!("Loading done, completing initialisation");
let _ = init_tx.send(InitStep::Done);
if loading_window.is_some() {
+38 -1
View File
@@ -8,9 +8,14 @@ use tokio::task::JoinHandle;
use crate::{
cli,
constants::{DEFAULT_SERVER_URL_KEY, SETTINGS_STORE},
constants::{DEFAULT_SERVER_URL_KEY, SETTINGS_STORE, WSL_ENABLED_KEY},
};
#[derive(Clone, serde::Serialize, serde::Deserialize, specta::Type, Debug, Default)]
pub struct WslConfig {
pub enabled: bool,
}
#[tauri::command]
#[specta::specta]
pub fn get_default_server_url(app: AppHandle) -> Result<Option<String>, String> {
@@ -48,6 +53,38 @@ pub async fn set_default_server_url(app: AppHandle, url: Option<String>) -> Resu
Ok(())
}
#[tauri::command]
#[specta::specta]
pub fn get_wsl_config(app: AppHandle) -> Result<WslConfig, String> {
let store = app
.store(SETTINGS_STORE)
.map_err(|e| format!("Failed to open settings store: {}", e))?;
let enabled = store
.get(WSL_ENABLED_KEY)
.as_ref()
.and_then(|v| v.as_bool())
.unwrap_or(false);
Ok(WslConfig { enabled })
}
#[tauri::command]
#[specta::specta]
pub fn set_wsl_config(app: AppHandle, config: WslConfig) -> Result<(), String> {
let store = app
.store(SETTINGS_STORE)
.map_err(|e| format!("Failed to open settings store: {}", e))?;
store.set(WSL_ENABLED_KEY, serde_json::Value::Bool(config.enabled));
store
.save()
.map_err(|e| format!("Failed to save settings: {}", e))?;
Ok(())
}
pub async fn get_saved_server_url(app: &tauri::AppHandle) -> Option<String> {
if let Some(url) = get_default_server_url(app.clone()).ok().flatten() {
tracing::info!(%url, "Using desktop-specific custom URL");
+9
View File
@@ -20,6 +20,7 @@ export const commands = {
/** Events */
export const events = {
loadingWindowComplete: makeEvent<LoadingWindowComplete>("loading-window-complete"),
sqliteMigrationProgress: makeEvent<SqliteMigrationProgress>("sqlite-migration-progress"),
};
/* Types */
@@ -34,6 +35,14 @@ export type ServerReadyData = {
password: string | null,
};
export type SqliteMigrationProgress = { type: "InProgress"; value: number } | { type: "Done" };
export type WslConfig = {
enabled: boolean,
};
export type WslPathMode = "windows" | "linux";
/* Tauri Specta runtime */
function makeEvent<T>(name: string) {
const base = {
+2 -11
View File
@@ -1,14 +1,7 @@
// @refresh reload
import { webviewZoom } from "./webview-zoom"
import { render } from "solid-js/web"
import {
AppBaseProviders,
AppInterface,
PlatformProvider,
Platform,
DisplayBackend,
useCommand,
} from "@opencode-ai/app"
import { AppBaseProviders, AppInterface, PlatformProvider, Platform, useCommand } from "@opencode-ai/app"
import { open, save } from "@tauri-apps/plugin-dialog"
import { getCurrent, onOpenUrl } from "@tauri-apps/plugin-deep-link"
import { openPath as openerOpenPath } from "@tauri-apps/plugin-opener"
@@ -352,7 +345,7 @@ const createPlatform = (password: Accessor<string | null>): Platform => ({
},
getDisplayBackend: async () => {
const result = await invoke<DisplayBackend | null>("get_display_backend").catch(() => null)
const result = await commands.getDisplayBackend().catch(() => null)
return result
},
@@ -451,11 +444,9 @@ type ServerReadyData = { url: string; password: string | null }
// Gate component that waits for the server to be ready
function ServerGate(props: { children: (data: Accessor<ServerReadyData>) => JSX.Element }) {
const [serverData] = createResource(() => commands.awaitInitialization(new Channel<InitStep>() as any))
if (serverData.state === "errored") throw serverData.error
return (
// Not using suspense as not all components are compatible with it (undefined refs)
<Show
when={serverData.state !== "pending" && serverData()}
fallback={
+70 -48
View File
@@ -3,73 +3,95 @@ import { MetaProvider } from "@solidjs/meta"
import "@opencode-ai/app/index.css"
import { Font } from "@opencode-ai/ui/font"
import { Splash } from "@opencode-ai/ui/logo"
import { Progress } from "@opencode-ai/ui/progress"
import "./styles.css"
import { createSignal, Match, onMount } from "solid-js"
import { createEffect, createMemo, createSignal, onCleanup } from "solid-js"
import { commands, events, InitStep } from "./bindings"
import { Channel } from "@tauri-apps/api/core"
import { Switch } from "solid-js"
const root = document.getElementById("root")!
const lines = ["Just a moment...", "Migrating your database", "This may take a couple of minutes"]
const delays = [3000, 9000]
render(() => {
let splash!: SVGSVGElement
const [state, setState] = createSignal<InitStep | null>(null)
const [step, setStep] = createSignal<InitStep | null>(null)
const [line, setLine] = createSignal(0)
const [percent, setPercent] = createSignal(0)
const phase = createMemo(() => step()?.phase)
const value = createMemo(() => {
if (phase() === "done") return 100
return Math.max(25, Math.min(100, percent()))
})
const channel = new Channel<InitStep>()
channel.onmessage = (e) => setState(e)
commands.awaitInitialization(channel as any).then(() => {
const currentOpacity = getComputedStyle(splash).opacity
channel.onmessage = (next) => setStep(next)
commands.awaitInitialization(channel as any).catch(() => undefined)
splash.style.animation = "none"
splash.style.animationPlayState = "paused"
splash.style.opacity = currentOpacity
createEffect(() => {
if (phase() !== "sqlite_waiting") return
requestAnimationFrame(() => {
splash.style.transition = "opacity 0.3s ease"
requestAnimationFrame(() => {
splash.style.opacity = "1"
setLine(0)
setPercent(0)
const timers = delays.map((ms, i) => setTimeout(() => setLine(i + 1), ms))
let stop: (() => void) | undefined
let active = true
void events.sqliteMigrationProgress
.listen((e) => {
if (e.payload.type === "InProgress") setPercent(Math.max(0, Math.min(100, e.payload.value)))
if (e.payload.type === "Done") setPercent(100)
})
.then((unlisten) => {
if (active) {
stop = unlisten
return
}
unlisten()
})
.catch(() => undefined)
onCleanup(() => {
active = false
timers.forEach(clearTimeout)
stop?.()
})
})
createEffect(() => {
if (phase() !== "done") return
const timer = setTimeout(() => events.loadingWindowComplete.emit(null), 1000)
onCleanup(() => clearTimeout(timer))
})
const status = createMemo(() => {
if (phase() === "done") return "All done"
if (phase() === "sqlite_waiting") return lines[line()]
return "Just a moment..."
})
return (
<MetaProvider>
<div class="w-screen h-screen bg-background-base flex items-center justify-center">
<Font />
<div class="flex flex-col items-center gap-10">
<Splash ref={splash} class="h-25 animate-[pulse-splash_2s_ease-in-out_infinite]" />
<span class="text-text-base">
<Switch fallback="Just a moment...">
<Match when={state()?.phase === "done"}>
{(_) => {
onMount(() => {
setTimeout(() => events.loadingWindowComplete.emit(null), 1000)
})
return "All done"
}}
</Match>
<Match when={state()?.phase === "sqlite_waiting"}>
{(_) => {
const textItems = [
"Just a moment...",
"Migrating your database",
"This could take a couple of minutes",
]
const [textIndex, setTextIndex] = createSignal(0)
onMount(async () => {
await new Promise((res) => setTimeout(res, 3000))
setTextIndex(1)
await new Promise((res) => setTimeout(res, 6000))
setTextIndex(2)
})
return <>{textItems[textIndex()]}</>
}}
</Match>
</Switch>
</span>
<div class="flex flex-col items-center gap-11">
<Splash class="w-20 h-25 opacity-15" />
<div class="w-60 flex flex-col items-center gap-4" aria-live="polite">
<span class="w-full overflow-hidden text-center text-ellipsis whitespace-nowrap text-text-strong text-14-normal">
{status()}
</span>
<Progress
value={value()}
class="w-20 [&_[data-slot='progress-track']]:h-1 [&_[data-slot='progress-track']]:border-0 [&_[data-slot='progress-track']]:rounded-none [&_[data-slot='progress-track']]:bg-surface-weak [&_[data-slot='progress-fill']]:rounded-none [&_[data-slot='progress-fill']]:bg-icon-warning-base"
aria-label="Database migration progress"
getValueLabel={({ value }) => `${Math.round(value)}%`}
/>
</div>
</div>
</div>
</MetaProvider>
-10
View File
@@ -5,13 +5,3 @@ button#decorum-tb-close,
div[data-tauri-decorum-tb] {
height: calc(var(--spacing) * 10) !important;
}
@keyframes pulse-splash {
0%,
100% {
opacity: 0.1;
}
50% {
opacity: 0.3;
}
}
+1 -1
View File
@@ -82,7 +82,7 @@ export namespace ModelsDev {
status: z.enum(["alpha", "beta", "deprecated"]).optional(),
options: z.record(z.string(), z.any()),
headers: z.record(z.string(), z.string()).optional(),
provider: z.object({ npm: z.string(), api: z.string() }).optional(),
provider: z.object({ npm: z.string().optional(), api: z.string().optional() }).optional(),
variants: z.record(z.string(), z.record(z.string(), z.any())).optional(),
})
export type Model = z.infer<typeof Model>
+6 -6
View File
@@ -38,7 +38,7 @@ export const EditTool = Tool.define("edit", {
}
if (params.oldString === params.newString) {
throw new Error("oldString and newString must be different")
throw new Error("No changes to apply: oldString and newString are identical.")
}
const filePath = path.isAbsolute(params.filePath) ? params.filePath : path.join(Instance.directory, params.filePath)
@@ -617,7 +617,7 @@ export function trimDiff(diff: string): string {
export function replace(content: string, oldString: string, newString: string, replaceAll = false): string {
if (oldString === newString) {
throw new Error("oldString and newString must be different")
throw new Error("No changes to apply: oldString and newString are identical.")
}
let notFound = true
@@ -647,9 +647,9 @@ export function replace(content: string, oldString: string, newString: string, r
}
if (notFound) {
throw new Error("oldString not found in content")
throw new Error(
"Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings.",
)
}
throw new Error(
"Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match.",
)
throw new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")
}
+3 -1
View File
@@ -62,7 +62,9 @@ export const GlobTool = Tool.define("glob", {
output.push(...files.map((f) => f.path))
if (truncated) {
output.push("")
output.push("(Results are truncated. Consider using a more specific path or pattern.)")
output.push(
`(Results are truncated: showing first ${limit} results. Consider using a more specific path or pattern.)`,
)
}
}
+6 -3
View File
@@ -109,7 +109,8 @@ export const GrepTool = Tool.define("grep", {
}
}
const outputLines = [`Found ${finalMatches.length} matches`]
const totalMatches = matches.length
const outputLines = [`Found ${totalMatches} matches${truncated ? ` (showing first ${limit})` : ""}`]
let currentFile = ""
for (const match of finalMatches) {
@@ -127,7 +128,9 @@ export const GrepTool = Tool.define("grep", {
if (truncated) {
outputLines.push("")
outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)")
outputLines.push(
`(Results truncated: showing ${limit} of ${totalMatches} matches (${totalMatches - limit} hidden). Consider using a more specific path or pattern.)`,
)
}
if (hasErrors) {
@@ -138,7 +141,7 @@ export const GrepTool = Tool.define("grep", {
return {
title: params.pattern,
metadata: {
matches: finalMatches.length,
matches: totalMatches,
truncated,
},
output: outputLines.join("\n"),
+4 -4
View File
@@ -1573,8 +1573,8 @@ export type ProviderConfig = {
[key: string]: string
}
provider?: {
npm: string
api: string
npm?: string
api?: string
}
/**
* Variant-specific configuration
@@ -4096,8 +4096,8 @@ export type ProviderListResponses = {
[key: string]: string
}
provider?: {
npm: string
api: string
npm?: string
api?: string
}
variants?: {
[key: string]: {
+1
View File
@@ -38,6 +38,7 @@
"./accordion": "./src/components/accordion.tsx",
"./sticky-accordion-header": "./src/components/sticky-accordion-header.tsx",
"./resize-handle": "./src/components/resize-handle.tsx",
"./progress": "./src/components/progress.tsx",
"./progress-circle": "./src/components/progress-circle.tsx",
"./tag": "./src/components/tag.tsx",
"./typewriter": "./src/components/typewriter.tsx",
+13 -2
View File
@@ -318,7 +318,7 @@ export function Code<T>(props: CodeProps<T>) {
const needle = query.toLowerCase()
const out: Range[] = []
const cols = Array.from(root.querySelectorAll("[data-column-content]")).filter(
const cols = Array.from(root.querySelectorAll("[data-content] [data-line], [data-column-content]")).filter(
(node): node is HTMLElement => node instanceof HTMLElement,
)
@@ -537,17 +537,28 @@ export function Code<T>(props: CodeProps<T>) {
node.removeAttribute("data-comment-selected")
}
const annotations = Array.from(root.querySelectorAll("[data-line-annotation]")).filter(
(node): node is HTMLElement => node instanceof HTMLElement,
)
for (const range of ranges) {
const start = Math.max(1, Math.min(range.start, range.end))
const end = Math.max(range.start, range.end)
for (let line = start; line <= end; line++) {
const nodes = Array.from(root.querySelectorAll(`[data-line="${line}"]`))
const nodes = Array.from(root.querySelectorAll(`[data-line="${line}"], [data-column-number="${line}"]`))
for (const node of nodes) {
if (!(node instanceof HTMLElement)) continue
node.setAttribute("data-comment-selected", "")
}
}
for (const annotation of annotations) {
const line = parseInt(annotation.dataset.lineAnnotation?.split(",")[1] ?? "", 10)
if (Number.isNaN(line)) continue
if (line < start || line > end) continue
annotation.setAttribute("data-comment-selected", "")
}
}
}
+58 -28
View File
@@ -1,8 +1,9 @@
import { DIFFS_TAG_NAME, FileDiff, type SelectedLineRange } from "@pierre/diffs"
import { DIFFS_TAG_NAME, FileDiff, type SelectedLineRange, VirtualizedFileDiff } from "@pierre/diffs"
import { PreloadMultiFileDiffResult } from "@pierre/diffs/ssr"
import { createEffect, onCleanup, onMount, Show, splitProps } from "solid-js"
import { Dynamic, isServer } from "solid-js/web"
import { createDefaultOptions, styleVariables, type DiffProps } from "../pierre"
import { acquireVirtualizer, virtualMetrics } from "../pierre/virtualizer"
import { useWorkerPool } from "../context/worker-pool"
export type SSRDiffProps<T = {}> = DiffProps<T> & {
@@ -24,10 +25,21 @@ export function Diff<T>(props: SSRDiffProps<T>) {
const workerPool = useWorkerPool(props.diffStyle)
let fileDiffInstance: FileDiff<T> | undefined
let sharedVirtualizer: NonNullable<ReturnType<typeof acquireVirtualizer>> | undefined
const cleanupFunctions: Array<() => void> = []
const getRoot = () => fileDiffRef?.shadowRoot ?? undefined
const getVirtualizer = () => {
if (sharedVirtualizer) return sharedVirtualizer.virtualizer
const result = acquireVirtualizer(container)
if (!result) return
sharedVirtualizer = result
return result.virtualizer
}
const applyScheme = () => {
const scheme = document.documentElement.dataset.colorScheme
if (scheme === "dark" || scheme === "light") {
@@ -70,10 +82,10 @@ export function Diff<T>(props: SSRDiffProps<T>) {
const root = getRoot()
if (!root) return
const diffs = root.querySelector("[data-diffs]")
const diffs = root.querySelector("[data-diff]")
if (!(diffs instanceof HTMLElement)) return
const split = diffs.dataset.type === "split"
const split = diffs.dataset.diffType === "split"
const start = rowIndex(root, split, range.start, range.side)
const end = rowIndex(root, split, range.end, range.endSide ?? range.side)
@@ -132,15 +144,19 @@ export function Diff<T>(props: SSRDiffProps<T>) {
node.removeAttribute("data-comment-selected")
}
const diffs = root.querySelector("[data-diffs]")
const diffs = root.querySelector("[data-diff]")
if (!(diffs instanceof HTMLElement)) return
const split = diffs.dataset.type === "split"
const split = diffs.dataset.diffType === "split"
const code = Array.from(diffs.querySelectorAll("[data-code]")).filter(
const rows = Array.from(diffs.querySelectorAll("[data-line-index]")).filter(
(node): node is HTMLElement => node instanceof HTMLElement,
)
if (rows.length === 0) return
const annotations = Array.from(diffs.querySelectorAll("[data-line-annotation]")).filter(
(node): node is HTMLElement => node instanceof HTMLElement,
)
if (code.length === 0) return
const lineIndex = (element: HTMLElement) => {
const raw = element.dataset.lineIndex
@@ -183,19 +199,18 @@ export function Diff<T>(props: SSRDiffProps<T>) {
const first = Math.min(start, end)
const last = Math.max(start, end)
for (const block of code) {
for (const element of Array.from(block.children)) {
if (!(element instanceof HTMLElement)) continue
const idx = lineIndex(element)
if (idx === undefined) continue
if (idx > last) break
if (idx < first) continue
element.setAttribute("data-comment-selected", "")
const next = element.nextSibling
if (next instanceof HTMLElement && next.hasAttribute("data-line-annotation")) {
next.setAttribute("data-comment-selected", "")
}
}
for (const row of rows) {
const idx = lineIndex(row)
if (idx === undefined) continue
if (idx < first || idx > last) continue
row.setAttribute("data-comment-selected", "")
}
for (const annotation of annotations) {
const idx = parseInt(annotation.dataset.lineAnnotation?.split(",")[1] ?? "", 10)
if (Number.isNaN(idx)) continue
if (idx < first || idx > last) continue
annotation.setAttribute("data-comment-selected", "")
}
}
}
@@ -212,14 +227,27 @@ export function Diff<T>(props: SSRDiffProps<T>) {
onCleanup(() => monitor.disconnect())
}
fileDiffInstance = new FileDiff<T>(
{
...createDefaultOptions(props.diffStyle),
...others,
...props.preloadedDiff,
},
workerPool,
)
const virtualizer = getVirtualizer()
fileDiffInstance = virtualizer
? new VirtualizedFileDiff<T>(
{
...createDefaultOptions(props.diffStyle),
...others,
...props.preloadedDiff,
},
virtualizer,
virtualMetrics,
workerPool,
)
: new FileDiff<T>(
{
...createDefaultOptions(props.diffStyle),
...others,
...props.preloadedDiff,
},
workerPool,
)
// @ts-expect-error - fileContainer is private but needed for SSR hydration
fileDiffInstance.fileContainer = fileDiffRef
fileDiffInstance.hydrate({
@@ -273,6 +301,8 @@ export function Diff<T>(props: SSRDiffProps<T>) {
// Clean up FileDiff event handlers and dispose SolidJS components
fileDiffInstance?.cleanUp()
cleanupFunctions.forEach((dispose) => dispose())
sharedVirtualizer?.release()
sharedVirtualizer = undefined
})
return (
+41 -21
View File
@@ -1,8 +1,9 @@
import { checksum } from "@opencode-ai/util/encode"
import { FileDiff, type SelectedLineRange } from "@pierre/diffs"
import { FileDiff, type SelectedLineRange, VirtualizedFileDiff } from "@pierre/diffs"
import { createMediaQuery } from "@solid-primitives/media"
import { createEffect, createMemo, createSignal, onCleanup, splitProps } from "solid-js"
import { createDefaultOptions, type DiffProps, styleVariables } from "../pierre"
import { acquireVirtualizer, virtualMetrics } from "../pierre/virtualizer"
import { getWorkerPool } from "../pierre/worker"
type SelectionSide = "additions" | "deletions"
@@ -52,6 +53,7 @@ function findSide(node: Node | null): SelectionSide | undefined {
export function Diff<T>(props: DiffProps<T>) {
let container!: HTMLDivElement
let observer: MutationObserver | undefined
let sharedVirtualizer: NonNullable<ReturnType<typeof acquireVirtualizer>> | undefined
let renderToken = 0
let selectionFrame: number | undefined
let dragFrame: number | undefined
@@ -92,6 +94,16 @@ export function Diff<T>(props: DiffProps<T>) {
const [current, setCurrent] = createSignal<FileDiff<T> | undefined>(undefined)
const [rendered, setRendered] = createSignal(0)
const getVirtualizer = () => {
if (sharedVirtualizer) return sharedVirtualizer.virtualizer
const result = acquireVirtualizer(container)
if (!result) return
sharedVirtualizer = result
return result.virtualizer
}
const getRoot = () => {
const host = container.querySelector("diffs-container")
if (!(host instanceof HTMLElement)) return
@@ -147,10 +159,10 @@ export function Diff<T>(props: DiffProps<T>) {
const root = getRoot()
if (!root) return
const diffs = root.querySelector("[data-diffs]")
const diffs = root.querySelector("[data-diff]")
if (!(diffs instanceof HTMLElement)) return
const split = diffs.dataset.type === "split"
const split = diffs.dataset.diffType === "split"
const start = rowIndex(root, split, range.start, range.side)
const end = rowIndex(root, split, range.end, range.endSide ?? range.side)
@@ -261,15 +273,19 @@ export function Diff<T>(props: DiffProps<T>) {
node.removeAttribute("data-comment-selected")
}
const diffs = root.querySelector("[data-diffs]")
const diffs = root.querySelector("[data-diff]")
if (!(diffs instanceof HTMLElement)) return
const split = diffs.dataset.type === "split"
const split = diffs.dataset.diffType === "split"
const code = Array.from(diffs.querySelectorAll("[data-code]")).filter(
const rows = Array.from(diffs.querySelectorAll("[data-line-index]")).filter(
(node): node is HTMLElement => node instanceof HTMLElement,
)
if (rows.length === 0) return
const annotations = Array.from(diffs.querySelectorAll("[data-line-annotation]")).filter(
(node): node is HTMLElement => node instanceof HTMLElement,
)
if (code.length === 0) return
for (const range of ranges) {
const start = rowIndex(root, split, range.start, range.side)
@@ -285,19 +301,18 @@ export function Diff<T>(props: DiffProps<T>) {
const first = Math.min(start, end)
const last = Math.max(start, end)
for (const block of code) {
for (const element of Array.from(block.children)) {
if (!(element instanceof HTMLElement)) continue
const idx = lineIndex(split, element)
if (idx === undefined) continue
if (idx > last) break
if (idx < first) continue
element.setAttribute("data-comment-selected", "")
const next = element.nextSibling
if (next instanceof HTMLElement && next.hasAttribute("data-line-annotation")) {
next.setAttribute("data-comment-selected", "")
}
}
for (const row of rows) {
const idx = lineIndex(split, row)
if (idx === undefined) continue
if (idx < first || idx > last) continue
row.setAttribute("data-comment-selected", "")
}
for (const annotation of annotations) {
const idx = parseInt(annotation.dataset.lineAnnotation?.split(",")[1] ?? "", 10)
if (Number.isNaN(idx)) continue
if (idx < first || idx > last) continue
annotation.setAttribute("data-comment-selected", "")
}
}
}
@@ -514,12 +529,15 @@ export function Diff<T>(props: DiffProps<T>) {
createEffect(() => {
const opts = options()
const workerPool = getWorkerPool(props.diffStyle)
const virtualizer = getVirtualizer()
const annotations = local.annotations
const beforeContents = typeof local.before?.contents === "string" ? local.before.contents : ""
const afterContents = typeof local.after?.contents === "string" ? local.after.contents : ""
instance?.cleanUp()
instance = new FileDiff<T>(opts, workerPool)
instance = virtualizer
? new VirtualizedFileDiff<T>(opts, virtualizer, virtualMetrics, workerPool)
: new FileDiff<T>(opts, workerPool)
setCurrent(instance)
container.innerHTML = ""
@@ -606,6 +624,8 @@ export function Diff<T>(props: DiffProps<T>) {
instance?.cleanUp()
setCurrent(undefined)
sharedVirtualizer?.release()
sharedVirtualizer = undefined
})
return <div data-component="diff" style={styleVariables} ref={container} />
+63
View File
@@ -0,0 +1,63 @@
[data-component="progress"] {
display: flex;
flex-direction: column;
gap: 4px;
[data-slot="progress-header"] {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
[data-slot="progress-label"],
[data-slot="progress-value-label"] {
font-family: var(--font-family-sans);
font-size: var(--font-size-small);
font-weight: var(--font-weight-regular);
line-height: var(--line-height-large);
letter-spacing: var(--letter-spacing-normal);
}
[data-slot="progress-label"] {
color: var(--text-base);
}
[data-slot="progress-value-label"] {
color: var(--text-weak);
font-variant-numeric: tabular-nums;
}
[data-slot="progress-track"] {
position: relative;
width: 100%;
height: 8px;
overflow: hidden;
border-radius: 999px;
border: 1px solid var(--border-weak-base);
background-color: var(--surface-base);
}
[data-slot="progress-fill"] {
height: 100%;
width: var(--kb-progress-fill-width);
border-radius: inherit;
background-color: var(--border-active);
transition: width 200ms ease;
}
&[data-indeterminate] [data-slot="progress-fill"] {
width: 35%;
animation: progress-indeterminate 1.3s ease-in-out infinite;
}
}
@keyframes progress-indeterminate {
from {
transform: translateX(-100%);
}
to {
transform: translateX(300%);
}
}
+39
View File
@@ -0,0 +1,39 @@
import { Progress as Kobalte } from "@kobalte/core/progress"
import { Show, splitProps } from "solid-js"
import type { ComponentProps, ParentProps } from "solid-js"
export interface ProgressProps extends ParentProps<ComponentProps<typeof Kobalte>> {
hideLabel?: boolean
showValueLabel?: boolean
}
export function Progress(props: ProgressProps) {
const [local, others] = splitProps(props, ["children", "class", "classList", "hideLabel", "showValueLabel"])
return (
<Kobalte
{...others}
data-component="progress"
classList={{
...(local.classList ?? {}),
[local.class ?? ""]: !!local.class,
}}
>
<Show when={local.children || local.showValueLabel}>
<div data-slot="progress-header">
<Show when={local.children}>
<Kobalte.Label data-slot="progress-label" classList={{ "sr-only": local.hideLabel }}>
{local.children}
</Kobalte.Label>
</Show>
<Show when={local.showValueLabel}>
<Kobalte.ValueLabel data-slot="progress-value-label" />
</Show>
</div>
</Show>
<Kobalte.Track data-slot="progress-track">
<Kobalte.Fill data-slot="progress-fill" />
</Kobalte.Track>
</Kobalte>
)
}
+1 -1
View File
@@ -10,7 +10,7 @@ registerCustomTheme("Kilo", () => {
return Promise.resolve({
name: "Kilo",
colors: {
"editor.background": "transparent",
"editor.background": "var(--color-background-stronger)",
"editor.foreground": "var(--text-base)",
"gitDecoration.addedResourceForeground": "var(--syntax-diff-add)",
"gitDecoration.deletedResourceForeground": "var(--syntax-diff-delete)",
+22 -48
View File
@@ -13,7 +13,7 @@ export type DiffProps<T = {}> = FileDiffOptions<T> & {
}
const unsafeCSS = `
[data-diffs] {
[data-diff] {
--diffs-bg: light-dark(var(--diffs-light-bg), var(--diffs-dark-bg));
--diffs-bg-buffer: var(--diffs-bg-buffer-override, light-dark( color-mix(in lab, var(--diffs-bg) 92%, var(--diffs-mixer)), color-mix(in lab, var(--diffs-bg) 92%, var(--diffs-mixer))));
--diffs-bg-hover: var(--diffs-bg-hover-override, light-dark( color-mix(in lab, var(--diffs-bg) 97%, var(--diffs-mixer)), color-mix(in lab, var(--diffs-bg) 91%, var(--diffs-mixer))));
@@ -44,7 +44,7 @@ const unsafeCSS = `
--diffs-bg-selection-text: rgb(from var(--surface-warning-strong) r g b / 0.2);
}
:host([data-color-scheme='dark']) [data-diffs] {
:host([data-color-scheme='dark']) [data-diff] {
--diffs-selection-number-fg: #fdfbfb;
--diffs-bg-selection: var(--diffs-bg-selection-override, rgb(from var(--solaris-dark-6) r g b / 0.65));
--diffs-bg-selection-number: var(
@@ -53,7 +53,7 @@ const unsafeCSS = `
);
}
[data-diffs] ::selection {
[data-diff] ::selection {
background-color: var(--diffs-bg-selection-text);
}
@@ -65,61 +65,48 @@ const unsafeCSS = `
background-color: rgb(from var(--surface-warning-strong) r g b / 0.55);
}
[data-diffs] [data-comment-selected]:not([data-selected-line]) [data-column-content] {
[data-diff] [data-line][data-comment-selected]:not([data-selected-line]) {
box-shadow: inset 0 0 0 9999px var(--diffs-bg-selection);
}
[data-diffs] [data-comment-selected]:not([data-selected-line]) [data-column-number] {
[data-diff] [data-column-number][data-comment-selected]:not([data-selected-line]) {
box-shadow: inset 0 0 0 9999px var(--diffs-bg-selection-number);
color: var(--diffs-selection-number-fg);
}
[data-diffs] [data-selected-line] {
[data-diff] [data-line-annotation][data-comment-selected]:not([data-selected-line]) [data-annotation-content] {
box-shadow: inset 0 0 0 9999px var(--diffs-bg-selection);
}
[data-diff] [data-line][data-selected-line] {
background-color: var(--diffs-bg-selection);
box-shadow: inset 2px 0 0 var(--diffs-selection-border);
}
[data-diffs] [data-selected-line] [data-column-number] {
[data-diff] [data-column-number][data-selected-line] {
background-color: var(--diffs-bg-selection-number);
color: var(--diffs-selection-number-fg);
}
[data-diffs] [data-line-type='context'][data-selected-line] [data-column-number],
[data-diffs] [data-line-type='context-expanded'][data-selected-line] [data-column-number],
[data-diffs] [data-line-type='change-addition'][data-selected-line] [data-column-number],
[data-diffs] [data-line-type='change-deletion'][data-selected-line] [data-column-number] {
[data-diff] [data-column-number][data-line-type='context'][data-selected-line],
[data-diff] [data-column-number][data-line-type='context-expanded'][data-selected-line],
[data-diff] [data-column-number][data-line-type='change-addition'][data-selected-line],
[data-diff] [data-column-number][data-line-type='change-deletion'][data-selected-line] {
color: var(--diffs-selection-number-fg);
}
/* The deletion word-diff emphasis is stronger than additions; soften it while selected so the selection highlight reads consistently. */
[data-diffs] [data-line-type='change-deletion'][data-selected-line] {
[data-diff] [data-line][data-line-type='change-deletion'][data-selected-line] {
--diffs-bg-deletion-emphasis: light-dark(
rgb(from var(--diffs-deletion-base) r g b / 0.07),
rgb(from var(--diffs-deletion-base) r g b / 0.1)
);
}
[data-diffs-header],
[data-diffs] {
[data-separator-wrapper] {
margin: 0 !important;
border-radius: 0 !important;
}
[data-expand-button] {
width: 6.5ch !important;
height: 24px !important;
justify-content: end !important;
padding-left: 3ch !important;
padding-inline: 1ch !important;
}
[data-separator-multi-button] {
grid-template-rows: 10px 10px !important;
[data-expand-button] {
height: 12px !important;
}
}
[data-separator-content] {
height: 24px !important;
[data-diff-header],
[data-diff] {
[data-separator] {
height: 24px;
}
[data-column-number] {
background-color: var(--background-stronger);
@@ -146,28 +133,15 @@ export function createDefaultOptions<T>(style: FileDiffOptions<T>["diffStyle"])
overflow: "wrap",
diffStyle: style ?? "unified",
diffIndicators: "bars",
lineHoverHighlight: "both",
disableBackground: false,
expansionLineCount: 20,
hunkSeparators: "line-info-basic",
lineDiffType: style === "split" ? "word-alt" : "none",
maxLineDiffLength: 1000,
maxLineLengthForHighlighting: 1000,
disableFileHeader: true,
unsafeCSS,
// hunkSeparators(hunkData: HunkData) {
// const fragment = document.createDocumentFragment()
// const numCol = document.createElement("div")
// numCol.innerHTML = `<svg data-slot="diff-hunk-separator-line-number-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M8.97978 14.0204L8.62623 13.6668L9.33334 12.9597L9.68689 13.3133L9.33333 13.6668L8.97978 14.0204ZM12 16.3335L12.3535 16.6871L12 17.0406L11.6464 16.687L12 16.3335ZM14.3131 13.3133L14.6667 12.9597L15.3738 13.6668L15.0202 14.0204L14.6667 13.6668L14.3131 13.3133ZM12.5 16.0002V16.5002H11.5V16.0002H12H12.5ZM9.33333 13.6668L9.68689 13.3133L12.3535 15.9799L12 16.3335L11.6464 16.687L8.97978 14.0204L9.33333 13.6668ZM12 16.3335L11.6464 15.9799L14.3131 13.3133L14.6667 13.6668L15.0202 14.0204L12.3535 16.6871L12 16.3335ZM6.5 8.00016V7.50016H8.5V8.00016V8.50016H6.5V8.00016ZM9.5 8.00016V7.50016H11.5V8.00016V8.50016H9.5V8.00016ZM12.5 8.00016V7.50016H14.5V8.00016V8.50016H12.5V8.00016ZM15.5 8.00016V7.50016H17.5V8.00016V8.50016H15.5V8.00016ZM12 10.5002H12.5V16.0002H12H11.5V10.5002H12Z" fill="currentColor"/></svg> `
// numCol.dataset["slot"] = "diff-hunk-separator-line-number"
// fragment.appendChild(numCol)
// const contentCol = document.createElement("div")
// contentCol.dataset["slot"] = "diff-hunk-separator-content"
// const span = document.createElement("span")
// span.dataset["slot"] = "diff-hunk-separator-content-span"
// span.textContent = `${hunkData.lines} unmodified lines`
// contentCol.appendChild(span)
// fragment.appendChild(contentCol)
// return fragment
// },
} as const
}
+76
View File
@@ -0,0 +1,76 @@
import { type VirtualFileMetrics, Virtualizer } from "@pierre/diffs"
type Target = {
key: Document | HTMLElement
root: Document | HTMLElement
content: HTMLElement | undefined
}
type Entry = {
virtualizer: Virtualizer
refs: number
}
const cache = new WeakMap<Document | HTMLElement, Entry>()
export const virtualMetrics: Partial<VirtualFileMetrics> = {
lineHeight: 24,
hunkSeparatorHeight: 24,
fileGap: 0,
}
function target(container: HTMLElement): Target | undefined {
if (typeof document === "undefined") return
const root = container.closest("[data-component='session-review']")
if (root instanceof HTMLElement) {
const content = root.querySelector("[data-slot='session-review-container']")
return {
key: root,
root,
content: content instanceof HTMLElement ? content : undefined,
}
}
return {
key: document,
root: document,
content: undefined,
}
}
export function acquireVirtualizer(container: HTMLElement) {
const resolved = target(container)
if (!resolved) return
let entry = cache.get(resolved.key)
if (!entry) {
const virtualizer = new Virtualizer()
virtualizer.setup(resolved.root, resolved.content)
entry = {
virtualizer,
refs: 0,
}
cache.set(resolved.key, entry)
}
entry.refs += 1
let done = false
return {
virtualizer: entry.virtualizer,
release() {
if (done) return
done = true
const current = cache.get(resolved.key)
if (!current) return
current.refs -= 1
if (current.refs > 0) return
current.virtualizer.cleanUp()
cache.delete(resolved.key)
},
}
}
+1
View File
@@ -21,6 +21,7 @@ function createPool(lineDiffType: "none" | "word-alt") {
{
theme: "Kilo", // kilocode_change
lineDiffType,
preferredHighlighter: "shiki-wasm",
},
)
+1
View File
@@ -36,6 +36,7 @@
@import "../components/message-part.css" layer(components);
@import "../components/message-nav.css" layer(components);
@import "../components/popover.css" layer(components);
@import "../components/progress.css" layer(components);
@import "../components/progress-circle.css" layer(components);
@import "../components/radio-group.css" layer(components);
@import "../components/resize-handle.css" layer(components);
+1 -1
View File
@@ -510,7 +510,7 @@
--icon-success-base: var(--apple-dark-7);
--icon-success-hover: var(--apple-dark-8);
--icon-success-active: var(--apple-dark-11);
--icon-warning-base: var(--amber-dark-7);
--icon-warning-base: var(--amber-dark-9);
--icon-warning-hover: var(--amber-dark-8);
--icon-warning-active: var(--amber-dark-11);
--icon-critical-base: var(--ember-dark-9);
+1 -1
View File
@@ -444,7 +444,7 @@
"icon-success-base": "var(--apple-dark-9)",
"icon-success-hover": "var(--apple-dark-10)",
"icon-success-active": "var(--apple-dark-11)",
"icon-warning-base": "var(--amber-dark-7)",
"icon-warning-base": "var(--amber-dark-9)",
"icon-warning-hover": "var(--amber-dark-8)",
"icon-warning-active": "var(--amber-dark-11)",
"icon-critical-base": "var(--ember-dark-9)",