Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
build(desktop): package reproducible GPUI sidecars on every platform
Richie McIlroy81805af68578
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lockindex c1efba9f3..7c0f28053 100644--- a/apps/desktop-gpui/Cargo.lock+++ b/apps/desktop-gpui/Cargo.lock@@ -521,8 +521,6 @@ version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39"dependencies = [- "async-fs",- "async-net","enumflags2","futures-channel","futures-util",@@ -1480,6 +1478,7 @@ dependencies = ["cap-camera","cap-camera-effects","cap-editor",+ "cap-enc-ffmpeg","cap-export","cap-project","cap-recording",@@ -1501,6 +1500,7 @@ dependencies = ["gpui_platform","gpui_tokio","image 0.25.10",+ "jpeg-decoder","kameo","libc","md-5",@@ -1512,6 +1512,7 @@ dependencies = ["reqwest 0.12.28","rfd","scap-targets",+ "semver","serde","serde_json","sha2",diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.tomlindex d414eb36f..8d00a8f39 100644--- a/apps/desktop-gpui/Cargo.toml+++ b/apps/desktop-gpui/Cargo.toml@@ -50,6 +50,7 @@ cpal = { git = "https://github.com/CapSoftware/cpal", rev = "6013cb5f8bd3" }# The actual recording engine -- the same studio/instant actors the Tauri app# drives. Drags in the ffmpeg encode stack; that is the point.cap-recording = { path = "../../crates/recording" }+cap-enc-ffmpeg = { path = "../../crates/enc-ffmpeg" }# Already in the tree through cap-recording; direct so the camera draw bench# can construct `NativeCameraFrame.timestamp` for its synthetic frames.cap-timestamp = { path = "../../crates/timestamp" }@@ -93,6 +94,7 @@ ffmpeg = { package = "ffmpeg-next", git = "https://github.com/CapSoftware/rust-f# the app ships as webp; features are additive, so enabling it here does not# move gpui's own pin.image = { version = "0.25.1", default-features = false, features = ["jpeg", "png", "webp"] }+jpeg-decoder = "0.3"smallvec = "1"# Grapheme boundaries for `ui::TextInput`: Backspace deletes a user-perceived# character, not a `char`, so a flag emoji or a combining accent goes in one@@ -114,8 +116,9 @@ chrono = "0.4"# Read the Tauri app's settings store so both apps share one recordings library.serde_json = "1"serde = { version = "1", features = ["derive"] }+semver = "1"base64 = "0.22"-rfd = "0.15"+rfd = { version = "0.15", default-features = false, features = ["xdg-portal", "tokio"] }# The screenshot export compositor (`src/screenshot_export.rs`): the canvas-2d# work `renderScreenshotExportCanvas` does in the webview -- shape rasterizing,# text, and the share fingerprint. All three are already in this lockfile@@ -166,6 +169,9 @@ libc = "0.2"raw-window-handle = "0.6"windows-sys = { version = "0.59", features = ["Win32_Foundation",+ "Win32_Security",+ "Win32_System_SystemInformation",+ "Win32_System_Threading","Win32_UI_WindowsAndMessaging",] }diff --git a/apps/desktop-gpui/patches/zed-gpui.patch b/apps/desktop-gpui/patches/zed-gpui.patchnew file mode 100644index 000000000..f5924044c--- /dev/null+++ b/apps/desktop-gpui/patches/zed-gpui.patch@@ -0,0 +1,365 @@+diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs+index afb2171476..6cc35624a4 100644+--- a/crates/gpui/src/scene.rs++++ b/crates/gpui/src/scene.rs+@@ -830,0 +831,4 @@ pub struct PaintSurface {++ pub corner_radii: Corners<ScaledPixels>,++ /// Normalized sub-rect of the source texture to sample, for object-fit++ /// crops. The full texture is `(0,0)..(1,1)`.++ pub source_uv: Bounds<f32>,+diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs+index 0480dc9574..484179d778 100644+--- a/crates/gpui/src/window.rs++++ b/crates/gpui/src/window.rs+@@ -1519,0 +1520 @@ impl Window {++ let will_draw = invalidator.is_dirty() || request_frame_options.force_render;+@@ -1526 +1527,4 @@ impl Window {+- Some(Duration::from_micros(33333))++ // The skip below returns before the dirty check, so without++ // this an unrelated pending next-frame callback caps fresh++ // content at 30fps -- video playback in an unfocused window.++ (!will_draw).then_some(Duration::from_micros(33333))+@@ -4544,0 +4549,18 @@ impl Window {++ self.paint_surface_fitted(bounds, bounds, Corners::default(), image_buffer);++ }++++ /// [`Self::paint_surface`] for object-fit layouts: paint the `visible`++ /// rect of a surface whose fitted content box is `fitted` (equal or++ /// larger, e.g. `ObjectFit::Cover`), cropping via the surface's source++ /// UVs so `corner_radii` round the element's actual corners — the same++ /// contract as [`Self::paint_image_fitted`].++ ///++ /// This method should only be called as part of the paint phase of element drawing.++ #[cfg(target_os = "macos")]++ pub fn paint_surface_fitted(++ &mut self,++ visible: Bounds<Pixels>,++ fitted: Bounds<Pixels>,++ corner_radii: Corners<Pixels>,++ image_buffer: CVPixelBuffer,++ ) {+@@ -4549 +4571,20 @@ impl Window {+- let bounds = self.snap_bounds(bounds);++ let source_uv = if visible == fitted {++ Bounds {++ origin: point(0., 0.),++ size: size(1., 1.),++ }++ } else {++ let fitted_width = f32::from(fitted.size.width).max(1.0);++ let fitted_height = f32::from(fitted.size.height).max(1.0);++ Bounds {++ origin: point(++ (f32::from(visible.origin.x) - f32::from(fitted.origin.x)) / fitted_width,++ (f32::from(visible.origin.y) - f32::from(fitted.origin.y)) / fitted_height,++ ),++ size: size(++ f32::from(visible.size.width) / fitted_width,++ f32::from(visible.size.height) / fitted_height,++ ),++ }++ };++ let bounds = self.snap_bounds(visible);+@@ -4550,0 +4592 @@ impl Window {++ let corner_radii = corner_radii.scale(self.scale_factor());+@@ -4554,0 +4597,2 @@ impl Window {++ corner_radii,++ source_uv,+diff --git a/crates/gpui_macos/src/metal_renderer.rs b/crates/gpui_macos/src/metal_renderer.rs+index c93a383c38..11506dbb62 100644+--- a/crates/gpui_macos/src/metal_renderer.rs++++ b/crates/gpui_macos/src/metal_renderer.rs+@@ -10,3 +10,3 @@ use gpui::{+- AtlasTextureId, BackdropBlur, Background, Bounds, ContentMask, DevicePixels, DrawOrder,+- MonochromeSprite, PaintSurface, Path, Point, PolychromeSprite, PrimitiveBatch, Quad,+- ScaledPixels, Scene, Shadow, Size, Surface, Underline, point, size,++ AtlasTextureId, BackdropBlur, Background, Bounds, ContentMask, Corners, DevicePixels,++ DrawOrder, MonochromeSprite, PaintSurface, Path, Point, PolychromeSprite, PrimitiveBatch, Quad,++ ScaledPixels, Scene, Shadow, Size, Underline, point, size,+@@ -19,2 +19,3 @@ use core_video::{+- metal_texture::CVMetalTextureGetTexture, metal_texture_cache::CVMetalTextureCache,+- pixel_buffer::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,++ metal_texture::CVMetalTextureGetTexture,++ metal_texture_cache::CVMetalTextureCache,++ pixel_buffer::{kCVPixelFormatType_32BGRA, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange},+@@ -178,0 +180 @@ pub(crate) struct MetalRenderer {++ bgra_surfaces_pipeline_state: metal::RenderPipelineState,+@@ -393,0 +396,8 @@ impl MetalRenderer {++ let bgra_surfaces_pipeline_state = build_pipeline_state(++ &device,++ &library,++ "bgra_surfaces",++ "surface_vertex",++ "surface_bgra_fragment",++ MTLPixelFormat::BGRA8Unorm,++ );+@@ -422,0 +433 @@ impl MetalRenderer {++ bgra_surfaces_pipeline_state,+@@ -489,3 +500,7 @@ impl MetalRenderer {+- if self.path_intermediate_texture.as_ref().is_some_and(|texture| {+- texture.width() == size.width.0 as u64 && texture.height() == size.height.0 as u64+- }) {++ if self++ .path_intermediate_texture++ .as_ref()++ .is_some_and(|texture| {++ texture.width() == size.width.0 as u64 && texture.height() == size.height.0 as u64++ })++ {+@@ -1196,3 +1211 @@ impl MetalRenderer {+- texture+- .as_ref()+- .map_or(0, |t| t.width() * t.height() * 4)++ texture.as_ref().map_or(0, |t| t.width() * t.height() * 4)+@@ -1385,2 +1398 @@ impl MetalRenderer {+- let alloc: *mut objc::runtime::Object =+- msg_send![class!(MPSImageGaussianBlur), alloc];++ let alloc: *mut objc::runtime::Object = msg_send![class!(MPSImageGaussianBlur), alloc];+@@ -1444,2 +1456,4 @@ impl MetalRenderer {+- command_encoder+- .set_fragment_texture(BackdropBlurInputIndex::SourceTexture as u64, Some(source_texture));++ command_encoder.set_fragment_texture(++ BackdropBlurInputIndex::SourceTexture as u64,++ Some(source_texture),++ );+@@ -1898 +1911,0 @@ impl MetalRenderer {+- command_encoder.set_render_pipeline_state(&self.surfaces_pipeline_state);+@@ -1916,27 +1929,63 @@ impl MetalRenderer {+- assert_eq!(+- surface.image_buffer.get_pixel_format(),+- kCVPixelFormatType_420YpCbCr8BiPlanarFullRange+- );+-+- let y_texture = self+- .core_video_texture_cache+- .create_texture_from_image(+- surface.image_buffer.as_concrete_TypeRef(),+- None,+- MTLPixelFormat::R8Unorm,+- surface.image_buffer.get_width_of_plane(0),+- surface.image_buffer.get_height_of_plane(0),+- 0,+- )+- .unwrap();+- let cb_cr_texture = self+- .core_video_texture_cache+- .create_texture_from_image(+- surface.image_buffer.as_concrete_TypeRef(),+- None,+- MTLPixelFormat::RG8Unorm,+- surface.image_buffer.get_width_of_plane(1),+- surface.image_buffer.get_height_of_plane(1),+- 1,+- )+- .unwrap();++ // CVMetalTexture wrappers must outlive the draw call below; the++ // command encoder retains the underlying MTLTextures, but the++ // texture cache may recycle them once the wrapper is released.++ let pixel_format = surface.image_buffer.get_pixel_format();++ let _plane_textures = if pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange++ {++ command_encoder.set_render_pipeline_state(&self.surfaces_pipeline_state);++ let y_texture = self++ .core_video_texture_cache++ .create_texture_from_image(++ surface.image_buffer.as_concrete_TypeRef(),++ None,++ MTLPixelFormat::R8Unorm,++ surface.image_buffer.get_width_of_plane(0),++ surface.image_buffer.get_height_of_plane(0),++ 0,++ )++ .unwrap();++ let cb_cr_texture = self++ .core_video_texture_cache++ .create_texture_from_image(++ surface.image_buffer.as_concrete_TypeRef(),++ None,++ MTLPixelFormat::RG8Unorm,++ surface.image_buffer.get_width_of_plane(1),++ surface.image_buffer.get_height_of_plane(1),++ 1,++ )++ .unwrap();++ command_encoder.set_fragment_texture(SurfaceInputIndex::YTexture as u64, unsafe {++ let texture = CVMetalTextureGetTexture(y_texture.as_concrete_TypeRef());++ Some(metal::TextureRef::from_ptr(texture as *mut _))++ });++ command_encoder.set_fragment_texture(++ SurfaceInputIndex::CbCrTexture as u64,++ unsafe {++ let texture = CVMetalTextureGetTexture(cb_cr_texture.as_concrete_TypeRef());++ Some(metal::TextureRef::from_ptr(texture as *mut _))++ },++ );++ (y_texture, Some(cb_cr_texture))++ } else if pixel_format == kCVPixelFormatType_32BGRA {++ command_encoder.set_render_pipeline_state(&self.bgra_surfaces_pipeline_state);++ let color_texture = self++ .core_video_texture_cache++ .create_texture_from_image(++ surface.image_buffer.as_concrete_TypeRef(),++ None,++ MTLPixelFormat::BGRA8Unorm,++ surface.image_buffer.get_width(),++ surface.image_buffer.get_height(),++ 0,++ )++ .unwrap();++ command_encoder.set_fragment_texture(SurfaceInputIndex::YTexture as u64, unsafe {++ let texture = CVMetalTextureGetTexture(color_texture.as_concrete_TypeRef());++ Some(metal::TextureRef::from_ptr(texture as *mut _))++ });++ (color_texture, None)++ } else {++ log::error!("unsupported surface pixel format: {pixel_format:#x}");++ continue;++ };+@@ -1945 +1994 @@ impl MetalRenderer {+- let next_offset = *instance_offset + mem::size_of::<Surface>();++ let next_offset = *instance_offset + mem::size_of::<SurfaceBounds>();+@@ -1954,0 +2004,6 @@ impl MetalRenderer {++ // The fragment reads corner radii from the same instance record.++ command_encoder.set_fragment_buffer(++ SurfaceInputIndex::Surfaces as u64,++ Some(&instance_buffer.metal_buffer),++ *instance_offset as u64,++ );+@@ -1960,9 +2014,0 @@ impl MetalRenderer {+- // let y_texture = y_texture.get_texture().unwrap().+- command_encoder.set_fragment_texture(SurfaceInputIndex::YTexture as u64, unsafe {+- let texture = CVMetalTextureGetTexture(y_texture.as_concrete_TypeRef());+- Some(metal::TextureRef::from_ptr(texture as *mut _))+- });+- command_encoder.set_fragment_texture(SurfaceInputIndex::CbCrTexture as u64, unsafe {+- let texture = CVMetalTextureGetTexture(cb_cr_texture.as_concrete_TypeRef());+- Some(metal::TextureRef::from_ptr(texture as *mut _))+- });+@@ -1978,0 +2025,2 @@ impl MetalRenderer {++ corner_radii: surface.corner_radii,++ source_uv: surface.source_uv,+@@ -2246 +2294 @@ pub struct PathSprite {+-#[derive(Clone, Debug, Eq, PartialEq)]++#[derive(Clone, Debug, PartialEq)]+@@ -2250,0 +2299,2 @@ pub struct SurfaceBounds {++ pub corner_radii: Corners<ScaledPixels>,++ pub source_uv: Bounds<f32>,+@@ -2454 +2504,4 @@ mod backdrop_blur_tests {+- assert!(diff <= 3, "vignette or shift at window edge: max diff {diff}");++ assert!(++ diff <= 3,++ "vignette or shift at window edge: max diff {diff}"++ );+diff --git a/crates/gpui_macos/src/shaders.metal b/crates/gpui_macos/src/shaders.metal+index 97bad184dc..71a05aca4f 100644+--- a/crates/gpui_macos/src/shaders.metal++++ b/crates/gpui_macos/src/shaders.metal+@@ -883,3 +883,6 @@ vertex SurfaceVertexOutput surface_vertex(+- // We are going to copy the whole texture, so the texture position corresponds+- // to the current vertex of the unit triangle.+- float2 texture_position = unit_vertex;++ // Sample the source_uv sub-rect: the full texture for plain paint_surface,++ // an object-fit crop for paint_surface_fitted.++ float2 texture_position =++ float2(surface.source_uv.origin.x, surface.source_uv.origin.y) +++ unit_vertex * float2(surface.source_uv.size.width,++ surface.source_uv.size.height);+@@ -891,0 +895,13 @@ vertex SurfaceVertexOutput surface_vertex(++// Rounded-corner clip shared by both surface fragments. Radii of zero take++// the early return so an unrounded surface keeps its exact hard-edged output.++float surface_corner_alpha(float2 position, SurfaceBounds surface) {++ float max_radius = max(++ max(surface.corner_radii.top_left, surface.corner_radii.top_right),++ max(surface.corner_radii.bottom_left, surface.corner_radii.bottom_right));++ if (max_radius <= 0.) {++ return 1.;++ }++ float distance = quad_sdf(position, surface.bounds, surface.corner_radii);++ return saturate(0.5 - distance);++}+++@@ -892,0 +909,2 @@ fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]],++ constant SurfaceBounds *surfaces++ [[buffer(SurfaceInputIndex_Surfaces)]],+@@ -907 +925,15 @@ fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]],+- return ycbcrToRGBTransform * ycbcr;++ float4 color = ycbcrToRGBTransform * ycbcr;++ color.a *= surface_corner_alpha(input.position.xy, surfaces[0]);++ return color;++}++++fragment float4 surface_bgra_fragment(SurfaceFragmentInput input [[stage_in]],++ constant SurfaceBounds *surfaces++ [[buffer(SurfaceInputIndex_Surfaces)]],++ texture2d<float> color_texture++ [[texture(SurfaceInputIndex_YTexture)]]) {++ constexpr sampler texture_sampler(mag_filter::linear, min_filter::linear);++ float4 color = float4(++ color_texture.sample(texture_sampler, input.texture_position).rgb, 1.0);++ color.a *= surface_corner_alpha(input.position.xy, surfaces[0]);++ return color;+diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs+index 8a3aa5ea06..e0a9b8e2ef 100644+--- a/crates/gpui_macos/src/window.rs++++ b/crates/gpui_macos/src/window.rs+@@ -3135 +3135,2 @@ unsafe fn remove_layer_background(layer: id) {+- let _: () = msg_send![filter, setValue: radius forKey: ns_string("inputRadius")];++ let _: () =++ msg_send![filter, setValue: radius forKey: ns_string("inputRadius")];+diff --git a/crates/gpui_windows/src/directx_atlas.rs b/crates/gpui_windows/src/directx_atlas.rs+--- a/crates/gpui_windows/src/directx_atlas.rs++++ b/crates/gpui_windows/src/directx_atlas.rs+@@ -110,0 +111,9 @@ impl PlatformAtlas for DirectXAtlas {++ let cached_texture_index = if id.kind == AtlasTextureKind::Polychrome {++ textures.textures.iter().position(|entry| {++ entry++ .as_ref()++ .is_some_and(|entry| entry.live_atlas_keys == 0)++ })++ } else {++ None++ };+@@ -119 +129,7 @@ impl PlatformAtlas for DirectXAtlas {+- if texture.is_unreferenced() {++ if texture.is_unreferenced() && id.kind == AtlasTextureKind::Polychrome {++ *texture_slot = Some(texture);++ if let Some(index) = cached_texture_index {++ textures.textures[index] = None;++ textures.free_list.push(index);++ }++ } else if texture.is_unreferenced() {+@@ -420 +435,33 @@ mod tests {+-}++++ #[test]++ fn test_reuses_one_unreferenced_polychrome_texture() {++ let Some(atlas) = create_atlas() else {++ return;++ };++++ let small = Size {++ width: DevicePixels(64),++ height: DevicePixels(64),++ };++ let large = Size {++ width: DevicePixels(1280),++ height: DevicePixels(720),++ };++ let small_key = make_image_key(10);++ let first_key = make_image_key(11);++ let second_key = make_image_key(12);++++ insert_tile(&atlas, &small_key, small);++ atlas.remove(&small_key);++ let first = insert_tile(&atlas, &first_key, large);++ atlas.remove(&first_key);++ let second = insert_tile(&atlas, &second_key, large);++++ assert_eq!(first.texture_id, second.texture_id);++ let state = atlas.0.lock();++ assert_eq!(++ state.polychrome_textures.textures.iter().flatten().count(),++ 1++ );++ }++}diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex e2e03c5c8..cd41bbe52 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -2,14 +2,16 @@"name": "@cap/desktop","type": "module","scripts": {- "dev": "pnpm -w cap-setup && pnpm build:sidecar && dotenv -e ../../.env -- pnpm run preparescript && dotenv -e ../../.env -- node ../../scripts/dev-desktop.mjs",- "build:tauri": "pnpm build:sidecar && dotenv -e ../../.env -- pnpm run preparescript && dotenv -e ../../.env -- pnpm tauri build",+ "dev": "pnpm -w cap-setup && pnpm build:sidecar && pnpm build:gpui:dev && dotenv -e ../../.env -- pnpm run preparescript && dotenv -e ../../.env -- node ../../scripts/dev-desktop.mjs",+ "build:tauri": "pnpm build:sidecar && pnpm build:gpui && dotenv -e ../../.env -- pnpm run preparescript --release && node ../../scripts/verify-gpui-release-inputs.mjs && dotenv -e ../../.env -- pnpm tauri build","build:sidecar": "node ../../scripts/build-desktop-binaries.mjs",+ "build:gpui": "node ../../scripts/run-gpui-build.mjs release",+ "build:gpui:dev": "dotenv -e ../../.env -- node ../../scripts/run-gpui-build.mjs debug","preparescript": "node scripts/prepare.js","localdev": "dotenv -e ../../.env -- vinxi dev --port 3002","build": "vinxi build","tauri": "tauri",- "test:display-transport": "node scripts/desktop-display-transport-benchmark.js",+ "test:display-transport": "node --experimental-websocket scripts/desktop-display-transport-benchmark.js","test:memory": "node scripts/desktop-memory-soak.js","test:memory:unit": "vitest run scripts/desktop-memory-soak.test.js"},@@ -80,7 +82,7 @@"@solid-devtools/overlay": "^0.33.5","@tailwindcss/postcss": "^4.2.2","@tailwindcss/typography": "^0.5.9",- "@tauri-apps/cli": ">=2.1.0",+ "@tauri-apps/cli": "2.8.4","@total-typescript/ts-reset": "^0.6.1","@types/dom-webcodecs": "^0.1.11","@types/uuid": "^9.0.8",diff --git a/apps/desktop/scripts/prepare.js b/apps/desktop/scripts/prepare.jsindex 93b9ea065..66df72366 100644--- a/apps/desktop/scripts/prepare.js+++ b/apps/desktop/scripts/prepare.js@@ -3,6 +3,7 @@import * as fs from "node:fs/promises";import * as path from "node:path";import { fileURLToPath } from "node:url";+import { shouldBundleGpui } from "../../../scripts/run-gpui-build.mjs";const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);@@ -47,7 +48,7 @@ async function semverToWIXCompatibleVersion(cargoFilePath) {* @param {Object} source* @returns {Object}*/-function deepMerge(target, source) {+export function deepMerge(target, source) {for (const key of Object.keys(source)) {if (source[key] instanceof Object &&@@ -71,6 +72,40 @@ export async function createTauriPlatformConfigs(configOptions = undefined,) {const srcTauri = path.join(__dirname, "../src-tauri/");+ const profile = process.argv.includes("--release") ? "release" : "debug";+ const hostArchitecture = process.arch === "arm64" ? "aarch64" : "x86_64";+ const hostTargets = {+ darwin: `${hostArchitecture}-apple-darwin`,+ win32: `${hostArchitecture}-pc-windows-msvc`,+ linux: `${hostArchitecture}-unknown-linux-gnu`,+ };+ const target = process.env.RUST_TARGET_TRIPLE ?? hostTargets[platform];+ const extension = platform === "win32" ? ".exe" : "";+ const sidecarAvailable = target+ ? await fs+ .access(+ path.join(srcTauri, "binaries", `cap-gpui-${target}${extension}`),+ )+ .then(() => true)+ .catch(() => false)+ : false;+ const developmentWorkspaceAvailable = await fs+ .access(path.join(__dirname, "../../desktop-gpui/dev.sh"))+ .then(() => true)+ .catch(() => false);+ const includeGpui = shouldBundleGpui(+ platform,+ process.env,+ profile,+ sidecarAvailable,+ developmentWorkspaceAvailable,+ );+ const externalBin = [+ "binaries/cap-muxer",+ "binaries/cap-exporter",+ "binaries/cap-cli",+ ...(includeGpui ? ["binaries/cap-gpui"] : []),+ ];let baseConfig = {};let configFileName = null;@@ -80,11 +115,7 @@ export async function createTauriPlatformConfigs(baseConfig = {...baseConfig,bundle: {- externalBin: [- "binaries/cap-muxer",- "binaries/cap-exporter",- "binaries/cap-cli",- ],+ externalBin,resources: {"../../../target/ffmpeg/bin/*.dll": "./","../../../target/native-deps/dxc/*.dll": "./",@@ -107,11 +138,7 @@ export async function createTauriPlatformConfigs(baseConfig = {...baseConfig,bundle: {- externalBin: [- "binaries/cap-muxer",- "binaries/cap-exporter",- "binaries/cap-cli",- ],+ externalBin,resources: {"../../../target/native-deps/onnxruntime/lib/libonnxruntime.dylib":"onnxruntime/lib/libonnxruntime.dylib",@@ -120,6 +147,18 @@ export async function createTauriPlatformConfigs(};}+ if (platform === "linux") {+ configFileName = "tauri.linux.conf.json";+ const existingConfig = await fs+ .readFile(path.join(srcTauri, configFileName), "utf-8")+ .then(JSON.parse)+ .catch((error) => {+ if (error.code === "ENOENT") return {};+ throw error;+ });+ baseConfig = deepMerge(existingConfig, { bundle: { externalBin } });+ }+if (!configFileName) return;const mergedConfig = configOptions@@ -137,11 +176,14 @@ async function main() {console.log("--- Preparation finished");}-main().catch((err) => {- console.error("\n--- Preparation Failed");- console.error(err);- console.error("---");-});+if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {+ main().catch((err) => {+ console.error("\n--- Preparation Failed");+ console.error(err);+ console.error("---");+ process.exitCode = 1;+ });+}async function writeFileIfChanged(filePath, contents) {const currentContents = await fsdiff --git a/apps/desktop/scripts/prepare.test.js b/apps/desktop/scripts/prepare.test.jsnew file mode 100644index 000000000..2ad7bfc58--- /dev/null+++ b/apps/desktop/scripts/prepare.test.js@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";+import { deepMerge } from "./prepare.js";++describe("Tauri platform release configuration", () => {+ it("preserves generated Linux shared-library mappings when adding GPUI", () => {+ const existing = {+ bundle: {+ linux: {+ deb: {+ files: {+ "/usr/lib/cap/libavcodec.so.61":+ "../../../target/native-deps/cap-deb-libs/libavcodec.so.61",+ },+ },+ },+ },+ };++ const merged = deepMerge(existing, {+ bundle: { externalBin: ["binaries/cap-gpui"] },+ });++ expect(merged.bundle.externalBin).toEqual(["binaries/cap-gpui"]);+ expect(merged.bundle.linux.deb.files).toEqual(+ existing.bundle.linux.deb.files,+ );+ });++ it("preserves Windows resource mappings when platform overrides are applied", () => {+ const merged = deepMerge(+ {+ bundle: {+ externalBin: ["binaries/cap-cli", "binaries/cap-gpui"],+ resources: { "ffmpeg/*.dll": "./" },+ },+ },+ { bundle: { windows: { wix: { version: "0.6.0" } } } },+ );++ expect(merged.bundle.externalBin).toContain("binaries/cap-gpui");+ expect(merged.bundle.resources).toEqual({ "ffmpeg/*.dll": "./" });+ expect(merged.bundle.windows.wix.version).toBe("0.6.0");+ });+});diff --git a/apps/desktop/src-tauri/binaries/gpui/README.md b/apps/desktop/src-tauri/binaries/gpui/README.mddeleted file mode 100644index 691b33356..000000000--- a/apps/desktop/src-tauri/binaries/gpui/README.md+++ /dev/null@@ -1,6 +0,0 @@-# Cap GPUI staging--Place the `cap-gpui` binary (built from `apps/desktop-gpui`) in this folder to-bundle it into the Tauri app as the `gpui/` resource dir. When present, the-Experimental settings page offers launching it; when absent, the section is-hidden. This file exists so the `binaries/gpui/*` bundle glob always matches.diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 542a0e4bb..f31590d46 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -57,7 +57,6 @@"icons/icon.ico"],"resources": {- "binaries/gpui/*": "gpui/","assets/backgrounds/macOS/*": "assets/backgrounds/macOS/","assets/backgrounds/blue/*": "assets/backgrounds/blue/","assets/backgrounds/cities/*": "assets/backgrounds/cities/",@@ -101,8 +100,12 @@"libayatana-appindicator3-1","libva2","libva-drm2",+ "pulseaudio-utils","libpipewire-0.3-0",- "libasound2t64 | libasound2"+ "libasound2t64 | libasound2",+ "libxkbcommon0",+ "libxkbcommon-x11-0",+ "libssl3t64 | libssl3"],"files": {"/usr/share/icons/hicolor/scalable/status/so.cap.desktop-tray-default-symbolic.svg": "icons/linux/so.cap.desktop-tray-default-symbolic.svg",diff --git a/package.json b/package.jsonindex 55c4e1879..1ed467b97 100644--- a/package.json+++ b/package.json@@ -28,7 +28,7 @@"docker:up": "turbo run docker:up","format": "pnpm exec biome check --write","lint": "pnpm exec biome lint",- "tauri:build": "node scripts/build-desktop-binaries.mjs && dotenv -e .env -- pnpm --dir apps/desktop run preparescript && dotenv -e .env -- pnpm --dir apps/desktop tauri build --verbose",+ "tauri:build": "dotenv -e .env -- pnpm --dir apps/desktop run build:tauri --config src-tauri/tauri.prod.conf.json --verbose","typecheck": "pnpm --dir apps/web exec next typegen && pnpm tsc -b","test": "turbo run test","test:web": "pnpm --filter=@cap/web test",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8b18a2739..6cc74db42 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -302,8 +302,8 @@ importers:specifier: ^0.5.9version: 0.5.20([email protected]([email protected]))'@tauri-apps/cli':- specifier: '>=2.1.0'- version: 2.11.4+ specifier: 2.8.4+ version: 2.8.4'@total-typescript/ts-reset':specifier: ^0.6.1version: 0.6.1@@ -7662,8 +7662,8 @@ packages:cpu: [arm64]os: [darwin]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-BKu8HRkYV01SMTa7r4fLx+wjgtRK8Vep7lmBdHDioP6b8XH3q2KgsAyPWfEZaZIkZ2LY4SqqGARaE9oilNe0oA==}engines: {node: '>= 10'}cpu: [arm64]os: [darwin]@@ -7674,8 +7674,8 @@ packages:cpu: [x64]os: [darwin]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-imb9PfSd/7G6VAO7v1bQ2A3ZH4NOCbhGJFLchxzepGcXf9NKkfun157JH9mko29K6sqAwuJ88qtzbKCbWJTH9g==}engines: {node: '>= 10'}cpu: [x64]os: [darwin]@@ -7686,8 +7686,8 @@ packages:cpu: [arm]os: [linux]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-Ml215UnDdl7/fpOrF1CNovym/KjtUbCuPgrcZ4IhqUCnhZdXuphud/JT3E8X97Y03TZ40Sjz8raXYI2ET0exzw==}engines: {node: '>= 10'}cpu: [arm]os: [linux]@@ -7698,8 +7698,8 @@ packages:cpu: [arm64]os: [linux]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-pbcgBpMyI90C83CxE5REZ9ODyIlmmAPkkJXtV398X3SgZEIYy5TACYqlyyv2z5yKgD8F8WH4/2fek7+jH+ZXAw==}engines: {node: '>= 10'}cpu: [arm64]os: [linux]@@ -7710,14 +7710,14 @@ packages:cpu: [arm64]os: [linux]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-zumFeaU1Ws5Ay872FTyIm7z8kfzEHu8NcIn8M6TxbJs0a7GRV21KBdpW1zNj2qy7HynnpQCqjAYXTUUmm9JAOw==}engines: {node: '>= 10'}cpu: [arm64]os: [linux]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-qiqbB3Zz6IyO201f+1ojxLj65WYj8mixL5cOMo63nlg8CIzsP23cPYUrx1YaDPsCLszKZo7tVs14pc7BWf+/aQ==}engines: {node: '>= 10'}cpu: [riscv64]os: [linux]@@ -7728,8 +7728,8 @@ packages:cpu: [x64]os: [linux]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-TaqaDd9Oy6k45Hotx3pOf+pkbsxLaApv4rGd9mLuRM1k6YS/aw81YrsMryYPThrxrScEIUcmNIHaHsLiU4GMkw==}engines: {node: '>= 10'}cpu: [x64]os: [linux]@@ -7740,8 +7740,8 @@ packages:cpu: [x64]os: [linux]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-ot9STAwyezN8w+bBHZ+bqSQIJ0qPZFlz/AyscpGqB/JnJQVDFQcRDmUPFEaAtt2UUHSWzN3GoTJ5ypqLBp2WQA==}engines: {node: '>= 10'}cpu: [x64]os: [linux]@@ -7752,8 +7752,8 @@ packages:cpu: [arm64]os: [win32]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-+2aJ/g90dhLiOLFSD1PbElXX3SoMdpO7HFPAZB+xot3CWlAZD1tReUFy7xe0L5GAR16ZmrxpIDM9v9gn5xRy/w==}engines: {node: '>= 10'}cpu: [arm64]os: [win32]@@ -7764,8 +7764,8 @@ packages:cpu: [ia32]os: [win32]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-yj7WDxkL1t9Uzr2gufQ1Hl7hrHuFKTNEOyascbc109EoiAqCp0tgZ2IykQqOZmZOHU884UAWI1pVMqBhS/BfhA==}engines: {node: '>= 10'}cpu: [ia32]os: [win32]@@ -7776,8 +7776,8 @@ packages:cpu: [x64]os: [win32]- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-XuvGB4ehBdd7QhMZ9qbj/8icGEatDuBNxyYHbLKsTYh90ggUlPa/AtaqcC1Fo69lGkTmq9BOKrs1aWSi7xDonA==}engines: {node: '>= 10'}cpu: [x64]os: [win32]@@ -7787,8 +7787,8 @@ packages:engines: {node: '>= 10'}hasBin: true- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ==}+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-ejUZBzuQRcjFV+v/gdj/DcbyX/6T4unZQjMSBZwLzP/CymEjKcc2+Fc8xTORThebHDUvqoXMdsCZt8r+hyN15g==}engines: {node: '>= 10'}hasBin: true@@ -23356,64 +23356,64 @@ snapshots:'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':optional: true- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optional: true'@tauri-apps/[email protected]':@@ -23431,19 +23431,19 @@ snapshots:'@tauri-apps/cli-win32-ia32-msvc': 1.6.3'@tauri-apps/cli-win32-x64-msvc': 1.6.3- '@tauri-apps/[email protected]':+ '@tauri-apps/[email protected]':optionalDependencies:- '@tauri-apps/cli-darwin-arm64': 2.11.4- '@tauri-apps/cli-darwin-x64': 2.11.4- '@tauri-apps/cli-linux-arm-gnueabihf': 2.11.4- '@tauri-apps/cli-linux-arm64-gnu': 2.11.4- '@tauri-apps/cli-linux-arm64-musl': 2.11.4- '@tauri-apps/cli-linux-riscv64-gnu': 2.11.4- '@tauri-apps/cli-linux-x64-gnu': 2.11.4- '@tauri-apps/cli-linux-x64-musl': 2.11.4- '@tauri-apps/cli-win32-arm64-msvc': 2.11.4- '@tauri-apps/cli-win32-ia32-msvc': 2.11.4- '@tauri-apps/cli-win32-x64-msvc': 2.11.4+ '@tauri-apps/cli-darwin-arm64': 2.8.4+ '@tauri-apps/cli-darwin-x64': 2.8.4+ '@tauri-apps/cli-linux-arm-gnueabihf': 2.8.4+ '@tauri-apps/cli-linux-arm64-gnu': 2.8.4+ '@tauri-apps/cli-linux-arm64-musl': 2.8.4+ '@tauri-apps/cli-linux-riscv64-gnu': 2.8.4+ '@tauri-apps/cli-linux-x64-gnu': 2.8.4+ '@tauri-apps/cli-linux-x64-musl': 2.8.4+ '@tauri-apps/cli-win32-arm64-msvc': 2.8.4+ '@tauri-apps/cli-win32-ia32-msvc': 2.8.4+ '@tauri-apps/cli-win32-x64-msvc': 2.8.4'@tauri-apps/[email protected]':dependencies:diff --git a/scripts/build-gpui-binary.sh b/scripts/build-gpui-binary.shnew file mode 100755index 000000000..e8e276e22--- /dev/null+++ b/scripts/build-gpui-binary.sh@@ -0,0 +1,74 @@+#!/usr/bin/env bash+set -euo pipefail++profile="${1:-release}"+requested_target="${2:-${RUST_TARGET_TRIPLE:-}}"+toolchain="${CAP_GPUI_RUST_TOOLCHAIN:-1.95.0}"+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+gpui_dir="$repo_root/apps/desktop-gpui"+binaries_dir="$repo_root/apps/desktop/src-tauri/binaries"++case "$profile" in+ debug)+ profile_dir="debug"+ ;;+ release)+ profile_dir="release"+ ;;+ *)+ echo "error: profile must be debug or release" >&2+ exit 1+ ;;+esac++if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1; then+ rustup toolchain install "$toolchain" --profile minimal+fi++if [[ -n "$requested_target" ]]; then+ target="$requested_target"+ artifact_dir="$gpui_dir/target/$target/$profile_dir"+ rustup target add "$target" --toolchain "$toolchain"+else+ target="$(cd "$gpui_dir" && rustc +"$toolchain" -vV | sed -n 's|host: ||p')"+ artifact_dir="$gpui_dir/target/$profile_dir"+fi++extension=""+if [[ "$target" == *windows* ]]; then+ extension=".exe"+fi++node "$repo_root/scripts/sync-desktop-versions.mjs"+"$repo_root/scripts/prepare-gpui-dependency.sh"++(+ cd "$gpui_dir"+ if [[ "$profile" == "release" && -n "$requested_target" ]]; then+ cargo +"$toolchain" build --release --target "$target"+ elif [[ "$profile" == "release" ]]; then+ cargo +"$toolchain" build --release+ elif [[ -n "$requested_target" ]]; then+ cargo +"$toolchain" build --target "$target"+ else+ cargo +"$toolchain" build+ fi+)++source_binary="$artifact_dir/cap-gpui$extension"+staged_binary="$binaries_dir/cap-gpui-$target$extension"+if [[ ! -f "$source_binary" ]]; then+ echo "error: built GPUI binary not found at $source_binary" >&2+ exit 1+fi++if [[ "$target" == *linux* ]]; then+ patchelf --set-rpath '$ORIGIN:$ORIGIN/../lib/cap' "$source_binary"+fi++mkdir -p "$binaries_dir"+cp "$source_binary" "$staged_binary"+if [[ "$extension" != ".exe" ]]; then+ chmod +x "$staged_binary"+fi+echo "Staged $source_binary -> $staged_binary"diff --git a/scripts/prepare-gpui-dependency.sh b/scripts/prepare-gpui-dependency.shnew file mode 100755index 000000000..445b5fa36--- /dev/null+++ b/scripts/prepare-gpui-dependency.sh@@ -0,0 +1,44 @@+#!/usr/bin/env bash+set -euo pipefail++repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+zed_dir="$repo_root/../zed-cap"+patch_file="$repo_root/apps/desktop-gpui/patches/zed-gpui.patch"+base_revision="5d1f83d9f27a19bec1fb241dc33b42238af9cf8d"+remote="https://github.com/wingleeio/zed.git"++verify_checkout() {+ if ! git -C "$zed_dir" merge-base --is-ancestor "$base_revision" HEAD; then+ echo "error: $zed_dir does not contain GPUI base $base_revision" >&2+ exit 1+ fi+ if ! git -C "$zed_dir" apply --reverse --check --unidiff-zero "$patch_file"; then+ echo "error: $zed_dir does not contain Cap's pinned GPUI patch" >&2+ exit 1+ fi+}++if [[ -e "$zed_dir/.git" ]]; then+ verify_checkout+ exit 0+fi++if [[ -e "$zed_dir" ]]; then+ echo "error: $zed_dir exists but is not a Git checkout" >&2+ exit 1+fi++temporary_dir="$(mktemp -d "$zed_dir.tmp.XXXXXX")"+cleanup() {+ rm -rf "$temporary_dir"+}+trap cleanup EXIT++git init --quiet "$temporary_dir"+git -C "$temporary_dir" remote add origin "$remote"+git -C "$temporary_dir" fetch --quiet --depth 1 origin "$base_revision"+git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD+git -C "$temporary_dir" apply --unidiff-zero "$patch_file"+mv "$temporary_dir" "$zed_dir"+trap - EXIT+verify_checkoutdiff --git a/scripts/run-gpui-build.mjs b/scripts/run-gpui-build.mjsnew file mode 100644index 000000000..ac751cc65--- /dev/null+++ b/scripts/run-gpui-build.mjs@@ -0,0 +1,91 @@+import { spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import * as path from "node:path";+import { fileURLToPath } from "node:url";++export function shouldBuildGpui(+ platform,+ environment,+ profile,+ developmentWorkspaceAvailable = true,+) {+ if (!["darwin", "win32", "linux"].includes(platform)) return false;+ if (profile === "release") return true;+ return (+ platform === "darwin" &&+ environment.CAP_GPUI_DEV !== "0" &&+ developmentWorkspaceAvailable+ );+}++export function shouldBundleGpui(+ platform,+ environment,+ profile,+ stagedSidecarAvailable,+ developmentWorkspaceAvailable = true,+) {+ return (+ shouldBuildGpui(+ platform,+ environment,+ profile,+ developmentWorkspaceAvailable,+ ) &&+ (profile === "release" || stagedSidecarAvailable)+ );+}++function main() {+ const profile = process.argv[2];+ if (profile !== "debug" && profile !== "release") {+ console.error("The Cap GPUI build profile must be debug or release.");+ process.exitCode = 1;+ return;+ }++ const scriptsDir = path.dirname(fileURLToPath(import.meta.url));+ const gpuiDevScript = path.join(+ scriptsDir,+ "..",+ "apps",+ "desktop-gpui",+ "dev.sh",+ );++ if (+ !shouldBuildGpui(+ process.platform,+ process.env,+ profile,+ profile !== "debug" || existsSync(gpuiDevScript),+ )+ ) {+ console.log(+ `Skipping Cap GPUI ${profile} build on ${process.platform}${+ process.env.CAP_GPUI_DEV === "0" ? " because CAP_GPUI_DEV=0" : ""+ }.`,+ );+ return;+ }++ const result = spawnSync(+ "bash",+ [path.join(scriptsDir, "build-gpui-binary.sh"), profile],+ { stdio: "inherit" },+ );++ if (result.error) {+ console.error(`Failed to build Cap GPUI: ${result.error.message}`);+ process.exitCode = 1;+ } else if (result.status !== 0) {+ process.exitCode = result.status ?? 1;+ }+}++if (+ process.argv[1] &&+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)+) {+ main();+}diff --git a/scripts/run-gpui-build.test.mjs b/scripts/run-gpui-build.test.mjsnew file mode 100644index 000000000..2121a395d--- /dev/null+++ b/scripts/run-gpui-build.test.mjs@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import test from "node:test";+import { shouldBuildGpui, shouldBundleGpui } from "./run-gpui-build.mjs";++test("GPUI release builds run on every supported desktop platform", () => {+ assert.equal(shouldBuildGpui("darwin", {}, "release"), true);+ assert.equal(shouldBuildGpui("win32", {}, "release"), true);+ assert.equal(shouldBuildGpui("linux", {}, "release"), true);+ assert.equal(shouldBuildGpui("freebsd", {}, "release"), false);+});++test("GPUI development builds honor their platform and opt-out guards", () => {+ assert.equal(shouldBuildGpui("darwin", {}, "debug"), true);+ assert.equal(+ shouldBuildGpui("darwin", { CAP_GPUI_DEV: "0" }, "debug"),+ false,+ );+ assert.equal(shouldBuildGpui("darwin", {}, "debug", false), false);+ assert.equal(shouldBuildGpui("win32", {}, "debug"), false);+ assert.equal(shouldBuildGpui("linux", {}, "debug"), false);+});++test("the development opt-out never suppresses supported release builds", () => {+ for (const platform of ["darwin", "win32", "linux"]) {+ assert.equal(+ shouldBuildGpui(platform, { CAP_GPUI_DEV: "0" }, "release"),+ true,+ );+ }+});++test("macOS development only bundles an enabled and available GPUI sidecar", () => {+ assert.equal(shouldBundleGpui("darwin", {}, "debug", true), true);+ assert.equal(shouldBundleGpui("darwin", {}, "debug", false), false);+ assert.equal(shouldBundleGpui("darwin", {}, "debug", true, false), false);+ assert.equal(+ shouldBundleGpui("darwin", { CAP_GPUI_DEV: "0" }, "debug", true),+ false,+ );+});++test("release bundling is mandatory on every supported desktop platform", () => {+ for (const platform of ["darwin", "win32", "linux"]) {+ assert.equal(+ shouldBundleGpui(platform, { CAP_GPUI_DEV: "0" }, "release", false),+ true,+ );+ }+ assert.equal(shouldBundleGpui("freebsd", {}, "release", true), false);+});diff --git a/scripts/setup.js b/scripts/setup.jsindex 6592f4445..378944e94 100644--- a/scripts/setup.js+++ b/scripts/setup.js@@ -202,21 +202,50 @@ async function main() {path.relative(__root, onnxRuntimePath),)}" }\n`;- const { stdout: vcInstallDir } = await exec(- // biome-ignore lint/suspicious/noTemplateCurlyInString: PowerShell syntax, not JS template literal- '$(& "${env:ProgramFiles(x86)}/Microsoft Visual Studio/Installer/vswhere.exe" -latest -property installationPath)',- { shell: "powershell.exe" },+ const vswherePath = path.join(+ process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)",+ "Microsoft Visual Studio",+ "Installer",+ "vswhere.exe",);+ const { stdout: vcInstallDir } = await execFile(vswherePath, [+ "-latest",+ "-products",+ "*",+ "-requires",+ "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",+ "-property",+ "installationPath",+ ]);+ if (!vcInstallDir.trim())+ throw new Error(+ "Visual Studio C++ build tools installation was not found",+ );const libclangPath = path.join(vcInstallDir.trim(),"VC/Tools/LLVM/x64/bin/libclang.dll",);+ if (!(await fileExists(libclangPath)))+ throw new Error(+ `Visual Studio LLVM libclang was not found at ${libclangPath}`,+ );cargoConfigContents += `LIBCLANG_PATH = "${libclangPath.replaceAll("\\","/",)}"\n`;++ const cmakePath = path.join(+ vcInstallDir.trim(),+ "Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe",+ );+ if (await fileExists(cmakePath))+ cargoConfigContents += `CMAKE = "${cargoConfigPath(cmakePath)}"\n`;+ else if (!(await findExecutable("cmake")))+ throw new Error(+ "CMake was not found. Install the Visual Studio C++ CMake tools component.",+ );} else if (process.platform === "linux") {const triple = process.env.RUST_TARGET_TRIPLE;if (triple) {@@ -259,6 +288,7 @@ async function main() {console.log("Extracted native-deps");} else console.log("Using cached native-deps");+ const onnxRuntimePath = await setupLinuxOnnxRuntime();const debLibDir = path.join(nativeDepsDir, "cap-deb-libs");await fs.rm(debLibDir, { recursive: true, force: true }).catch(() => {});await fs.mkdir(debLibDir, { recursive: true });@@ -279,12 +309,30 @@ async function main() {for (const dir of profileDirs)await fs.copyFile(realPath, path.join(dir, name));}+ const onnxRuntimeName = path.basename(onnxRuntimePath);+ const onnxRuntimeNames = [onnxRuntimeName, `${onnxRuntimeName}.1`];+ for (const name of onnxRuntimeNames) {+ await fs.copyFile(onnxRuntimePath, path.join(debLibDir, name));+ for (const dir of profileDirs)+ await fs.copyFile(onnxRuntimePath, path.join(dir, name));+ }+ const bundledLibraries = [+ ...new Set([...sonameLibs, ...onnxRuntimeNames]),+ ];console.log(- `Staged ${sonameLibs.length} FFmpeg shared libraries for Linux bundling`,+ `Staged ${bundledLibraries.length} shared libraries for Linux bundling`,);- await writeLinuxTauriConfig(sonameLibs);+ await writeLinuxTauriConfig(bundledLibraries);+ cargoConfigContents += `ORT_DYLIB_PATH = { relative = true, force = true, value = "${cargoConfigPath(+ path.relative(__root, onnxRuntimePath),+ )}" }\n`;cargoConfigContents += `\n[target.${triple}]\nrustflags = ["-C", "link-arg=-Wl,-rpath,$ORIGIN", "-C", "link-arg=-Wl,-rpath,$ORIGIN/../lib/cap"]\n`;+ } else {+ const onnxRuntimePath = await setupLinuxOnnxRuntime();+ cargoConfigContents += `[env]\nORT_DYLIB_PATH = { relative = true, force = true, value = "${cargoConfigPath(+ path.relative(__root, onnxRuntimePath),+ )}" }\n`;}}@@ -490,6 +538,50 @@ async function setupWindowsOnnxRuntime() {return outputPath;}+async function setupLinuxOnnxRuntime() {+ const version = "1.24.3";+ const platformArch = { x86_64: "x64", aarch64: "aarch64" }[arch];+ if (!platformArch)+ throw new Error(`Unsupported Linux arch for ONNX Runtime: ${arch}`);++ const archiveName = `onnxruntime-linux-${platformArch}-${version}.tgz`;+ const archivePath = path.join(targetDir, archiveName);+ const extractDir = path.join(targetDir, archiveName.replace(/\.tgz$/, ""));+ const outputDir = path.join(targetDir, "native-deps", "onnxruntime", "lib");+ const outputPath = path.join(outputDir, "libonnxruntime.so");+ const markerPath = path.join(outputDir, "asset.txt");+ const marker = await fs+ .readFile(markerPath, "utf-8")+ .then((value) => value.trim())+ .catch(() => null);++ if (!(await fileExists(archivePath))) {+ const response = await fetch(+ `https://github.com/microsoft/onnxruntime/releases/download/v${version}/${archiveName}`,+ );+ if (!response.ok)+ throw new Error(+ `Failed to download ${archiveName}: HTTP ${response.status}`,+ );+ await fs.writeFile(archivePath, Buffer.from(await response.arrayBuffer()));+ console.log(`Downloaded ${archiveName}`);+ } else console.log(`Using cached ${archiveName}`);++ if (!(await fileExists(outputPath)) || marker !== archiveName) {+ await fs.rm(extractDir, { recursive: true, force: true }).catch(() => {});+ await execFile("tar", ["xf", archivePath, "-C", targetDir]);+ await fs.mkdir(outputDir, { recursive: true });+ await fs.copyFile(+ path.join(extractDir, "lib", "libonnxruntime.so"),+ outputPath,+ );+ await fs.writeFile(markerPath, archiveName);+ console.log("Prepared ONNX Runtime shared library");+ } else console.log("Using cached ONNX Runtime shared library");++ return outputPath;+}+async function setupWindowsDxc() {const asset = {version: "1.9.2607.13",diff --git a/scripts/sync-desktop-versions.mjs b/scripts/sync-desktop-versions.mjsnew file mode 100644index 000000000..a1f80a6bd--- /dev/null+++ b/scripts/sync-desktop-versions.mjs@@ -0,0 +1,60 @@+import * as fs from "node:fs/promises";+import * as path from "node:path";+import { fileURLToPath } from "node:url";++const scriptDir = path.dirname(fileURLToPath(import.meta.url));+const repoRoot = path.resolve(scriptDir, "..");+const tauriManifest = path.join(+ repoRoot,+ "apps",+ "desktop",+ "src-tauri",+ "Cargo.toml",+);+const gpuiManifest = path.join(repoRoot, "apps", "desktop-gpui", "Cargo.toml");++function packageVersion(source, manifestPath) {+ const packageStart = source.indexOf("[package]");+ const packageEnd = source.indexOf("\n[", packageStart + 1);+ const section = source.slice(+ packageStart,+ packageEnd === -1 ? source.length : packageEnd,+ );+ const match = /^version\s*=\s*"([^"]+)"$/m.exec(section);+ if (!match) throw new Error(`package.version not found in ${manifestPath}`);+ return match[1];+}++function replacePackageVersion(source, manifestPath, version) {+ const packageStart = source.indexOf("[package]");+ const packageEnd = source.indexOf("\n[", packageStart + 1);+ const end = packageEnd === -1 ? source.length : packageEnd;+ const section = source.slice(packageStart, end);+ const nextSection = section.replace(+ /^version\s*=\s*"[^"]+"$/m,+ `version = "${version}"`,+ );+ if (nextSection === section)+ throw new Error(`package.version not found in ${manifestPath}`);+ return source.slice(0, packageStart) + nextSection + source.slice(end);+}++const [tauriSource, gpuiSource] = await Promise.all([+ fs.readFile(tauriManifest, "utf8"),+ fs.readFile(gpuiManifest, "utf8"),+]);+const version = packageVersion(tauriSource, tauriManifest);+const gpuiVersion = packageVersion(gpuiSource, gpuiManifest);++if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version))+ throw new Error(`Invalid desktop version: ${version}`);++if (gpuiVersion !== version) {+ await fs.writeFile(+ gpuiManifest,+ replacePackageVersion(gpuiSource, gpuiManifest, version),+ );+ console.log(`Synchronized Cap GPUI ${gpuiVersion} -> ${version}`);+} else {+ console.log(`Cap desktop versions match: ${version}`);+}diff --git a/scripts/verify-gpui-release-inputs.mjs b/scripts/verify-gpui-release-inputs.mjsnew file mode 100644index 000000000..8db35f432--- /dev/null+++ b/scripts/verify-gpui-release-inputs.mjs@@ -0,0 +1,78 @@+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import * as fs from "node:fs/promises";+import * as path from "node:path";+import { fileURLToPath } from "node:url";++const repoRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+);++const configNames = {+ darwin: "tauri.macos.conf.json",+ win32: "tauri.windows.conf.json",+ linux: "tauri.linux.conf.json",+};+const configName = configNames[process.platform];++if (!configName) {+ console.log(`Skipping Cap GPUI release validation on ${process.platform}.`);+} else {+ const srcTauri = path.join(repoRoot, "apps/desktop/src-tauri");+ const configPath = path.join(srcTauri, configName);+ const productionConfigPath = path.join(srcTauri, "tauri.prod.conf.json");+ const [config, productionConfig] = await Promise.all([+ fs.readFile(configPath, "utf8").then(JSON.parse),+ fs.readFile(productionConfigPath, "utf8").then(JSON.parse),+ ]);+ const externalBin =+ productionConfig.bundle?.externalBin ?? config.bundle?.externalBin;+ if (+ !Array.isArray(externalBin) ||+ !externalBin.includes("binaries/cap-gpui")+ ) {+ throw new Error(+ `The effective ${process.platform} release config does not bundle Cap GPUI.`,+ );+ }++ const binariesDir = path.join(srcTauri, "binaries");+ const requestedTarget = process.env.RUST_TARGET_TRIPLE;+ const host = execFileSync("rustc", ["-vV"], { encoding: "utf8" }).match(+ /^host:\s*(.+)$/m,+ )?.[1];+ const target = requestedTarget ?? host;+ if (!target) throw new Error("Could not determine the Rust target triple");++ const extension = process.platform === "win32" ? ".exe" : "";+ const fileName = `cap-gpui-${target}${extension}`;+ const binaryPath = path.join(binariesDir, fileName);+ const releaseBinaryPath = path.join(+ repoRoot,+ "apps",+ "desktop-gpui",+ "target",+ ...(requestedTarget ? [target] : []),+ "release",+ `cap-gpui${extension}`,+ );+ const [stagedBinary, releaseBinary] = await Promise.all([+ fs.readFile(binaryPath),+ fs.readFile(releaseBinaryPath),+ ]);++ if (stagedBinary.length === 0 || releaseBinary.length === 0) {+ throw new Error("The staged Cap GPUI release binary is empty");+ }++ const sha256 = (contents) =>+ createHash("sha256").update(contents).digest("hex");+ if (sha256(stagedBinary) !== sha256(releaseBinary)) {+ throw new Error(`${binaryPath} does not match ${releaseBinaryPath}`);+ }++ console.log(+ `Verified effective ${process.platform} release configuration and ${fileName} for GPUI packaging.`,+ );+}