Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): nightly update channel with background auto-update

Richie McIlroy28d64eedd859
diff --git a/Cargo.lock b/Cargo.lock
index 6609b5d31..299368590 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1465,6 +1465,7 @@ dependencies = [
"scap-direct3d",
"scap-screencapturekit",
"scap-targets",
+ "semver",
"sentry",
"serde",
"serde_json",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 6700db3ed..e5e0fb7ac 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -75,6 +75,7 @@ clipboard-rs = "0.2.2"
whisper-rs = "0.11.0"
lazy_static = "1.4.0"
log = "0.4.20"
+semver = "1"
cap-audio = { path = "../../../crates/audio" }
cap-camera = { path = "../../../crates/camera", features = ["serde", "specta"] }
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index eb8d4246b..313a89dfe 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -1,3 +1,4 @@
+use crate::updates::UpdateChannel;
use crate::window_exclusion::WindowExclusion;
use scap_targets::DisplayId;
use serde::{Deserialize, Serialize};
@@ -238,6 +239,8 @@ pub struct GeneralSettingsStore {
/// update, since a new ort/wgpu/driver stack may have fixed the crash).
#[serde(default)]
pub camera_blur_disabled_by_crash: Option<String>,
+ #[serde(default)]
+ pub update_channel: UpdateChannel,
}
fn default_enable_native_camera_preview() -> bool {
@@ -339,6 +342,7 @@ impl Default for GeneralSettingsStore {
recordings_path: None,
previous_recordings_paths: Vec::new(),
camera_blur_disabled_by_crash: None,
+ update_channel: UpdateChannel::Stable,
}
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index a685e5829..971270530 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -43,6 +43,7 @@ mod target_select_overlay;
mod thumbnails;
mod tray;
mod update_project_names;
+mod updates;
mod upload;
pub mod web_api;
mod window_exclusion;
@@ -4949,6 +4950,9 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
automation::test_automation,
automation::automation_should_open_screenshot_editor,
automation::list_automation_capabilities,
+ updates::updates_check,
+ updates::updates_download_and_install,
+ updates::updates_channel_changed,
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -4979,6 +4983,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
import::VideoImportProgress,
SetCaptureAreaPending,
DevicesUpdated,
+ updates::UpdateDownloadProgress,
+ updates::UpdateReady,
])
.error_handling(tauri_specta::ErrorHandlingMode::Throw)
.typ::<ProjectConfiguration>()
@@ -5176,6 +5182,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
app.manage(http_client::RetryableHttpClient::default());
app.manage(PendingScreenshots::default());
app.manage(FinalizingRecordings::default());
+ app.manage(updates::UpdatesState::default());
+ updates::spawn_background_loop(app.clone());
#[cfg(unix)]
{
diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rs
new file mode 100644
index 000000000..ac2e1cb37
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates.rs
@@ -0,0 +1,380 @@
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::time::Duration;
+use tauri::{AppHandle, Manager, Url};
+use tauri_plugin_updater::{Update, UpdaterExt};
+use tauri_specta::Event;
+use tokio::sync::{Mutex, Notify};
+use tracing::{info, warn};
+
+use crate::general_settings::GeneralSettingsStore;
+
+const UPDATE_ENDPOINT: &str =
+ "https://cdn.crabnebula.app/update/cap/cap/{{target}}/{{current_version}}";
+
+const FIRST_CHECK_DELAY: Duration = Duration::from_secs(60);
+const CHECK_INTERVAL: Duration = Duration::from_secs(2 * 60 * 60);
+const BUSY_RETRY_DELAY: Duration = Duration::from_secs(5 * 60);
+
+#[derive(Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum UpdateChannel {
+ #[default]
+ Stable,
+ Nightly,
+}
+
+#[derive(Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateCheckResult {
+ pub version: String,
+ pub notes: Option<String>,
+ pub channel: UpdateChannel,
+}
+
+#[derive(Serialize, Type, tauri_specta::Event, Clone, Debug)]
+pub struct UpdateDownloadProgress {
+ pub downloaded: u32,
+ pub total: Option<u32>,
+}
+
+#[derive(Serialize, Type, tauri_specta::Event, Clone, Debug)]
+pub struct UpdateReady {
+ pub version: String,
+ pub installed: bool,
+}
+
+#[derive(Clone)]
+struct PendingUpdate {
+ update: Update,
+ version: String,
+ installed: bool,
+}
+
+#[derive(Default)]
+pub struct UpdatesState {
+ pending: Mutex<Option<PendingUpdate>>,
+ announced_version: Mutex<Option<String>>,
+ notify: Notify,
+}
+
+fn current_channel(app: &AppHandle) -> UpdateChannel {
+ GeneralSettingsStore::get(app)
+ .ok()
+ .flatten()
+ .map(|s| s.update_channel)
+ .unwrap_or_default()
+}
+
+// Mirrors `updaterTarget()` in src/utils/updater.ts; the plugin's built-in
+// target reports "macos"/"linux" while CrabNebula releases are keyed on
+// "darwin-*" / "linux-*-deb".
+fn updater_target() -> String {
+ let arch = if cfg!(target_arch = "aarch64") {
+ "aarch64"
+ } else {
+ "x86_64"
+ };
+
+ if cfg!(target_os = "macos") {
+ format!("darwin-{arch}")
+ } else if cfg!(target_os = "linux") {
+ format!("linux-{arch}-deb")
+ } else {
+ format!("windows-{arch}")
+ }
+}
+
+fn endpoint(channel: UpdateChannel) -> Result<Url, String> {
+ let url = match channel {
+ UpdateChannel::Stable => UPDATE_ENDPOINT.to_string(),
+ UpdateChannel::Nightly => format!("{UPDATE_ENDPOINT}?channel=nightly"),
+ };
+ Url::parse(&url).map_err(|e| e.to_string())
+}
+
+async fn check_channel(
+ app: &AppHandle,
+ channel: UpdateChannel,
+ allow_stable_downgrade: bool,
+) -> Result<Option<Update>, String> {
+ let builder = app
+ .updater_builder()
+ .target(updater_target())
+ .endpoints(vec![endpoint(channel)?])
+ .map_err(|e| e.to_string())?;
+
+ // A user on a nightly prerelease who switches back to Stable should land
+ // on the newest stable build even though it is semver-lower than their
+ // current version, so any differing non-prerelease remote counts as an
+ // update (deliberate downgrade-on-channel-switch semantics). This must
+ // ONLY apply when the user's configured channel is Stable: a nightly user
+ // on the latest nightly would otherwise see the older stable release
+ // qualify and flip-flop between the two channels forever.
+ let builder = if allow_stable_downgrade {
+ builder.version_comparator(|current, remote| {
+ remote.version > current
+ || (!current.pre.is_empty()
+ && remote.version.pre.is_empty()
+ && remote.version != current)
+ })
+ } else {
+ builder.version_comparator(|current, remote| remote.version > current)
+ };
+
+ builder
+ .build()
+ .map_err(|e| e.to_string())?
+ .check()
+ .await
+ .map_err(|e| e.to_string())
+}
+
+fn pick_higher_version(a: Option<Update>, b: Option<Update>) -> Option<Update> {
+ match (a, b) {
+ (Some(a), Some(b)) => {
+ match (
+ semver::Version::parse(&a.version),
+ semver::Version::parse(&b.version),
+ ) {
+ (Ok(a_version), Ok(b_version)) => Some(if b_version > a_version { b } else { a }),
+ (Ok(_), Err(_)) => Some(a),
+ _ => Some(b),
+ }
+ }
+ (a, b) => a.or(b),
+ }
+}
+
+pub async fn check(app: &AppHandle) -> Result<Option<Update>, String> {
+ let channel = current_channel(app);
+
+ let stable = check_channel(app, UpdateChannel::Stable, channel == UpdateChannel::Stable).await;
+
+ let update = if channel == UpdateChannel::Nightly {
+ let nightly = check_channel(app, UpdateChannel::Nightly, false).await;
+
+ // Both channels can produce a candidate when a stable release was
+ // promoted after the last nightly; the higher version wins.
+ match (stable, nightly) {
+ (Ok(stable), Ok(nightly)) => pick_higher_version(stable, nightly),
+ (Ok(update), Err(err)) | (Err(err), Ok(update)) => {
+ warn!("Update check failed for one channel: {err}");
+ update
+ }
+ (Err(err), Err(_)) => return Err(err),
+ }
+ } else {
+ stable?
+ };
+
+ let state = app.state::<UpdatesState>();
+ let mut pending = state.pending.lock().await;
+ *pending = update.as_ref().map(|update| PendingUpdate {
+ // Keep the installed flag if the background loop already installed
+ // this version silently.
+ installed: pending
+ .as_ref()
+ .is_some_and(|p| p.version == update.version && p.installed),
+ version: update.version.clone(),
+ update: update.clone(),
+ });
+
+ Ok(update)
+}
+
+async fn download_with_progress(app: &AppHandle, update: &Update) -> Result<Vec<u8>, String> {
+ let mut downloaded: u32 = 0;
+ update
+ .download(
+ |chunk, total| {
+ downloaded = downloaded.saturating_add(chunk as u32);
+ let _ = UpdateDownloadProgress {
+ downloaded,
+ total: total.and_then(|t| u32::try_from(t).ok()),
+ }
+ .emit(app);
+ },
+ || {},
+ )
+ .await
+ .map_err(|e| e.to_string())
+}
+
+async fn is_busy(app: &AppHandle) -> bool {
+ if crate::export::export_session_active() {
+ return true;
+ }
+
+ let Some(state) = app.try_state::<crate::ArcLock<crate::App>>() else {
+ return true;
+ };
+
+ state.read().await.is_recording_active_or_pending()
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn updates_check(app: AppHandle) -> Result<Option<UpdateCheckResult>, String> {
+ let channel = current_channel(&app);
+ Ok(check(&app).await?.map(|update| UpdateCheckResult {
+ version: update.version.clone(),
+ notes: update.body.clone(),
+ channel,
+ }))
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn updates_download_and_install(app: AppHandle) -> Result<(), String> {
+ let state = app.state::<UpdatesState>();
+
+ let pending = match state.pending.lock().await.clone() {
+ Some(pending) => pending,
+ None => {
+ let Some(update) = check(&app).await? else {
+ return Err("No update available".to_string());
+ };
+ PendingUpdate {
+ version: update.version.clone(),
+ update,
+ installed: false,
+ }
+ }
+ };
+
+ // The macOS background loop may have already installed this version
+ // silently; restarting is all that's left to do.
+ if pending.installed {
+ return Ok(());
+ }
+
+ let bytes = download_with_progress(&app, &pending.update).await?;
+
+ info!("Installing update {}", pending.version);
+ pending.update.install(bytes).map_err(|e| e.to_string())?;
+
+ let mut guard = state.pending.lock().await;
+ if let Some(p) = guard.as_mut()
+ && p.version == pending.version
+ {
+ p.installed = true;
+ }
+
+ Ok(())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub fn updates_channel_changed(app: AppHandle) -> Result<(), String> {
+ app.state::<UpdatesState>().notify.notify_one();
+ Ok(())
+}
+
+pub fn spawn_background_loop(app: AppHandle) {
+ // Never auto-update dev builds.
+ if cfg!(debug_assertions) {
+ return;
+ }
+
+ tokio::spawn(async move {
+ let mut delay = FIRST_CHECK_DELAY;
+
+ loop {
+ {
+ let state = app.state::<UpdatesState>();
+ tokio::select! {
+ _ = tokio::time::sleep(delay) => {}
+ _ = state.notify.notified() => {}
+ }
+ }
+
+ delay = CHECK_INTERVAL;
+
+ // Stable updates stay frontend-driven; this loop only owns nightly.
+ if current_channel(&app) != UpdateChannel::Nightly {
+ continue;
+ }
+
+ if is_busy(&app).await {
+ delay = BUSY_RETRY_DELAY;
+ continue;
+ }
+
+ let update = match check(&app).await {
+ Ok(Some(update)) => update,
+ Ok(None) => continue,
+ Err(err) => {
+ warn!("Nightly update check failed: {err}");
+ continue;
+ }
+ };
+
+ let version = update.version.clone();
+ let state = app.state::<UpdatesState>();
+
+ if state.announced_version.lock().await.as_deref() == Some(version.as_str()) {
+ continue;
+ }
+
+ let installed = if cfg!(target_os = "macos") {
+ let already_installed = state
+ .pending
+ .lock()
+ .await
+ .as_ref()
+ .is_some_and(|p| p.version == version && p.installed);
+
+ if already_installed {
+ true
+ } else {
+ let bytes = match update.download(|_, _| {}, || {}).await {
+ Ok(bytes) => bytes,
+ Err(err) => {
+ warn!("Failed to download nightly update {version}: {err}");
+ continue;
+ }
+ };
+
+ // A recording or export may have started mid-download;
+ // don't touch the install while one is running.
+ if is_busy(&app).await {
+ delay = BUSY_RETRY_DELAY;
+ continue;
+ }
+
+ // Safe while Cap runs: the .app bundle is swapped in place
+ // and takes effect on relaunch.
+ if let Err(err) = update.install(bytes) {
+ warn!("Failed to install nightly update {version}: {err}");
+ continue;
+ }
+
+ let mut pending = state.pending.lock().await;
+ if let Some(p) = pending.as_mut()
+ && p.version == version
+ {
+ p.installed = true;
+ }
+
+ info!("Nightly update {version} installed; restart to apply");
+ true
+ }
+ } else {
+ // Windows (NSIS) install exits the app mid-session and Linux
+ // (deb) prompts for privileges, so never auto-install there;
+ // announce and let the user trigger the install.
+ info!("Nightly update {version} available");
+ false
+ };
+
+ let _ = UpdateReady {
+ version: version.clone(),
+ installed,
+ }
+ .emit(&app);
+
+ *state.announced_version.lock().await = Some(version);
+ }
+ });
+}
diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
index 2d0edfb7d..4f2860cb8 100644
--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
@@ -14,8 +14,8 @@ import {
} from "@tauri-apps/api/webviewWindow";
import { getCurrentWindow, LogicalSize } from "@tauri-apps/api/window";
import * as dialog from "@tauri-apps/plugin-dialog";
+import { relaunch } from "@tauri-apps/plugin-process";
import * as shell from "@tauri-apps/plugin-shell";
-import * as updater from "@tauri-apps/plugin-updater";
import { cx } from "cva";
import {
createEffect,
@@ -30,8 +30,8 @@ import {
Suspense,
} from "solid-js";
import { createStore, produce, reconcile } from "solid-js/store";
-import { Transition } from "solid-transition-group";
import toast from "solid-toast";
+import { Transition } from "solid-transition-group";
import Mode from "~/components/Mode";
import { RecoveryToast } from "~/components/RecoveryToast";
import Tooltip from "~/components/Tooltip";
@@ -76,9 +76,9 @@ import {
type OSPermissionsCheck,
type RecordingTargetMode,
type ScreenCaptureTarget,
+ type UpdateCheckResult,
type UploadProgress,
} from "~/utils/tauri";
-import { getUpdaterCheckOptions } from "~/utils/updater";
import IconCapLogoFull from "~icons/cap/logo-full";
import IconCapLogoFullDark from "~icons/cap/logo-full-dark";
import IconLucideAppWindowMac from "~icons/lucide/app-window-mac";
@@ -1563,10 +1563,13 @@ function createUpdateCheck() {
await new Promise((res) => setTimeout(res, 10_000));
- let update: updater.Update | undefined;
+ // The Rust background loop owns nightly updates.
+ const settings = await generalSettingsStore.get();
+ if (settings?.updateChannel === "nightly") return;
+
+ let update: UpdateCheckResult | null = null;
try {
- const result = await updater.check(getUpdaterCheckOptions());
- if (result) update = result;
+ update = await commands.updatesCheck();
} catch (e) {
console.error("Failed to check for updates:", e);
return;
@@ -1590,6 +1593,51 @@ function createUpdateCheck() {
});
}
+function createUpdateReadyToast() {
+ createTauriEventListener(events.updateReady, (update) => {
+ toast.custom(
+ (t) => (
+ <div class="flex gap-3 items-center px-4 py-3 rounded-xl border shadow-lg bg-gray-1 border-gray-4 text-gray-12">
+ <p class="text-sm">
+ {update.installed
+ ? `Cap ${update.version} has been installed — restart to apply`
+ : `Cap ${update.version} is ready to install`}
+ </p>
+ <button
+ type="button"
+ class="px-2.5 py-1 text-xs font-medium rounded-lg transition-colors bg-blue-9 text-white hover:bg-blue-10"
+ onClick={() => {
+ toast.dismiss(t.id);
+ const install = update.installed
+ ? Promise.resolve(null)
+ : commands.updatesDownloadAndInstall();
+ // On Windows the NSIS installer restarts Cap itself, so the
+ // relaunch call is unreachable there; that matches update.tsx.
+ install
+ .then(() => relaunch())
+ .catch((e) => console.error("Failed to install update:", e));
+ }}
+ >
+ {update.installed ? "Restart now" : "Install and restart"}
+ </button>
+ <button
+ type="button"
+ class="px-2.5 py-1 text-xs font-medium rounded-lg transition-colors text-gray-11 hover:text-gray-12"
+ onClick={() => toast.dismiss(t.id)}
+ >
+ Dismiss
+ </button>
+ </div>
+ ),
+ {
+ // One toast per version: re-emissions replace instead of stacking.
+ id: `update-ready-${update.version}`,
+ duration: Number.POSITIVE_INFINITY,
+ },
+ );
+ });
+}
+
function MainWindowHelpButton() {
return (
<Tooltip content={<span>Help & Tour</span>}>
@@ -2137,6 +2185,7 @@ function Page() {
const setCamera = createCameraMutation();
createUpdateCheck();
+ createUpdateReadyToast();
onMount(async () => {
if (document.activeElement instanceof HTMLElement) {
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index 687ad08dd..6e653a426 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -5,7 +5,6 @@ import { getVersion } from "@tauri-apps/api/app";
import * as dialog from "@tauri-apps/plugin-dialog";
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import * as shell from "@tauri-apps/plugin-shell";
-import { check } from "@tauri-apps/plugin-updater";
import {
createEffect,
createMemo,
@@ -23,7 +22,7 @@ import { SignInButton } from "~/components/SignInButton";
import { authStore, userProfileStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { createSignInMutation } from "~/utils/auth";
-import { getUpdaterCheckOptions } from "~/utils/updater";
+import { commands } from "~/utils/tauri";
import {
apiClient,
getConfiguredServerUrl,
@@ -411,7 +410,7 @@ export default function Settings(props: RouteSectionProps) {
setIsCheckingForUpdates(true);
try {
- const update = await check(getUpdaterCheckOptions());
+ const update = await commands.updatesCheck();
if (!update) {
await dialog.message(
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index 071666afa..a654d34e1 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -41,6 +41,7 @@ import {
type PostDeletionBehaviour,
type PostStudioRecordingBehaviour,
type StudioRecordingQuality,
+ type UpdateChannel,
type WindowExclusion,
} from "~/utils/tauri";
import IconLucideAlertTriangle from "~icons/lucide/alert-triangle";
@@ -686,6 +687,18 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
isWindows={ostype === "windows"}
/>
+ <UpdatesSection
+ value={settings.updateChannel ?? "stable"}
+ onChange={async (channel) => {
+ await handleChange("updateChannel", channel);
+ try {
+ await commands.updatesChannelChanged();
+ } catch (error) {
+ console.error("Failed to notify update channel change", error);
+ }
+ }}
+ />
+
<ServerURLSetting
value={settings.serverUrl ?? clientEnv.VITE_SERVER_URL}
defaultValue={clientEnv.VITE_SERVER_URL}
@@ -820,6 +833,71 @@ function TelemetryCard(props: {
);
}
+type UpdateChannelOption = {
+ value: UpdateChannel;
+ label: string;
+ description: string;
+};
+
+const UPDATE_CHANNEL_OPTIONS: UpdateChannelOption[] = [
+ {
+ value: "stable",
+ label: "Stable",
+ description: "Versioned releases (recommended)",
+ },
+ {
+ value: "nightly",
+ label: "Nightly",
+ description:
+ "The newest builds, updated automatically in the background when you're not recording or exporting. May be unstable.",
+ },
+];
+
+function UpdatesSection(props: {
+ value: UpdateChannel;
+ onChange: (value: UpdateChannel) => void;
+}) {
+ const currentOption = createMemo(
+ () =>
+ UPDATE_CHANNEL_OPTIONS.find((option) => option.value === props.value) ??
+ UPDATE_CHANNEL_OPTIONS[0],
+ );
+
+ return (
+ <Section title="Updates" description="Choose which Cap builds you receive.">
+ <SectionCard>
+ <div class="flex flex-col gap-3 px-4 py-4">
+ <div class="flex justify-between items-start gap-4">
+ <div class="flex flex-col gap-0.5 min-w-0">
+ <p class="text-[13px] text-gray-12">Update channel</p>
+ <p class="text-xs leading-snug text-gray-10">
+ Which release channel Cap updates from.
+ </p>
+ </div>
+ <SegmentedControl
+ value={props.value}
+ onChange={props.onChange}
+ options={UPDATE_CHANNEL_OPTIONS.map((option) => ({
+ value: option.value,
+ label: option.label,
+ }))}
+ />
+ </div>
+ <div class="flex flex-col gap-1.5 px-3 py-2.5 rounded-lg bg-gray-3">
+ <p class="text-xs text-gray-12">{currentOption().description}</p>
+ <Show when={props.value === "nightly"}>
+ <p class="text-[11px] text-gray-10 leading-snug">
+ Switching back to Stable will return you to the latest stable
+ version, which may be older than your current build.
+ </p>
+ </Show>
+ </div>
+ </div>
+ </SectionCard>
+ </Section>
+ );
+}
+
type StudioQualityTier = {
value: StudioRecordingQuality;
label: string;
diff --git a/apps/desktop/src/routes/(window-chrome)/update.tsx b/apps/desktop/src/routes/(window-chrome)/update.tsx
index fe997f645..ca9cb960f 100644
--- a/apps/desktop/src/routes/(window-chrome)/update.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/update.tsx
@@ -2,9 +2,15 @@ import { Button } from "@cap/ui-solid";
import { useNavigate } from "@solidjs/router";
import { getCurrentWindow, UserAttentionType } from "@tauri-apps/api/window";
import { relaunch } from "@tauri-apps/plugin-process";
-import { check } from "@tauri-apps/plugin-updater";
-import { createResource, createSignal, Match, Show, Switch } from "solid-js";
-import { getUpdaterCheckOptions } from "~/utils/updater";
+import {
+ createResource,
+ createSignal,
+ Match,
+ onCleanup,
+ Show,
+ Switch,
+} from "solid-js";
+import { commands, events } from "~/utils/tauri";
export default function () {
const navigate = useNavigate();
@@ -12,7 +18,7 @@ export default function () {
const [update] = createResource(async () => {
try {
- const update = await check(getUpdaterCheckOptions());
+ const update = await commands.updatesCheck();
if (!update) return;
return update;
} catch (e) {
@@ -46,51 +52,37 @@ export default function () {
}
keyed
>
- {(update) => {
+ {(_update) => {
type UpdateStatus =
| { type: "downloading"; progress: number; contentLength?: number }
| { type: "done" };
- const [updateStatus, updateStatusActions] =
- createResource<UpdateStatus>(
- () =>
- new Promise<UpdateStatus>((resolve) => {
- update
- .downloadAndInstall((e) => {
- if (e.event === "Started") {
- resolve({
- type: "downloading",
- progress: 0,
- contentLength: e.data.contentLength,
- });
- } else if (e.event === "Progress") {
- const status = updateStatus();
- if (
- !status ||
- status.type !== "downloading" ||
- status.contentLength === undefined
- )
- return;
- updateStatusActions.mutate({
- ...status,
- progress: e.data.chunkLength + status.progress,
- });
- }
- })
- .then(async () => {
- updateStatusActions.mutate({ type: "done" });
- getCurrentWindow().requestUserAttention(
- UserAttentionType.Informational,
- );
- })
- .catch((e) => {
- console.error("Failed to download/install update:", e);
- setUpdateError(
- "Failed to download or install the update.",
- );
- });
- }),
- );
+ const [updateStatus, setUpdateStatus] = createSignal<UpdateStatus>();
+
+ const unlisten = events.updateDownloadProgress.listen((e) => {
+ if (updateStatus()?.type === "done") return;
+ setUpdateStatus({
+ type: "downloading",
+ progress: e.payload.downloaded,
+ contentLength: e.payload.total ?? undefined,
+ });
+ });
+ onCleanup(() => {
+ unlisten.then((cleanup) => cleanup());
+ });
+
+ commands
+ .updatesDownloadAndInstall()
+ .then(() => {
+ setUpdateStatus({ type: "done" });
+ getCurrentWindow().requestUserAttention(
+ UserAttentionType.Informational,
+ );
+ })
+ .catch((e) => {
+ console.error("Failed to download/install update:", e);
+ setUpdateError("Failed to download or install the update.");
+ });
return (
<div>
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index d0daef9d8..f7fd0df82 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -471,6 +471,15 @@ async automationShouldOpenScreenshotEditor(target: ScreenCaptureTarget) : Promis
},
async listAutomationCapabilities() : Promise<string[]> {
return await TAURI_INVOKE("list_automation_capabilities");
+},
+async updatesCheck() : Promise<UpdateCheckResult | null> {
+ return await TAURI_INVOKE("updates_check");
+},
+async updatesDownloadAndInstall() : Promise<null> {
+ return await TAURI_INVOKE("updates_download_and_install");
+},
+async updatesChannelChanged() : Promise<null> {
+ return await TAURI_INVOKE("updates_channel_changed");
}
}
@@ -504,6 +513,8 @@ requestSetTargetMode: RequestSetTargetMode,
requestStartRecording: RequestStartRecording,
setCaptureAreaPending: SetCaptureAreaPending,
targetUnderCursor: TargetUnderCursor,
+updateDownloadProgress: UpdateDownloadProgress,
+updateReady: UpdateReady,
uploadProgressEvent: UploadProgressEvent,
videoImportProgress: VideoImportProgress
}>({
@@ -533,6 +544,8 @@ requestSetTargetMode: "request-set-target-mode",
requestStartRecording: "request-start-recording",
setCaptureAreaPending: "set-capture-area-pending",
targetUnderCursor: "target-under-cursor",
+updateDownloadProgress: "update-download-progress",
+updateReady: "update-ready",
uploadProgressEvent: "upload-progress-event",
videoImportProgress: "video-import-progress"
})
@@ -755,7 +768,7 @@ previousRecordingsPaths?: string[];
* Cleared automatically when the app version changes (one retry per
* update, since a new ort/wgpu/driver stack may have fixed the crash).
*/
-cameraBlurDisabledByCrash?: string | null }
+cameraBlurDisabledByCrash?: string | null; updateChannel?: UpdateChannel }
export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }
export type GifQuality = {
/**
@@ -896,6 +909,10 @@ export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments:
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number; name?: string | null }
export type TranscriptionEngine = "Whisper" | "Parakeet"
export type Trigger = "screenshotTaken" | "studioRecordingFinished" | "instantRecordingFinished" | "recordingStarted" | "uploadCompleted" | "videoImported" | "recordingDeleted"
+export type UpdateChannel = "stable" | "nightly"
+export type UpdateCheckResult = { version: string; notes: string | null; channel: UpdateChannel }
+export type UpdateDownloadProgress = { downloaded: number; total: number | null }
+export type UpdateReady = { version: string; installed: boolean }
export type UploadMeta = { state: "MultipartUpload"; video_id: string; file_path: string; pre_created_video: VideoUploadInfo; recording_dir: string } | { state: "SinglePartUpload"; video_id: string; recording_dir: string; file_path: string; screenshot_path: string } | { state: "SegmentUpload"; video_id: string; pre_created_video: VideoUploadInfo; recording_dir: string } | { state: "Failed"; error: string } | { state: "Complete" }
export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null } } | "Reupload"
export type UploadProgress = { progress: number }