Desktop D5 app: --self-test (sidecar handshake, no window) for release smoke tests; Settings > Updates checks and installs signed updates after a native dialog; storebound://open?path= adds or selects an app folder after asking

This commit is contained in:
CRTkafa 2026-10-11 05:16:59 +08:00
parent 1a8d817cb2
commit c68ef8acd0
19 changed files with 514 additions and 9 deletions

View file

@ -43,6 +43,8 @@
"allow-cache-info", "allow-cache-info",
"allow-data-reveal", "allow-data-reveal",
"allow-notify", "allow-notify",
"allow-app-reset" "allow-app-reset",
"allow-update-check",
"allow-update-install"
] ]
} }

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Hardened runtime entitlements of the Developer ID build (tools/desktop-release.ts). Tauri signs the app and the
bundled CLI sidecar with the same file; the sidecar is a Bun single-file executable whose JavaScriptCore
JIT needs these two. Nothing else is granted (no library validation exceptions, no sandbox escapes). -->
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
</dict>
</plist>

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-update-check"
description = "Enables the update_check command without any pre-configured scope."
commands.allow = ["update_check"]
[[permission]]
identifier = "deny-update-check"
description = "Denies the update_check command without any pre-configured scope."
commands.deny = ["update_check"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-update-install"
description = "Enables the update_install command without any pre-configured scope."
commands.allow = ["update_install"]
[[permission]]
identifier = "deny-update-install"
description = "Denies the update_install command without any pre-configured scope."
commands.deny = ["update_install"]

View file

@ -17,6 +17,7 @@ use crate::downloads;
use crate::policy::{self, Kind}; use crate::policy::{self, Kind};
use crate::sidecar::{valid_job, Fail, Progress, Sidecar}; use crate::sidecar::{valid_job, Fail, Progress, Sidecar};
use crate::store::{self, Project, State as Saved}; use crate::store::{self, Project, State as Saved};
use crate::updates;
use crate::workspace::{self, Overrides, Settings, StoreTarget, Studio}; use crate::workspace::{self, Overrides, Settings, StoreTarget, Studio};
pub struct AppState { pub struct AppState {
@ -902,3 +903,132 @@ pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res
state.cache.clear().map_err(Fail::host)?; state.cache.clear().map_err(Fail::host)?;
Ok(true) Ok(true)
} }
// ---------------------------------------------------------------------------------------------------------------------
// Updates (Settings > Updates): signed bundles from storebound.dev, installed only after the owner's click.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateInfo {
pub current: String,
pub channel: String,
/// The newer version on the channel, if any.
pub available: Option<String>,
pub notes: Option<String>,
pub date: Option<String>,
}
async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plugin_updater::Update>> {
use tauri_plugin_updater::UpdaterExt;
let url = url::Url::parse(updates::endpoint(channel)).map_err(|e| Fail::host(e.to_string()))?;
if !updates::endpoint_allowed(&url) {
return Err(Fail::host("update endpoint not allowed"));
}
let updater = app
.updater_builder()
.endpoints(vec![url])
.map_err(|e| Fail::host(e.to_string()))?
.timeout(std::time::Duration::from_secs(30))
.build()
.map_err(|e| Fail::host(updates::error_text(&e.to_string())))?;
updater.check().await.map_err(|e| Fail::host(updates::error_text(&e.to_string())))
}
/// Asks storebound.dev whether the chosen channel has a newer version. Reads only; installs nothing.
#[tauri::command]
pub async fn update_check(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<UpdateInfo> {
guard(&window)?;
let channel = saved(&state)?.settings.channel.clone();
let found = find_update(&app, &channel).await?;
Ok(UpdateInfo {
current: env!("CARGO_PKG_VERSION").into(),
channel,
available: found.as_ref().map(|u| u.version.clone()),
notes: found.as_ref().and_then(|u| u.body.clone()),
date: found.as_ref().and_then(|u| u.date).and_then(|d| u64::try_from(d.unix_timestamp()).ok()).map(store::iso_from_unix),
})
}
/// Installs `version` (the one the window showed) after a native dialog: download, signature check against the key
/// in tauri.conf.json, install, restart. False = the owner said no. Progress goes to the window as `update-progress`.
#[tauri::command]
pub async fn update_install(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, version: String) -> Res<bool> {
guard(&window)?;
let channel = saved(&state)?.settings.channel.clone();
let Some(update) = find_update(&app, &channel).await? else {
return Err(Fail::host("no update available"));
};
if update.version != version {
return Err(Fail::host(format!("storebound.dev now offers {} instead of {version}: check again", update.version)));
}
let text = format!(
"storebound {version} is ready (this is {}).\n\nThe update comes from storebound.dev; its signature is checked against this app's key before anything is replaced. Then storebound restarts.",
env!("CARGO_PKG_VERSION")
);
if !confirm_dialog_with(&window, "Install the update?".into(), text, "Install and restart".into()).await? {
return Ok(false);
}
// the sidecar binary lives inside the app bundle that is about to be replaced
state.sidecar.shutdown().await;
let w = window.clone();
let mut received: u64 = 0;
update
.download_and_install(
move |n, total| {
received += n as u64;
let _ = w.emit("update-progress", json!({ "received": received, "total": total }));
},
|| {},
)
.await
.map_err(|e| Fail::host(updates::error_text(&e.to_string())))?;
app.restart();
}
// ---------------------------------------------------------------------------------------------------------------------
// storebound://open?path=<folder> (`storebound desktop` in a terminal): select that app folder, or add it after a
// native dialog. Not a command: lib.rs calls it for a deep link.
fn tell(app: &AppHandle, text: String) {
let mut d = app.dialog().message(text).title("storebound").kind(MessageDialogKind::Info);
if let Some(w) = app.get_webview_window(policy::MAIN) {
d = d.parent(&w);
}
d.show(|_| {});
}
pub async fn open_folder_link(app: AppHandle, dir: PathBuf) {
if let Err(e) = open_folder(&app, &dir).await {
tell(&app, e.message);
}
}
async fn open_folder(app: &AppHandle, dir: &Path) -> Res<()> {
let state = app.state::<AppState>();
let window = app.get_webview_window(policy::MAIN).ok_or_else(|| Fail::host("no main window"))?;
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
let shown = tilde(&dir.to_string_lossy(), home.as_deref());
let dir = std::fs::canonicalize(dir).map_err(|_| Fail::host(format!("{shown} does not exist")))?;
if !dir.is_dir() {
return Err(Fail::host(format!("{shown} is not a folder")));
}
if !has_config(&dir) {
return Err(Fail::host(format!(
"{shown} has no storebound config.\n\nStart one with `storebound init` in that folder, or in storebound: App folders > Start an app folder."
)));
}
let path = dir.to_string_lossy().to_string();
let known = saved(&state)?.projects.iter().find(|p| p.path == path).map(|p| p.id.clone());
let id = match known {
Some(id) => id,
None => {
let text = format!("{}\n\nAdd this app folder to storebound? Nothing in the folder changes.", tilde(&path, home.as_deref()));
if !confirm_dialog_with(&window, "Add an app folder".into(), text, "Add folder".into()).await? {
return Ok(());
}
add_folder(app, &state, &dir).await?.id
}
};
let _ = app.emit_to(policy::MAIN, "deep-link-folder", id);
Ok(())
}

View file

@ -36,4 +36,6 @@ pub const COMMANDS: &[&str] = &[
"data_reveal", "data_reveal",
"notify", "notify",
"app_reset", "app_reset",
"update_check",
"update_install",
]; ];

View file

@ -6,6 +6,8 @@ pub mod commands;
pub mod confirm; pub mod confirm;
pub mod downloads; pub mod downloads;
pub mod policy; pub mod policy;
pub mod selftest;
pub mod updates;
pub mod sidecar; pub mod sidecar;
pub mod store; pub mod store;
pub mod workspace; pub mod workspace;
@ -87,8 +89,11 @@ fn menu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Menu<R>> {
Menu::with_items(app, &[&app_menu, &edit, &window]) Menu::with_items(app, &[&app_menu, &edit, &window])
} }
fn handle_deep_link<R: Runtime>(app: &AppHandle<R>, urls: &[url::Url]) { fn handle_deep_link(app: &AppHandle, urls: &[url::Url]) {
if let Some(screen) = urls.iter().find_map(policy::deep_link_screen) { if let Some(dir) = urls.iter().find_map(policy::deep_link_open_path) {
show_main(app);
tauri::async_runtime::spawn(commands::open_folder_link(app.clone(), dir));
} else if let Some(screen) = urls.iter().find_map(policy::deep_link_screen) {
show_main(app); show_main(app);
let _ = app.emit_to(policy::MAIN, "deep-link", screen); let _ = app.emit_to(policy::MAIN, "deep-link", screen);
} }
@ -214,6 +219,8 @@ pub fn run() {
commands::data_reveal, commands::data_reveal,
commands::notify, commands::notify,
commands::app_reset, commands::app_reset,
commands::update_check,
commands::update_install,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("storebound desktop failed to start"); .expect("storebound desktop failed to start");

View file

@ -2,5 +2,10 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() { fn main() {
// Release smoke test of the exact artifact (tools/desktop-release.ts, the Forgejo workflow): sidecar handshake,
// one JSON line, exit. Runs before Tauri starts, so no window opens.
if std::env::args().skip(1).any(|a| a == storebound_desktop::selftest::FLAG) {
std::process::exit(storebound_desktop::selftest::run());
}
storebound_desktop::run(); storebound_desktop::run();
} }

View file

@ -150,3 +150,26 @@ pub fn deep_link_screen(url: &Url) -> Option<&'static str> {
let host = url.host_str().unwrap_or_default(); let host = url.host_str().unwrap_or_default();
DEEP_LINK_SCREENS.iter().copied().find(|s| *s == host) DEEP_LINK_SCREENS.iter().copied().find(|s| *s == host)
} }
/// `storebound://open?path=<absolute folder>` (what `storebound desktop` sends from a terminal): the folder to add or
/// select. Only an absolute, plain path: no `..`, no NUL or control characters, at most 4096 bytes, one `path`
/// parameter and nothing else. The host still checks that it is a folder with a storebound config and asks the owner
/// in a native dialog before adding it.
pub fn deep_link_open_path(url: &Url) -> Option<std::path::PathBuf> {
if url.scheme() != "storebound" || url.host_str() != Some("open") || !url.username().is_empty() || url.password().is_some() || url.port().is_some() {
return None;
}
if !(url.path().is_empty() || url.path() == "/") || url.fragment().is_some() {
return None;
}
let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let [(k, v)] = pairs.as_slice() else { return None };
if k != "path" || v.is_empty() || v.len() > 4096 || v.chars().any(char::is_control) {
return None;
}
let p = std::path::PathBuf::from(v);
if !p.is_absolute() || p.components().any(|c| matches!(c, std::path::Component::ParentDir | std::path::Component::CurDir)) {
return None;
}
Some(p)
}

View file

@ -0,0 +1,99 @@
//! `storebound-desktop --self-test`: the release smoke test of the exact artifact. It starts the bundled sidecar the
//! same way the app does (next to the executable, policy::SIDECAR_ARGS), sends `session.hello` with a fresh secret,
//! checks the protocol, prints one JSON line and exits. No window, no webview, no Tauri runtime: it runs headless
//! (a CI runner, a mounted DMG, an SSH session) and never brings anything to the front.
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use serde_json::{json, Value};
use crate::{confirm, policy};
pub const FLAG: &str = "--self-test";
const PROTOCOL: &str = "storebound-desktop/1";
/// The bundled sidecar: Tauri puts `externalBin` next to the main executable without its target triple
/// (Contents/MacOS on macOS, the install folder on Windows, usr/bin in the AppImage and the deb).
pub fn sidecar_path() -> Result<PathBuf, String> {
let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
let dir = exe.parent().ok_or("the executable has no folder")?;
Ok(dir.join(format!("{}{}", policy::SIDECAR, std::env::consts::EXE_SUFFIX)))
}
/// Exit code of the self-test (0 = the sidecar answered with the expected protocol).
pub fn run() -> i32 {
match check(Duration::from_secs(30)) {
Ok(v) => {
println!("{v}");
0
}
Err(e) => {
eprintln!("self-test failed: {e}");
1
}
}
}
pub fn check(timeout: Duration) -> Result<Value, String> {
let bin = sidecar_path()?;
if !bin.is_file() {
return Err(format!("no sidecar next to the executable ({})", bin.file_name().unwrap_or_default().to_string_lossy()));
}
let started = Instant::now();
let mut child = Command::new(&bin)
.args(policy::SIDECAR_ARGS)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("sidecar did not start: {e}"))?;
let secret = confirm::new_secret()?;
let hello = json!({ "jsonrpc": "2.0", "id": 1, "method": "session.hello",
"params": { "secret": confirm::hex(&secret), "client": { "name": "storebound-desktop-self-test", "version": env!("CARGO_PKG_VERSION") } } });
let mut stdin = child.stdin.take().ok_or("no sidecar stdin")?;
let line = format!("{hello}\n");
let stdout = child.stdout.take().ok_or("no sidecar stdout")?;
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
for l in BufReader::new(stdout).lines().map_while(Result::ok) {
if let Ok(v) = serde_json::from_str::<Value>(&l) {
if v.get("id").and_then(Value::as_u64) == Some(1) {
let _ = tx.send(v);
return;
}
}
}
});
let wrote = stdin.write_all(line.as_bytes()).and_then(|_| stdin.flush());
let answer = rx.recv_timeout(timeout);
drop(stdin);
let _ = child.kill();
let _ = child.wait();
wrote.map_err(|e| format!("sidecar stdin: {e}"))?;
let answer = answer.map_err(|_| format!("no answer to session.hello within {} s", timeout.as_secs()))?;
if let Some(e) = answer.get("error") {
return Err(format!("session.hello failed: {e}"));
}
let r = &answer["result"];
let protocol = r["protocol"].as_str().unwrap_or_default();
if protocol != PROTOCOL {
return Err(format!("unsupported sidecar protocol '{protocol}'"));
}
let methods = r["methods"].as_array().map(Vec::len).unwrap_or(0);
if methods == 0 {
return Err("the sidecar announced no methods".into());
}
Ok(json!({
"ok": true,
"app": env!("CARGO_PKG_VERSION"),
"sidecar": r["server"]["version"],
"protocol": protocol,
"methods": methods,
"ms": started.elapsed().as_millis() as u64,
"os": std::env::consts::OS,
"arch": std::env::consts::ARCH,
}))
}

View file

@ -0,0 +1,37 @@
//! Signed updates from storebound.dev. The updater plugin checks `latest.json` of the chosen channel, downloads the
//! platform's bundle and refuses it unless its minisign signature matches the public key in tauri.conf.json (the
//! private key never leaves the release machine, ~/.storebound-keys). Nothing installs without the owner's click in
//! a native dialog (commands::update_install). Pure parts here so tests can pin them.
use url::Url;
/// `latest.json` of each channel (static files on storebound.dev, published by tools/desktop-release.ts).
pub const STABLE: &str = "https://storebound.dev/desktop/latest.json";
pub const BETA: &str = "https://storebound.dev/desktop/beta/latest.json";
/// The endpoint of a channel (Settings > Updates); anything unknown is the stable channel.
pub fn endpoint(channel: &str) -> &'static str {
if channel == "beta" {
BETA
} else {
STABLE
}
}
/// Only storebound.dev over HTTPS, without port or user info, may serve updates.
pub fn endpoint_allowed(url: &Url) -> bool {
url.scheme() == "https" && url.host_str() == Some("storebound.dev") && url.port().is_none() && url.username().is_empty() && url.password().is_none() && url.path().starts_with("/desktop/")
}
/// The updater's error in words the owner can act on.
pub fn error_text(e: &str) -> String {
let l = e.to_lowercase();
if l.contains("signature") {
"the update's signature does not match this app's key: not installed".into()
} else if l.contains("404") || l.contains("not found") {
"no update information on storebound.dev yet".into()
} else if l.contains("platform") {
"no update for this system in the latest release yet".into()
} else {
format!("update check failed: {e}")
}
}

View file

@ -0,0 +1,104 @@
//! D5 release pipeline: one version everywhere, the updater's key and endpoints, the `storebound://open?path=` deep
//! link and the self-test the release runs on the exact artifact.
use std::fs;
use std::path::PathBuf;
use base64::Engine;
use serde_json::Value;
use storebound_desktop::policy::deep_link_open_path;
use storebound_desktop::{selftest, updates};
use url::Url;
fn root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn conf() -> Value {
serde_json::from_str(&fs::read_to_string(root().join("tauri.conf.json")).unwrap()).unwrap()
}
#[test]
fn one_version_from_the_root_package_json() {
let pkg: Value = serde_json::from_str(&fs::read_to_string(root().join("../../../package.json")).unwrap()).unwrap();
let want = pkg["desktopVersion"].as_str().expect("package.json desktopVersion");
assert_eq!(env!("CARGO_PKG_VERSION"), want, "Cargo.toml (bun tools/desktop-version.ts --set {want})");
assert_eq!(conf()["version"], want, "tauri.conf.json");
let app: Value = serde_json::from_str(&fs::read_to_string(root().join("../package.json")).unwrap()).unwrap();
assert_eq!(app["version"], want, "apps/desktop/package.json");
}
#[test]
fn updater_has_a_real_minisign_key_and_only_storebound_dev() {
let c = conf();
let key = c["plugins"]["updater"]["pubkey"].as_str().unwrap();
let text = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(key).expect("base64 pubkey")).unwrap();
let mut lines = text.lines();
assert!(lines.next().unwrap().starts_with("untrusted comment: minisign public key"));
let raw = base64::engine::general_purpose::STANDARD.decode(lines.next().unwrap()).unwrap();
assert_eq!(raw.len(), 42, "Ed + key id + 32-byte key");
assert_eq!(&raw[..2], b"Ed");
assert_eq!(c["plugins"]["updater"]["endpoints"], serde_json::json!([updates::STABLE]));
// updater bundles are signed by tools/desktop-release.ts on the release Mac, never by a CI runner
assert_eq!(c["bundle"]["createUpdaterArtifacts"], false);
for ch in ["stable", "beta", "nightly", ""] {
assert!(updates::endpoint_allowed(&Url::parse(updates::endpoint(ch)).unwrap()), "{ch}");
}
assert_eq!(updates::endpoint("beta"), updates::BETA);
assert_eq!(updates::endpoint("anything"), updates::STABLE);
for bad in ["http://storebound.dev/desktop/latest.json", "https://storebound.dev:8443/desktop/latest.json", "https://evil.test/desktop/latest.json", "https://storebound.dev/latest.json"] {
assert!(!updates::endpoint_allowed(&Url::parse(bad).unwrap()), "{bad}");
}
assert!(updates::error_text("signature verification failed").contains("not installed"));
}
#[test]
fn open_deep_link_takes_one_plain_absolute_path() {
let p = |s: &str| deep_link_open_path(&Url::parse(s).unwrap());
let abs = if cfg!(windows) { "C:%5Cgames%5CDemo App" } else { "%2FUsers%2Fyou%2Fgames%2FDemo App" };
let want = if cfg!(windows) { "C:\\games\\Demo App" } else { "/Users/you/games/Demo App" };
assert_eq!(p(&format!("storebound://open?path={abs}")), Some(PathBuf::from(want)));
assert_eq!(p(&format!("storebound://open/?path={abs}")), Some(PathBuf::from(want)));
for bad in [
"storebound://open?path=games%2FDemo App".to_string(),
"storebound://open?path=".to_string(),
"storebound://open".to_string(),
format!("storebound://open?path={abs}&path={abs}"),
format!("storebound://open?path={abs}&run=1"),
format!("storebound://open?path={abs}%2F..%2F..%2Fetc"),
format!("storebound://open?path={abs}%0A"),
format!("storebound://open/x?path={abs}"),
format!("storebound://open?path={abs}#f"),
format!("storebound://user@open?path={abs}"),
format!("storebound://apps?path={abs}"),
format!("https://open?path={abs}"),
format!("storebound://open?path={}", "a".repeat(5000)),
] {
assert_eq!(p(&bad), None, "{bad}");
}
}
#[test]
fn self_test_looks_for_the_sidecar_next_to_the_executable() {
let p = selftest::sidecar_path().unwrap();
let exe = std::env::current_exe().unwrap();
assert_eq!(p.parent(), exe.parent());
assert_eq!(p.file_name().unwrap().to_string_lossy(), format!("storebound{}", std::env::consts::EXE_SUFFIX));
assert_eq!(selftest::FLAG, "--self-test");
// the flag is handled in main before Tauri starts, so no window opens
let main = fs::read_to_string(root().join("src/main.rs")).unwrap();
let flag = main.find("selftest::FLAG").unwrap();
assert!(flag < main.find("storebound_desktop::run()").unwrap());
}
#[test]
fn deep_links_to_folders_ask_before_adding() {
let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap();
let at = cmds.find("async fn open_folder(").unwrap();
let body = &cmds[at..];
let confirm = body.find("confirm_dialog_with(").unwrap();
let add = body.find("add_folder(").unwrap();
assert!(confirm < add, "the native dialog comes before add_folder");
let at = cmds.find("pub async fn update_install(").unwrap();
let body = &cmds[at..];
assert!(body.find("confirm_dialog_with(").unwrap() < body.find("download_and_install(").unwrap());
}

View file

@ -173,6 +173,12 @@ fn sidecar_starts_with_fixed_arguments_from_one_place() {
assert!(src.contains(".args(policy::SIDECAR_ARGS)")); assert!(src.contains(".args(policy::SIDECAR_ARGS)"));
} }
assert!(!src.contains(".command("), "{}: no other programs are started", p.display()); assert!(!src.contains(".command("), "{}: no other programs are started", p.display());
// the release self-test (--self-test) starts the bundled sidecar with the same fixed arguments, nothing else
if p.ends_with("selftest.rs") {
assert_eq!(src.matches("Command::new(").count(), 1);
assert!(src.contains("Command::new(&bin)\n .args(policy::SIDECAR_ARGS)"));
continue;
}
// other programs: only the download checks (unpack, signature, version banner), with fixed program names // other programs: only the download checks (unpack, signature, version banner), with fixed program names
if src.contains("Command::new(") { if src.contains("Command::new(") {
assert!(p.ends_with("downloads.rs"), "{} starts a program", p.display()); assert!(p.ends_with("downloads.rs"), "{} starts a program", p.display());

View file

@ -1,7 +1,7 @@
// Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh), // Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh),
// the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. // the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide.
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { FIXTURES, onDeepLink } from './api'; import { FIXTURES, onDeepLink, onDeepLinkFolder } from './api';
import { devSwitch } from './dev/switches'; import { devSwitch } from './dev/switches';
import { type Key, t } from './i18n'; import { type Key, t } from './i18n';
import { ago } from './lib/format'; import { ago } from './lib/format';
@ -61,8 +61,10 @@ export function App({ onTheme }: { onTheme: () => void }) {
useEffect(() => { useEffect(() => {
const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); }); const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); });
return () => { un.then(f => f()); }; // `storebound desktop` in an app folder: the host added (after its native dialog) or found that folder
}, [go]); const unFolder = onDeepLinkFolder(id => { d.reload().catch(() => {}).finally(() => go({ screen: 'app', appId: id, tab: 'releases' })); });
return () => { un.then(f => f()); unFolder.then(f => f()); };
}, [go, d.reload]);
const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined; const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined;
const tabs = app ? tabsFor(!!app.project) : []; const tabs = app ? tabsFor(!!app.project) : [];

View file

@ -38,6 +38,7 @@ export interface CacheEntry<T = unknown> { value: T; at: string }
export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string } export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string }
export interface DownloadEvent { job: string; tool: string; stage: 'resolve' | 'download' | 'verify' | 'unpack' | 'install' | 'done' | 'error' | 'cancelled'; received: number; total: number | null; message?: string } export interface DownloadEvent { job: string; tool: string; stage: 'resolve' | 'download' | 'verify' | 'unpack' | 'install' | 'done' | 'error' | 'cancelled'; received: number; total: number | null; message?: string }
export type { IconResult as Icon }; export type { IconResult as Icon };
export interface UpdateInfo { current: string; channel: 'stable' | 'beta'; available: string | null; notes: string | null; date: string | null }
/** What a failed command rejects with (sidecar.rs `Fail`). */ /** What a failed command rejects with (sidecar.rs `Fail`). */
export interface Fail { code: number; message: string; data?: unknown } export interface Fail { code: number; message: string; data?: unknown }
@ -111,6 +112,10 @@ export const api = {
toolsInfo: () => invoke<DownloadInfo[]>('tools_info'), toolsInfo: () => invoke<DownloadInfo[]>('tools_info'),
installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke<string>('tools_install', { tool, job }), installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke<string>('tools_install', { tool, job }),
uninstallTool: (tool: 'ffmpeg' | 'chrome') => invoke<void>('tools_uninstall', { tool }), uninstallTool: (tool: 'ffmpeg' | 'chrome') => invoke<void>('tools_uninstall', { tool }),
/** Asks storebound.dev for a newer version on the chosen channel (installs nothing). */
updateCheck: () => invoke<UpdateInfo>('update_check'),
/** Native dialog, then download, signature check, install and restart. False = not installed. */
updateInstall: (version: string) => invoke<boolean>('update_install', { version }),
}; };
/** Typed reads of the project files (offline) and the stores (network). */ /** Typed reads of the project files (offline) and the stores (network). */
@ -125,3 +130,6 @@ export const onProgress = (cb: (p: ProgressEvent) => void): Promise<UnlistenFn>
listen<{ params: ProgressParams; job?: string }>('sidecar-progress', e => cb({ ...e.params, job: e.job })); listen<{ params: ProgressParams; job?: string }>('sidecar-progress', e => cb({ ...e.params, job: e.job }));
export const onDownload = (cb: (e: DownloadEvent) => void): Promise<UnlistenFn> => listen<DownloadEvent>('tool-download', cb); export const onDownload = (cb: (e: DownloadEvent) => void): Promise<UnlistenFn> => listen<DownloadEvent>('tool-download', cb);
export const onDeepLink = (cb: (screen: string) => void): Promise<UnlistenFn> => listen<string>('deep-link', cb); export const onDeepLink = (cb: (screen: string) => void): Promise<UnlistenFn> => listen<string>('deep-link', cb);
/** storebound://open?path=... selected or added an app folder (its project id). */
export const onDeepLinkFolder = (cb: (projectId: string) => void): Promise<UnlistenFn> => listen<string>('deep-link-folder', cb);
export const onUpdateProgress = (cb: (p: { received: number; total: number | null }) => void): Promise<UnlistenFn> => listen('update-progress', cb);

View file

@ -463,6 +463,8 @@ async function answer(cmd: string, a: Record<string, unknown>): Promise<unknown>
case 'cache_info': return { rows: 214, bytes: 3_412_000, oldest: iso(60 * 24 * 26), file_bytes: 4_718_592 }; case 'cache_info': return { rows: 214, bytes: 3_412_000, oldest: iso(60 * 24 * 26), file_bytes: 4_718_592 };
case 'data_reveal': case 'notify': return null; case 'data_reveal': case 'notify': return null;
case 'app_reset': return false; case 'app_reset': return false;
case 'update_check': await sleep(300); return { current: '0.1.0', channel: settings.channel, available: null, notes: null, date: null };
case 'update_install': return false;
case 'portfolio_status': { case 'portfolio_status': {
const stores = (a.stores as string[] | undefined) ?? []; const stores = (a.stores as string[] | undefined) ?? [];
if (a.live) { if (a.live) {

View file

@ -763,7 +763,13 @@ export const en = {
'set.channel': 'Channel', 'set.channel': 'Channel',
'set.stable': 'Stable', 'set.stable': 'Stable',
'set.beta': 'Beta', 'set.beta': 'Beta',
'set.updatesText': 'Signed updates from storebound.dev arrive with the first public desktop release; the channel is kept for then.', 'set.updatesText': 'Updates come from storebound.dev and are signed; the app checks the signature before it replaces anything, and installs only when you press Install. Nothing is checked in the background.',
'set.updateCheck': 'Check for updates',
'set.updateChecking': 'Checking…',
'set.updateNone': 'storebound {version} is the newest version on the {channel} channel.',
'set.updateAvailable': 'storebound {version} is available.',
'set.updateInstall': 'Install {version}…',
'set.updateInstalling': 'Downloading the update… {done}',
'set.reset': 'Reset', 'set.reset': 'Reset',
'set.resetText': 'Forgets {accounts} accounts (their keys are removed from the keychain), {studios} studios, {folders} app folders (the folders stay on disk), pairing, the ignore list, settings and saved reads. A system dialog asks first.', 'set.resetText': 'Forgets {accounts} accounts (their keys are removed from the keychain), {studios} studios, {folders} app folders (the folders stay on disk), pairing, the ignore list, settings and saved reads. A system dialog asks first.',
'set.resetButton': 'Reset the app', 'set.resetButton': 'Reset the app',

View file

@ -765,7 +765,13 @@ export const tr: Record<keyof typeof en, string> = {
'set.channel': 'Kanal', 'set.channel': 'Kanal',
'set.stable': 'Kararlı', 'set.stable': 'Kararlı',
'set.beta': 'Beta', 'set.beta': 'Beta',
'set.updatesText': 'storebound.dev\'den imzalı güncellemeler ilk herkese açık masaüstü sürümüyle gelir; kanal o zaman için saklanır.', 'set.updatesText': 'Güncellemeler storebound.dev\'den imzalı gelir; uygulama bir şeyi değiştirmeden önce imzayı denetler ve yalnızca siz Yükle\'ye bastığınızda yükler. Arka planda denetim yapılmaz.',
'set.updateCheck': 'Güncellemeleri denetle',
'set.updateChecking': 'Denetleniyor…',
'set.updateNone': 'storebound {version}, {channel} kanalındaki en yeni sürüm.',
'set.updateAvailable': 'storebound {version} çıktı.',
'set.updateInstall': '{version} sürümünü yükle…',
'set.updateInstalling': 'Güncelleme indiriliyor… {done}',
'set.reset': 'Sıfırla', 'set.reset': 'Sıfırla',
'set.resetText': '{accounts} hesabı (anahtarları anahtar zincirinden silinir), {studios} stüdyoyu, {folders} uygulama klasörünü (klasörler diskte kalır), eşleştirmeyi, yok sayılanları, ayarları ve kayıtlı okumaları unutur. Önce bir sistem penceresi sorar.', 'set.resetText': '{accounts} hesabı (anahtarları anahtar zincirinden silinir), {studios} stüdyoyu, {folders} uygulama klasörünü (klasörler diskte kalır), eşleştirmeyi, yok sayılanları, ayarları ve kayıtlı okumaları unutur. Önce bir sistem penceresi sorar.',
'set.resetButton': 'Uygulamayı sıfırla', 'set.resetButton': 'Uygulamayı sıfırla',

View file

@ -2,7 +2,7 @@
// (on launch, every N minutes, how many apps at once, icons), the offline cache, language and theme, notifications, // (on launch, every N minutes, how many apps at once, icons), the offline cache, language and theme, notifications,
// local tools, the CLI sidecar, privacy, keyboard shortcuts, updates and reset. A section list on the left jumps. // local tools, the CLI sidecar, privacy, keyboard shortcuts, updates and reset. A section list on the left jumps.
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { api, type CacheInfo, errorText, type Settings as S } from '../api'; import { api, type CacheInfo, errorText, onUpdateProgress, type Settings as S, type UpdateInfo } from '../api';
import { type Key, t } from '../i18n'; import { type Key, t } from '../i18n';
import { ago, bytes, date, num } from '../lib/format'; import { ago, bytes, date, num } from '../lib/format';
import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/identity'; import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/identity';
@ -221,6 +221,7 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
<div className="form"> <div className="form">
<div className="field"><span className="legend">{t('set.channel')}</span> <div className="field"><span className="legend">{t('set.channel')}</span>
<Seg value={s.channel} label={t('set.channel')} onChange={channel => set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} /></div> <Seg value={s.channel} label={t('set.channel')} onChange={channel => set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} /></div>
<Updates />
<p className="small muted">{t('set.updatesText')}</p> <p className="small muted">{t('set.updatesText')}</p>
</div> </div>
</Card> </Card>
@ -240,3 +241,33 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
</div> </div>
); );
} }
/** Settings > Updates: checks on click only; installs after the host's native dialog (the signature is checked there). */
function Updates() {
const [info, setInfo] = useState<UpdateInfo | null>(null);
const [busy, setBusy] = useState<'check' | 'install' | null>(null);
const [error, setError] = useState<string | null>(null);
const [got, setGot] = useState<{ received: number; total: number | null } | null>(null);
useEffect(() => { const un = onUpdateProgress(setGot); return () => { un.then(f => f()); }; }, []);
const check = async () => {
setBusy('check'); setError(null);
try { setInfo(await api.updateCheck()); } catch (e) { setError(errorText(e)); } finally { setBusy(null); }
};
const install = async (version: string) => {
setBusy('install'); setError(null);
try { await api.updateInstall(version); } catch (e) { setError(errorText(e)); } finally { setBusy(null); setGot(null); }
};
const channel = info ? t(info.channel === 'beta' ? 'set.beta' : 'set.stable') : '';
return (
<div className="stack" style={{ gap: 8 }}>
{error && <Notice tone="bad">{error}</Notice>}
{info && !info.available && <p className="small">{t('set.updateNone', { version: info.current, channel })}</p>}
{info?.available && <p className="small"><b>{t('set.updateAvailable', { version: info.available })}</b>{info.notes ? ` ${info.notes}` : ''}</p>}
{busy === 'install' && got && <p className="small muted" role="status">{t('set.updateInstalling', { done: got.total ? `${Math.round((got.received / got.total) * 100)}%` : bytes(got.received) })}</p>}
<div className="actions">
<button className="btn btn-sm" disabled={!!busy} onClick={check}><Icon name="refresh" />{busy === 'check' ? t('set.updateChecking') : t('set.updateCheck')}</button>
{info?.available && <button className="btn btn-sm btn-primary" disabled={!!busy} onClick={() => install(info.available!)}><Icon name="download" />{t('set.updateInstall', { version: info.available })}</button>}
</div>
</div>
);
}