diff --git a/apps/desktop/scripts/screens.ts b/apps/desktop/scripts/screens.ts index 157489b..078d188 100644 --- a/apps/desktop/scripts/screens.ts +++ b/apps/desktop/scripts/screens.ts @@ -15,11 +15,14 @@ const only = arg('only', '').split(',').filter(Boolean); const themes = arg('themes', 'light,dark').split(','); const lang = arg('lang', 'en'); const suffix = arg('suffix', ''); +const prefix = arg('prefix', 'd3'); export const SCREENS: [string, string][] = [ ['portfolio', 'portfolio'], ['releases', 'app:releases'], ['releases-2', 'app:releases:2'], ['catalog', 'app:catalog'], ['listings', 'app:listings'], ['health', 'app:health'], ['reviews', 'app:reviews'], ['testflight', 'app:testflight'], ['checks', 'app:checks'], ['apps', 'apps'], ['accounts', 'accounts'], ['dependencies', 'dependencies'], ['settings', 'settings'], + ['ignored', 'ignored'], ['store-app', 'app:releases:3'], ['store-app-reviews', 'app:reviews:3'], ['store-app-single', 'app:releases:7'], + ['settings-pairing', 'settings:pairing'], ['settings-refresh', 'settings:refresh'], ['settings-privacy', 'settings:privacy'], ['palette', 'palette'], ['welcome-1', 'welcome:1'], ['welcome-2', 'welcome:2'], ['welcome-3', 'welcome:3'], ['welcome-4', 'welcome:4'], ['welcome-5', 'welcome:5'], ]; @@ -41,7 +44,7 @@ for (const theme of themes) { if (only.length && !only.includes(name)) continue; await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=${theme}&lang=${lang}`); await settle(page); - const f = join(out, `d2-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); + const f = join(out, `${prefix}-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); await page.screenshot({ path: f }); files.push(f); } @@ -51,10 +54,45 @@ for (const theme of themes) { await settle(page); await page.getByRole('button', { name: /Read the stores|Mağazaları oku/ }).first().click(); await page.waitForTimeout(900); - const f = join(out, `d2-toast${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); + const f = join(out, `${prefix}-toast${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); await page.screenshot({ path: f }); files.push(f); } + const shot = async (name: string) => { + const f = join(out, `${prefix}-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); + await page.screenshot({ path: f }); + files.push(f); + }; + if (!only.length || only.includes('accounts-tested')) { + // every account checked: one Play service account was never invited (permission missing, with the fix) + await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`); + await settle(page); + await page.getByRole('button', { name: /Test all accounts|Tüm hesapları sına/ }).click(); + await page.waitForTimeout(900); + await page.getByText(/Sample Labs · Play/).first().scrollIntoViewIfNeeded(); + await page.evaluate(() => document.getElementById('content')?.scrollBy({ top: 260 })); + await page.waitForTimeout(200); + await shot('accounts-tested'); + } + if (!only.length || only.includes('portfolio-filter')) { + // one studio, sorted by name, no grouping, with a search + await page.goto(`${base}/?start=portfolio&theme=${theme}&lang=${lang}`); + await settle(page); + await page.locator('.fchip', { hasText: 'Example Games' }).click(); + await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill('o'); + await page.waitForTimeout(300); + await shot('portfolio-filter'); + await page.locator('.fchip').first().click(); + await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill(''); + } + if (!only.length || only.includes('import')) { + // Import apps running, with its progress toast + await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`); + await settle(page); + await page.getByRole('button', { name: /^Import apps$|^Uygulamaları içe aktar$/ }).first().click(); + await page.waitForTimeout(700); + await shot('import'); + } if (errors.length) console.error(`${theme}: page errors:\n ${[...new Set(errors)].join('\n ')}`); await ctx.close(); } diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json index 2ef3bf4..8936134 100644 --- a/apps/desktop/src-tauri/capabilities/main.json +++ b/apps/desktop/src-tauri/capabilities/main.json @@ -29,6 +29,20 @@ "allow-open-external", "allow-tools-info", "allow-tools-install", - "allow-tools-uninstall" + "allow-tools-uninstall", + "allow-workspace-get", + "allow-studio-save", + "allow-studio-remove", + "allow-studio-logo", + "allow-account-update", + "allow-account-check", + "allow-store-apps-refresh", + "allow-store-apps-cached", + "allow-overrides-set", + "allow-settings-set", + "allow-cache-info", + "allow-data-reveal", + "allow-notify", + "allow-app-reset" ] } diff --git a/apps/desktop/src-tauri/permissions/autogenerated/account_check.toml b/apps/desktop/src-tauri/permissions/autogenerated/account_check.toml new file mode 100644 index 0000000..48b40a3 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/account_check.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-account-check" +description = "Enables the account_check command without any pre-configured scope." +commands.allow = ["account_check"] + +[[permission]] +identifier = "deny-account-check" +description = "Denies the account_check command without any pre-configured scope." +commands.deny = ["account_check"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/account_update.toml b/apps/desktop/src-tauri/permissions/autogenerated/account_update.toml new file mode 100644 index 0000000..3fc065c --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/account_update.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-account-update" +description = "Enables the account_update command without any pre-configured scope." +commands.allow = ["account_update"] + +[[permission]] +identifier = "deny-account-update" +description = "Denies the account_update command without any pre-configured scope." +commands.deny = ["account_update"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/app_reset.toml b/apps/desktop/src-tauri/permissions/autogenerated/app_reset.toml new file mode 100644 index 0000000..c6aec16 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/app_reset.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-app-reset" +description = "Enables the app_reset command without any pre-configured scope." +commands.allow = ["app_reset"] + +[[permission]] +identifier = "deny-app-reset" +description = "Denies the app_reset command without any pre-configured scope." +commands.deny = ["app_reset"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/cache_info.toml b/apps/desktop/src-tauri/permissions/autogenerated/cache_info.toml new file mode 100644 index 0000000..bc6d6f8 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/cache_info.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-cache-info" +description = "Enables the cache_info command without any pre-configured scope." +commands.allow = ["cache_info"] + +[[permission]] +identifier = "deny-cache-info" +description = "Denies the cache_info command without any pre-configured scope." +commands.deny = ["cache_info"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/data_reveal.toml b/apps/desktop/src-tauri/permissions/autogenerated/data_reveal.toml new file mode 100644 index 0000000..f66ed76 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/data_reveal.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-data-reveal" +description = "Enables the data_reveal command without any pre-configured scope." +commands.allow = ["data_reveal"] + +[[permission]] +identifier = "deny-data-reveal" +description = "Denies the data_reveal command without any pre-configured scope." +commands.deny = ["data_reveal"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/notify.toml b/apps/desktop/src-tauri/permissions/autogenerated/notify.toml new file mode 100644 index 0000000..4ed8344 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/notify.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-notify" +description = "Enables the notify command without any pre-configured scope." +commands.allow = ["notify"] + +[[permission]] +identifier = "deny-notify" +description = "Denies the notify command without any pre-configured scope." +commands.deny = ["notify"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/overrides_set.toml b/apps/desktop/src-tauri/permissions/autogenerated/overrides_set.toml new file mode 100644 index 0000000..388264b --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/overrides_set.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-overrides-set" +description = "Enables the overrides_set command without any pre-configured scope." +commands.allow = ["overrides_set"] + +[[permission]] +identifier = "deny-overrides-set" +description = "Denies the overrides_set command without any pre-configured scope." +commands.deny = ["overrides_set"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/settings_set.toml b/apps/desktop/src-tauri/permissions/autogenerated/settings_set.toml new file mode 100644 index 0000000..1477839 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/settings_set.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-settings-set" +description = "Enables the settings_set command without any pre-configured scope." +commands.allow = ["settings_set"] + +[[permission]] +identifier = "deny-settings-set" +description = "Denies the settings_set command without any pre-configured scope." +commands.deny = ["settings_set"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/store_apps_cached.toml b/apps/desktop/src-tauri/permissions/autogenerated/store_apps_cached.toml new file mode 100644 index 0000000..8809839 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/store_apps_cached.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-store-apps-cached" +description = "Enables the store_apps_cached command without any pre-configured scope." +commands.allow = ["store_apps_cached"] + +[[permission]] +identifier = "deny-store-apps-cached" +description = "Denies the store_apps_cached command without any pre-configured scope." +commands.deny = ["store_apps_cached"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/store_apps_refresh.toml b/apps/desktop/src-tauri/permissions/autogenerated/store_apps_refresh.toml new file mode 100644 index 0000000..24d5753 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/store_apps_refresh.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-store-apps-refresh" +description = "Enables the store_apps_refresh command without any pre-configured scope." +commands.allow = ["store_apps_refresh"] + +[[permission]] +identifier = "deny-store-apps-refresh" +description = "Denies the store_apps_refresh command without any pre-configured scope." +commands.deny = ["store_apps_refresh"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/studio_logo.toml b/apps/desktop/src-tauri/permissions/autogenerated/studio_logo.toml new file mode 100644 index 0000000..88f2750 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/studio_logo.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-studio-logo" +description = "Enables the studio_logo command without any pre-configured scope." +commands.allow = ["studio_logo"] + +[[permission]] +identifier = "deny-studio-logo" +description = "Denies the studio_logo command without any pre-configured scope." +commands.deny = ["studio_logo"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/studio_remove.toml b/apps/desktop/src-tauri/permissions/autogenerated/studio_remove.toml new file mode 100644 index 0000000..c1e34cb --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/studio_remove.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-studio-remove" +description = "Enables the studio_remove command without any pre-configured scope." +commands.allow = ["studio_remove"] + +[[permission]] +identifier = "deny-studio-remove" +description = "Denies the studio_remove command without any pre-configured scope." +commands.deny = ["studio_remove"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/studio_save.toml b/apps/desktop/src-tauri/permissions/autogenerated/studio_save.toml new file mode 100644 index 0000000..766c0ea --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/studio_save.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-studio-save" +description = "Enables the studio_save command without any pre-configured scope." +commands.allow = ["studio_save"] + +[[permission]] +identifier = "deny-studio-save" +description = "Denies the studio_save command without any pre-configured scope." +commands.deny = ["studio_save"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/workspace_get.toml b/apps/desktop/src-tauri/permissions/autogenerated/workspace_get.toml new file mode 100644 index 0000000..e33840f --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/workspace_get.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-workspace-get" +description = "Enables the workspace_get command without any pre-configured scope." +commands.allow = ["workspace_get"] + +[[permission]] +identifier = "deny-workspace-get" +description = "Denies the workspace_get command without any pre-configured scope." +commands.deny = ["workspace_get"] diff --git a/apps/desktop/src-tauri/src/accounts.rs b/apps/desktop/src-tauri/src/accounts.rs index 06f6b10..7d1f12d 100644 --- a/apps/desktop/src-tauri/src/accounts.rs +++ b/apps/desktop/src-tauri/src/accounts.rs @@ -22,6 +22,9 @@ pub struct Account { pub label: String, pub kind: AccountKind, pub created: String, + /// The studio this account belongs to (workspace::Studio id), if any. + #[serde(default)] + pub studio: Option, } /// The keychain entry of one account (JSON). diff --git a/apps/desktop/src-tauri/src/cache.rs b/apps/desktop/src-tauri/src/cache.rs index 3bafb86..f27c741 100644 --- a/apps/desktop/src-tauri/src/cache.rs +++ b/apps/desktop/src-tauri/src/cache.rs @@ -94,6 +94,19 @@ impl Cache { Ok(()) } + /// Rows, bytes of the saved values and the oldest read time. + pub fn info(&self) -> Result<(u64, u64, Option), String> { + let db = self.db.lock().map_err(|_| "cache poisoned")?; + db.query_row("SELECT COUNT(*), COALESCE(SUM(LENGTH(value)), 0), MIN(at) FROM reads", [], |r| Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64, r.get(2)?))) + .map_err(|e| e.to_string()) + } + + /// Drops reads older than `cutoff` (RFC 3339, compared as text: every `at` is written in the same UTC format). + pub fn prune_before(&self, cutoff: &str) -> Result { + let db = self.db.lock().map_err(|_| "cache poisoned")?; + db.execute("DELETE FROM reads WHERE at < ?1", params![cutoff]).map_err(|e| e.to_string()) + } + pub fn clear(&self) -> Result<(), String> { let db = self.db.lock().map_err(|_| "cache poisoned")?; db.execute("DELETE FROM reads", []).map_err(|e| e.to_string())?; diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index aaca49b..f685852 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -17,6 +17,7 @@ use crate::downloads; use crate::policy::{self, Kind}; use crate::sidecar::{valid_job, Fail, Progress, Sidecar}; use crate::store::{self, Project, State as Saved}; +use crate::workspace::{self, Overrides, Settings, StoreTarget, Studio}; pub struct AppState { pub sidecar: Sidecar, @@ -62,6 +63,40 @@ fn project_params(s: &AppState, project_id: &str) -> Res<(Project, Map Res> { + let st = saved(s)?; + let kind = |id: &str| st.accounts.iter().find(|a| a.id == id).map(|a| a.kind); + if let Some((acc, ..)) = &t.ios { + if kind(acc) != Some(AccountKind::Apple) { + return Err(Fail::host("store app: not an App Store Connect account")); + } + } + if let Some((acc, _)) = &t.android { + if kind(acc) != Some(AccountKind::Play) { + return Err(Fail::host("store app: not a Google Play account")); + } + } + drop(st); + let mut creds = Map::new(); + for id in t.accounts() { + if let Ok(secret) = s.secrets.get(id) { + secret.to_credentials(&mut creds); + } + } + Ok(creds) +} + +/// One account's credentials only (account reads). +fn account_creds(s: &AppState, id: &str) -> Res> { + if !saved(s)?.accounts.iter().any(|a| a.id == id) { + return Err(Fail::host("unknown account")); + } + let mut creds = Map::new(); + s.secrets.get(id).map_err(Fail::host)?.to_credentials(&mut creds); + Ok(creds) +} + #[derive(Serialize)] pub struct AppInfo { version: &'static str, @@ -105,6 +140,24 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_ let mut cache_project = None; if matches!(kind, Some(Kind::Read | Kind::Write)) { let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?; + if id.starts_with("store:") { + // a store-only app: store reads only, through the sidecar's generated config + if kind != Some(Kind::Read) { + return Err(Fail::host("store-only apps are read-only: link a folder to change anything")); + } + let target = StoreTarget::parse(&id).map_err(Fail::host)?; + let creds = target_params(&state, &target)?; + let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?; + o.insert("virtual".into(), target.virtual_project()); + if !creds.is_empty() { + o.insert("credentials".into(), Value::Object(creds)); + } + let res = r.call_job(&method, p, job.as_deref()).await?; + if res["ok"] == Value::Bool(true) && !res["data"].is_null() { + let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso()); + } + return Ok(res); + } let (proj, creds) = project_params(&state, &id)?; let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?; o.insert("project".into(), Value::String(proj.path)); @@ -347,6 +400,10 @@ pub fn project_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str guard(&window)?; let mut st = saved(&state)?; st.projects.retain(|p| p.id != id); + st.overrides.links.retain(|l| l.project != id); + let (ig, key) = (format!("project:{id}"), format!("project:{id}")); + st.overrides.ignored.retain(|i| i != &ig); + st.overrides.app_studio.retain(|a| a.key != key); let _ = state.cache.forget_project(&id); persist(&state, &st) } @@ -380,9 +437,19 @@ pub fn accounts_list(window: WebviewWindow, state: State<'_, AppState>) -> Res Res { +fn check_studio(state: &AppState, studio: &Option) -> Res<()> { + if let Some(s) = studio { + if !saved(state)?.studios.iter().any(|x| &x.id == s) { + return Err(Fail::host("unknown studio")); + } + } + Ok(()) +} + +fn add_account(state: &AppState, label: &str, secret: Secret, studio: Option) -> Res { let label = accounts::check_label(label).map_err(Fail::host)?; - let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso() }; + check_studio(state, &studio)?; + let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso(), studio }; state.secrets.set(&acc.id, &secret).map_err(Fail::host)?; let mut st = saved(state)?; st.accounts.push(acc.clone()); @@ -409,24 +476,26 @@ async fn pick_file(window: &WebviewWindow, title: &'static str, filter: (&'stati /// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only. #[tauri::command] -pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String) -> Res> { +pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String, studio: Option) -> Res> { guard(&window)?; accounts::check_label(&label).map_err(Fail::host)?; + check_studio(&state, &studio)?; let Some(text) = pick_file(&window, "Google Play service account key (JSON)", ("JSON key", &["json"])).await? else { return Ok(None) }; let sa = accounts::check_service_account(&text).map_err(Fail::host)?; - add_account(&state, &label, Secret::Play { service_account: sa }).map(Some) + add_account(&state, &label, Secret::Play { service_account: sa }, studio).map(Some) } /// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain. #[tauri::command] -pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String) -> Res> { +pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String, studio: Option) -> Res> { guard(&window)?; accounts::check_label(&label).map_err(Fail::host)?; + check_studio(&state, &studio)?; let key_id = accounts::check_key_id(&key_id).map_err(Fail::host)?; let issuer_id = accounts::check_issuer_id(&issuer_id).map_err(Fail::host)?; let Some(text) = pick_file(&window, "App Store Connect API key (.p8)", ("API key", &["p8"])).await? else { return Ok(None) }; let p8 = accounts::check_p8(&text).map_err(Fail::host)?; - add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }).map(Some) + add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }, studio).map(Some) } #[tauri::command] @@ -435,6 +504,9 @@ pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str state.secrets.delete(&id).map_err(Fail::host)?; let mut st = saved(&state)?; st.accounts.retain(|a| a.id != id); + let ignored = format!("account:{id}"); + st.overrides.ignored.retain(|i| i != &ignored); + let _ = state.cache.forget_project(&format!("acct:{id}")); for p in st.projects.iter_mut() { if p.play_account.as_deref() == Some(id.as_str()) { p.play_account = None; @@ -446,18 +518,31 @@ pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str persist(&state, &st) } -/// Store reads run at most this many apps at once (each is two status reads). -const LIVE_PARALLEL: usize = 4; +/// Store-only apps one live portfolio read takes at most. +const MAX_STORE_TARGETS: usize = 300; /// `portfolio.status` over every project. Offline unless `live`; live reads every app with its own accounts, several /// at once, and sends one progress line per finished app (job progress n / total). Each live app result is cached; /// the whole live result too (project "*"), so the portfolio shows the last read when offline. #[tauri::command] -pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option, job: Option) -> Res { +pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option, stores: Option>, job: Option) -> Res { guard(&window)?; let job = job_of(job)?; - let projects = saved(&state)?.projects.clone(); - if projects.is_empty() { + let (projects, parallel) = { + let st = saved(&state)?; + let ignored: Vec<&str> = st.overrides.ignored.iter().filter_map(|i| i.strip_prefix("project:")).collect(); + (st.projects.iter().filter(|p| !ignored.contains(&p.id.as_str())).cloned().collect::>(), st.settings.refresh.parallel.clamp(1, 8) as usize) + }; + // store-only apps (live reads only): validated targets with their accounts' credentials + let mut targets = Vec::new(); + if live == Some(true) { + for key in stores.unwrap_or_default().into_iter().take(MAX_STORE_TARGETS) { + let t = StoreTarget::parse(&key).map_err(Fail::host)?; + let creds = target_params(&state, &t)?; + targets.push((key, t, creds)); + } + } + if projects.is_empty() && targets.is_empty() { return Ok(json!({ "apps": [], "at": store::now_iso() })); } let r = state.sidecar.get(&app).await?; @@ -465,8 +550,8 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat let paths: Vec<&str> = projects.iter().map(|p| p.path.as_str()).collect(); return r.call_job("portfolio.status", json!({ "projects": paths }), job.as_deref()).await; } - let total = projects.len(); - let sem = Arc::new(tokio::sync::Semaphore::new(LIVE_PARALLEL)); + let total = projects.len() + targets.len(); + let sem = Arc::new(tokio::sync::Semaphore::new(parallel)); let done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let mut handles = Vec::new(); for p in &projects { @@ -481,6 +566,18 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat (id, res) })); } + for (key, t, creds) in targets { + let (r, sem, done, app, job, id) = (r.clone(), sem.clone(), done.clone(), app.clone(), job.clone(), key.clone()); + let entry = json!({ "key": key, "virtual": t.virtual_project() }); + handles.push(tauri::async_runtime::spawn(async move { + let _permit = sem.acquire_owned().await.ok(); + let sub = job.as_ref().map(|j| format!("{j}:p")); + let res = r.call_job("portfolio.status", json!({ "projects": [entry], "live": true, "credentials": creds }), sub.as_deref()).await; + let n = done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + let _ = app.emit_to(policy::MAIN, "sidecar-progress", Progress { params: json!({ "requestId": 0, "n": n, "total": total, "project": id }), job: job.clone() }); + (id, res) + })); + } let mut all = Vec::new(); let at = store::now_iso(); for h in handles { @@ -541,3 +638,250 @@ pub async fn tools_uninstall(window: WebviewWindow, state: State<'_, AppState>, state.sidecar.shutdown().await; Ok(()) } + +// ---- D3: studios, store accounts' apps, pairing overrides, ignore list, settings ---- + +#[derive(Serialize)] +pub struct Workspace { + studios: Vec, + overrides: Overrides, + settings: Settings, +} + +/// Studios, the owner's pairing / link / ignore overrides and the app settings in one read. +#[tauri::command] +pub fn workspace_get(window: WebviewWindow, state: State<'_, AppState>) -> Res { + guard(&window)?; + let st = saved(&state)?; + Ok(Workspace { studios: st.studios.clone(), overrides: st.overrides.clone(), settings: st.settings.clone() }) +} + +/// Creates (no id) or renames / recolours a studio. +#[tauri::command] +pub fn studio_save(window: WebviewWindow, state: State<'_, AppState>, id: Option, name: String, color: String) -> Res { + guard(&window)?; + let name = workspace::check_studio_name(&name).map_err(Fail::host)?; + let color = workspace::check_color(&color).map_err(Fail::host)?; + let mut st = saved(&state)?; + let out = match id { + Some(id) => { + let s = st.studios.iter_mut().find(|s| s.id == id).ok_or_else(|| Fail::host("unknown studio"))?; + s.name = name; + s.color = color; + s.clone() + } + None => { + if st.studios.len() >= 100 { + return Err(Fail::host("at most 100 studios")); + } + let s = Studio { id: store::new_id()?, name, color, logo: None, created: store::now_iso() }; + st.studios.push(s.clone()); + s + } + }; + persist(&state, &st)?; + Ok(out) +} + +/// Removes a studio; its accounts and apps stay, without a studio. +#[tauri::command] +pub fn studio_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> { + guard(&window)?; + let mut st = saved(&state)?; + st.studios.retain(|s| s.id != id); + for a in st.accounts.iter_mut() { + if a.studio.as_deref() == Some(id.as_str()) { + a.studio = None; + } + } + st.overrides.app_studio.retain(|a| a.studio != id); + persist(&state, &st) +} + +/// Studio logo: a small PNG / JPEG / WebP picked in a native dialog (kept as a data URL), or `clear`. +#[tauri::command] +pub async fn studio_logo(window: WebviewWindow, state: State<'_, AppState>, id: String, clear: bool) -> Res> { + guard(&window)?; + if !saved(&state)?.studios.iter().any(|s| s.id == id) { + return Err(Fail::host("unknown studio")); + } + let logo = if clear { + None + } else { + let w = window.clone(); + let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title("Studio logo (PNG, JPEG or WebP)").add_filter("Image", &["png", "jpg", "jpeg", "webp"]).set_parent(&w).blocking_pick_file()) + .await + .map_err(|e| Fail::host(e.to_string()))?; + let Some(p) = picked else { return Ok(None) }; + let path = p.into_path().map_err(|e| Fail::host(e.to_string()))?; + if std::fs::metadata(&path).map_err(|e| Fail::host(e.to_string()))?.len() > workspace::LOGO_MAX as u64 { + return Err(Fail::host("logo: at most 256 KB")); + } + Some(workspace::logo_data_url(&std::fs::read(&path).map_err(|e| Fail::host(e.to_string()))?).map_err(Fail::host)?) + }; + let mut st = saved(&state)?; + let s = st.studios.iter_mut().find(|s| s.id == id).ok_or_else(|| Fail::host("unknown studio"))?; + s.logo = logo; + let out = s.clone(); + persist(&state, &st)?; + Ok(Some(out)) +} + +/// Renames an account or moves it to another studio (the key in the keychain stays as it is). +#[tauri::command] +pub fn account_update(window: WebviewWindow, state: State<'_, AppState>, id: String, label: String, studio: Option) -> Res { + guard(&window)?; + let label = accounts::check_label(&label).map_err(Fail::host)?; + check_studio(&state, &studio)?; + let mut st = saved(&state)?; + let a = st.accounts.iter_mut().find(|a| a.id == id).ok_or_else(|| Fail::host("unknown account"))?; + a.label = label; + a.studio = studio; + let out = a.clone(); + persist(&state, &st)?; + Ok(out) +} + +/// Does the account's key work, and can it see apps (sidecar `account.check`). Not cached: it is a live answer. +#[tauri::command] +pub async fn account_check(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option) -> Res { + guard(&window)?; + let job = job_of(job)?; + let creds = account_creds(&state, &id)?; + let r = state.sidecar.get(&app).await?; + r.call_job("account.check", json!({ "credentials": creds }), job.as_deref()).await +} + +/// Reads every app the account can see from its store (sidecar `apps.list`, icons per Settings) and keeps the list +/// (cache project "acct:"). +#[tauri::command] +pub async fn store_apps_refresh(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option) -> Res { + guard(&window)?; + let job = job_of(job)?; + let creds = account_creds(&state, &id)?; + let icons = saved(&state)?.settings.refresh.icons; + let r = state.sidecar.get(&app).await?; + let value = r.call_job("apps.list", json!({ "credentials": creds, "args": { "icons": icons } }), job.as_deref()).await?; + let at = store::now_iso(); + state.cache.put(&format!("acct:{id}"), "apps.list", &json!({}), &value, &at).map_err(Fail::host)?; + Ok(Entry { value, at }) +} + +#[derive(Serialize)] +pub struct AccountApps { + account: String, + entry: Option, +} + +/// The last app list read of every account (null for an account never read). +#[tauri::command] +pub fn store_apps_cached(window: WebviewWindow, state: State<'_, AppState>) -> Res> { + guard(&window)?; + let ids: Vec = saved(&state)?.accounts.iter().map(|a| a.id.clone()).collect(); + ids.into_iter() + .map(|account| { + let entry = state.cache.get(&format!("acct:{account}"), "apps.list", &json!({})).map_err(Fail::host)?; + Ok(AccountApps { account, entry }) + }) + .collect() +} + +/// Replaces the pairing / link / studio / ignore overrides (every key is checked). +#[tauri::command] +pub fn overrides_set(window: WebviewWindow, state: State<'_, AppState>, overrides: Overrides) -> Res { + guard(&window)?; + workspace::check_overrides(&overrides).map_err(Fail::host)?; + let mut st = saved(&state)?; + st.overrides = overrides.clone(); + persist(&state, &st)?; + Ok(overrides) +} + +/// Saves the app settings; a shorter "keep saved reads" drops older reads right away. +#[tauri::command] +pub fn settings_set(window: WebviewWindow, state: State<'_, AppState>, settings: Settings) -> Res { + guard(&window)?; + workspace::check_settings(&settings).map_err(Fail::host)?; + let mut st = saved(&state)?; + st.settings = settings.clone(); + persist(&state, &st)?; + drop(st); + prune_cache(&state, settings.cache.keep_days); + Ok(settings) +} + +pub fn prune_cache(state: &AppState, keep_days: u32) { + if keep_days == 0 { + return; + } + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let cutoff = store::iso_from_unix(now.saturating_sub(u64::from(keep_days) * 86_400)); + let _ = state.cache.prune_before(&cutoff); +} + +#[derive(Serialize)] +pub struct CacheInfo { + rows: u64, + bytes: u64, + oldest: Option, + /// cache.sqlite (+ its WAL) on disk. + file_bytes: u64, +} + +#[tauri::command] +pub fn cache_info(window: WebviewWindow, state: State<'_, AppState>) -> Res { + guard(&window)?; + let (rows, bytes, oldest) = state.cache.info().map_err(Fail::host)?; + let file_bytes = ["", "-wal", "-shm"].iter().filter_map(|s| std::fs::metadata(state.data_dir.join(format!("{}{s}", crate::cache::FILE))).ok()).map(|m| m.len()).sum(); + Ok(CacheInfo { rows, bytes, oldest, file_bytes }) +} + +/// Shows the app data folder (state, saved reads, downloaded tools; never keys) in the file manager. +#[tauri::command] +pub fn data_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<()> { + guard(&window)?; + let _ = std::fs::create_dir_all(&state.data_dir); + app.opener().reveal_item_in_dir(state.data_dir.join(store::FILE)).or_else(|_| app.opener().open_path(state.data_dir.to_string_lossy(), None::<&str>)).map_err(|e| Fail::host(e.to_string())) +} + +/// A desktop notification (review state changed, a new 1-2 star review, a crash rate over the threshold). The window +/// decides when, from Settings > Notifications; text is plain and short. +#[tauri::command] +pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String) -> Res<()> { + guard(&window)?; + use tauri_plugin_notification::NotificationExt; + let cut = |s: &str, n: usize| s.chars().filter(|c| !c.is_control()).take(n).collect::(); + app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string())) +} + +/// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders +/// themselves stay), overrides, settings and saved reads. Downloaded tools stay. True when it was reset. +#[tauri::command] +pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res { + guard(&window)?; + let w = window.clone(); + let yes = tauri::async_runtime::spawn_blocking(move || { + w.app_handle() + .dialog() + .message("Removes every store key from the system keychain and forgets studios, accounts, app folders (the folders and their files stay), pairing, the ignore list, settings and saved store reads.\n\nDownloaded tools stay. This cannot be undone.") + .title("Reset storebound desktop?") + .kind(MessageDialogKind::Warning) + .buttons(MessageDialogButtons::OkCancelCustom("Reset".into(), "Cancel".into())) + .parent(&w) + .blocking_show() + }) + .await + .map_err(|e| Fail::host(e.to_string()))?; + if !yes { + return Ok(false); + } + let mut st = saved(&state)?; + for a in &st.accounts { + state.secrets.delete(&a.id).map_err(Fail::host)?; + } + *st = Saved::default(); + persist(&state, &st)?; + drop(st); + state.cache.clear().map_err(Fail::host)?; + Ok(true) +} diff --git a/apps/desktop/src-tauri/src/commands_list.rs b/apps/desktop/src-tauri/src/commands_list.rs index ce2e1fc..f6978ae 100644 --- a/apps/desktop/src-tauri/src/commands_list.rs +++ b/apps/desktop/src-tauri/src/commands_list.rs @@ -22,4 +22,18 @@ pub const COMMANDS: &[&str] = &[ "tools_info", "tools_install", "tools_uninstall", + "workspace_get", + "studio_save", + "studio_remove", + "studio_logo", + "account_update", + "account_check", + "store_apps_refresh", + "store_apps_cached", + "overrides_set", + "settings_set", + "cache_info", + "data_reveal", + "notify", + "app_reset", ]; diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 23d79ce..2c49697 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -8,6 +8,7 @@ pub mod downloads; pub mod policy; pub mod sidecar; pub mod store; +pub mod workspace; include!("commands_list.rs"); @@ -136,14 +137,19 @@ pub fn run() { let data_dir = app.path().app_data_dir()?; dev_seed(&data_dir); let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?; - app.manage(commands::AppState { + let saved = store::load(&data_dir); + let keep_days = saved.settings.cache.keep_days; + let state = commands::AppState { sidecar: sidecar::Sidecar::default(), - saved: Mutex::new(store::load(&data_dir)), + saved: Mutex::new(saved), data_dir, secrets: Box::new(accounts::Keychain), cache, downloads: downloads::Jobs::default(), - }); + }; + // Settings > Offline cache: drop saved reads older than the chosen number of days + commands::prune_cache(&state, keep_days); + app.manage(state); #[cfg(target_os = "macos")] app.set_menu(menu(app.handle())?)?; #[cfg(not(target_os = "macos"))] @@ -194,6 +200,20 @@ pub fn run() { commands::tools_info, commands::tools_install, commands::tools_uninstall, + commands::workspace_get, + commands::studio_save, + commands::studio_remove, + commands::studio_logo, + commands::account_update, + commands::account_check, + commands::store_apps_refresh, + commands::store_apps_cached, + commands::overrides_set, + commands::settings_set, + commands::cache_info, + commands::data_reveal, + commands::notify, + commands::app_reset, ]) .build(tauri::generate_context!()) .expect("storebound desktop failed to start"); diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index 7ed2c71..d1a0e37 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -51,6 +51,8 @@ pub enum Kind { System, Portfolio, Session, + /// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key. + Account, } impl Kind { @@ -61,6 +63,7 @@ impl Kind { "system" => Kind::System, "portfolio" => Kind::Portfolio, "session" => Kind::Session, + "account" => Kind::Account, _ => return None, }) } @@ -78,6 +81,7 @@ pub fn sanitize_js_call(method: &str, kind: Option, params: &Value) -> Res match kind { Kind::Session => return Err(format!("{method} is the host's")), Kind::Portfolio => return Err(format!("{method}: use portfolio_status")), + Kind::Account => return Err(format!("{method}: use the account commands")), _ => {} } let empty = Map::new(); @@ -109,6 +113,8 @@ pub const EXTERNAL_HOSTS: &[&str] = &[ "ffmpeg.org", "googlechromelabs.github.io", "git-scm.com", + // account health fixes (enable an API in the service account's Google Cloud project) + "console.cloud.google.com", ]; /// Executable of a Chrome for Testing download, relative to its unpacked folder (app data `tools/chrome/`). @@ -131,7 +137,7 @@ pub fn external_allowed(url: &Url) -> bool { } /// Deep links the app reacts to: `storebound://` for a known screen, nothing else. -pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "dependencies", "settings"]; +pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "ignored", "dependencies", "settings"]; pub fn deep_link_screen(url: &Url) -> Option<&'static str> { if url.scheme() != "storebound" { diff --git a/apps/desktop/src-tauri/src/store.rs b/apps/desktop/src-tauri/src/store.rs index be386b0..39f7d34 100644 --- a/apps/desktop/src-tauri/src/store.rs +++ b/apps/desktop/src-tauri/src/store.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::accounts::Account; +use crate::workspace::{Overrides, Settings, Studio}; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -27,6 +28,12 @@ pub struct State { pub projects: Vec, #[serde(default)] pub accounts: Vec, + #[serde(default)] + pub studios: Vec, + #[serde(default)] + pub overrides: Overrides, + #[serde(default)] + pub settings: Settings, } pub const FILE: &str = "state.json"; diff --git a/apps/desktop/src-tauri/src/workspace.rs b/apps/desktop/src-tauri/src/workspace.rs new file mode 100644 index 0000000..0a37b20 --- /dev/null +++ b/apps/desktop/src-tauri/src/workspace.rs @@ -0,0 +1,309 @@ +//! Studios, app pairing overrides, the ignore list, app settings and store-only app targets. Pure data and checks, so +//! tests/workspace.rs can pin every rule. Nothing here is a secret: studios are names and colours, overrides are store +//! app keys (account id + store app id), settings are numbers and switches. +//! +//! Store app key: "ios::" or "android::" +//! Store target id: "store:ios:::;android::" (either part optional, at least +//! one): a store-only app (no app folder) the window reads through the sidecar's generated config. +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// Colours a studio can carry (CSS classes `studio-` in the window, contrast-checked there). +pub const STUDIO_COLORS: &[&str] = &["indigo", "violet", "rose", "amber", "emerald", "teal", "sky", "slate"]; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Studio { + pub id: String, + pub name: String, + pub color: String, + /// Small logo as a data: URL (PNG / JPEG / WebP, at most LOGO_MAX bytes before encoding), or none (monogram). + #[serde(default)] + pub logo: Option, + pub created: String, +} + +pub const LOGO_MAX: usize = 256 * 1024; + +pub fn check_studio_name(s: &str) -> Result { + let s = s.trim(); + if s.is_empty() || s.chars().count() > 48 || s.chars().any(char::is_control) { + return Err("studio name: 1 to 48 characters".into()); + } + Ok(s.to_string()) +} + +pub fn check_color(s: &str) -> Result { + if STUDIO_COLORS.contains(&s) { + Ok(s.to_string()) + } else { + Err(format!("colour: one of {}", STUDIO_COLORS.join(", "))) + } +} + +/// Logo bytes -> data URL; only small raster images whose bytes match the type. +pub fn logo_data_url(bytes: &[u8]) -> Result { + use base64::{engine::general_purpose::STANDARD, Engine}; + if bytes.len() > LOGO_MAX { + return Err("logo: at most 256 KB".into()); + } + let mime = if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { + "image/png" + } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) { + "image/jpeg" + } else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + "image/webp" + } else { + return Err("logo: a PNG, JPEG or WebP image".into()); + }; + Ok(format!("data:{mime};base64,{}", STANDARD.encode(bytes))) +} + +/// Account ids are what store::new_id makes (16 hex). +pub fn is_account_id(s: &str) -> bool { + s.len() == 16 && s.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) +} + +fn is_bundle(s: &str) -> bool { + !s.is_empty() && s.len() <= 155 && s.contains('.') && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') && s.chars().next().is_some_and(|c| c.is_ascii_alphanumeric()) +} + +fn is_package(s: &str) -> bool { + let parts: Vec<&str> = s.split('.').collect(); + s.len() <= 155 + && parts.len() >= 2 + && parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) + && parts[0].chars().next().is_some_and(|c| c.is_ascii_alphabetic()) +} + +fn is_asc_id(s: &str) -> bool { + !s.is_empty() && s.len() <= 20 && s.chars().all(|c| c.is_ascii_digit()) +} + +/// One app record on one store account. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StoreAppKey { + Ios { account: String, app_id: String }, + Android { account: String, package: String }, +} + +impl StoreAppKey { + pub fn parse(s: &str) -> Result { + let mut it = s.splitn(3, ':'); + let (store, account, id) = (it.next().unwrap_or_default(), it.next().unwrap_or_default(), it.next().unwrap_or_default()); + if !is_account_id(account) { + return Err(format!("store app key {s}: bad account id")); + } + match store { + "ios" if is_asc_id(id) => Ok(StoreAppKey::Ios { account: account.into(), app_id: id.into() }), + "android" if is_package(id) => Ok(StoreAppKey::Android { account: account.into(), package: id.into() }), + _ => Err(format!("store app key {s}: ios:: or android::")), + } + } + pub fn account(&self) -> &str { + match self { + StoreAppKey::Ios { account, .. } | StoreAppKey::Android { account, .. } => account, + } + } +} + +/// A store-only app the window reads: which accounts, which store ids. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct StoreTarget { + /// (account, App Store Connect app id, bundle id) + pub ios: Option<(String, String, String)>, + /// (account, package name) + pub android: Option<(String, String)>, +} + +impl StoreTarget { + pub fn parse(s: &str) -> Result { + let rest = s.strip_prefix("store:").ok_or("store target: store:...")?; + if rest.len() > 400 { + return Err("store target: too long".into()); + } + let mut t = StoreTarget::default(); + for part in rest.split(';') { + let f: Vec<&str> = part.split(':').collect(); + match f.as_slice() { + ["ios", acc, id, bundle] if t.ios.is_none() && is_account_id(acc) && is_asc_id(id) && is_bundle(bundle) => { + t.ios = Some((acc.to_string(), id.to_string(), bundle.to_string())); + } + ["android", acc, pkg] if t.android.is_none() && is_account_id(acc) && is_package(pkg) => { + t.android = Some((acc.to_string(), pkg.to_string())); + } + _ => return Err(format!("store target: bad part '{part}'")), + } + } + if t.ios.is_none() && t.android.is_none() { + return Err("store target: ios and / or android".into()); + } + Ok(t) + } + + /// The sidecar's `virtual` object: store ids only, named after them. + pub fn virtual_project(&self) -> Value { + let name = self.ios.as_ref().map(|i| i.2.clone()).or_else(|| self.android.as_ref().map(|a| a.1.clone())).unwrap_or_default(); + let mut v = json!({ "name": name }); + if let Some((_, id, bundle)) = &self.ios { + v["apple"] = json!({ "bundleId": bundle, "appId": id }); + } + if let Some((_, pkg)) = &self.android { + v["play"] = json!({ "packageName": pkg }); + } + v + } + + pub fn accounts(&self) -> Vec<&str> { + self.ios.iter().map(|i| i.0.as_str()).chain(self.android.iter().map(|a| a.0.as_str())).collect() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Pair { + pub ios: String, + pub android: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Link { + /// Store app key. + pub key: String, + /// Project id (app folder). + pub project: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AppStudio { + /// Store app key or "project:". + pub key: String, + pub studio: String, +} + +/// The owner's corrections to automatic pairing, links of store apps to folders, studio moves and the ignore list. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Overrides { + #[serde(default)] + pub pairs: Vec, + #[serde(default)] + pub unpairs: Vec, + #[serde(default)] + pub links: Vec, + #[serde(default)] + pub app_studio: Vec, + /// "app:", "project:" or "account:". + #[serde(default)] + pub ignored: Vec, +} + +pub const MAX_OVERRIDES: usize = 2000; + +/// Checks every key; drops nothing silently (an error names the bad entry). +pub fn check_overrides(o: &Overrides) -> Result<(), String> { + if o.pairs.len() + o.unpairs.len() + o.links.len() + o.app_studio.len() + o.ignored.len() > MAX_OVERRIDES { + return Err("too many overrides".into()); + } + for p in o.pairs.iter().chain(o.unpairs.iter()) { + match (StoreAppKey::parse(&p.ios)?, StoreAppKey::parse(&p.android)?) { + (StoreAppKey::Ios { .. }, StoreAppKey::Android { .. }) => {} + _ => return Err("pair: an iOS key and an Android key".into()), + } + } + for l in &o.links { + StoreAppKey::parse(&l.key)?; + if l.project.is_empty() || l.project.len() > 64 { + return Err("link: project id".into()); + } + } + for a in &o.app_studio { + if let Some(p) = a.key.strip_prefix("project:") { + if p.is_empty() || p.len() > 64 { + return Err("app studio: project id".into()); + } + } else { + StoreAppKey::parse(&a.key)?; + } + if a.studio.is_empty() || a.studio.len() > 64 { + return Err("app studio: studio id".into()); + } + } + for i in &o.ignored { + let ok = match i.split_once(':') { + Some(("app", k)) => StoreAppKey::parse(k).is_ok(), + Some(("account", id)) => is_account_id(id), + Some(("project", id)) => !id.is_empty() && id.len() <= 64, + _ => false, + }; + if !ok { + return Err(format!("ignored: bad entry '{i}'")); + } + } + Ok(()) +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RefreshSettings { + /// Minutes between automatic store reads; 0 = off. + pub auto_minutes: u32, + pub on_launch: bool, + /// Apps read at the same time (1-8). + pub parallel: u8, + /// Read app icons from the stores when importing (an extra request per app). + pub icons: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CacheSettings { + /// Saved reads older than this many days are dropped; 0 = keep. + pub keep_days: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NotifySettings { + pub review_state: bool, + pub low_reviews: bool, + pub crash: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Settings { + pub refresh: RefreshSettings, + pub cache: CacheSettings, + pub notify: NotifySettings, + /// Update channel (placeholder until the updater ships): stable | beta. + pub channel: String, +} + +impl Default for Settings { + fn default() -> Settings { + Settings { + refresh: RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true }, + cache: CacheSettings { keep_days: 30 }, + notify: NotifySettings { review_state: true, low_reviews: true, crash: true }, + channel: "stable".into(), + } + } +} + +pub const AUTO_MINUTES: &[u32] = &[0, 15, 30, 60, 180, 720]; +pub const KEEP_DAYS: &[u32] = &[0, 7, 30, 90, 365]; + +pub fn check_settings(s: &Settings) -> Result<(), String> { + if !AUTO_MINUTES.contains(&s.refresh.auto_minutes) { + return Err("refresh: 0 (off), 15, 30, 60, 180 or 720 minutes".into()); + } + if !(1..=8).contains(&s.refresh.parallel) { + return Err("parallel reads: 1 to 8".into()); + } + if !KEEP_DAYS.contains(&s.cache.keep_days) { + return Err("keep saved reads: 0 (always), 7, 30, 90 or 365 days".into()); + } + if !["stable", "beta"].contains(&s.channel.as_str()) { + return Err("channel: stable or beta".into()); + } + Ok(()) +} diff --git a/apps/desktop/src-tauri/tests/accounts.rs b/apps/desktop/src-tauri/tests/accounts.rs index 1e8d1e4..6305987 100644 --- a/apps/desktop/src-tauri/tests/accounts.rs +++ b/apps/desktop/src-tauri/tests/accounts.rs @@ -9,9 +9,9 @@ const FAKE_PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PR #[test] fn shown_metadata_carries_no_secret() { - let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into() }; + let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into(), studio: Some("s1".into()) }; let v = serde_json::to_value(&a).unwrap(); - assert_eq!(v.as_object().unwrap().keys().cloned().collect::>(), vec!["created", "id", "kind", "label"]); + assert_eq!(v.as_object().unwrap().keys().cloned().collect::>(), vec!["created", "id", "kind", "label", "studio"]); assert_eq!(v["kind"], "play"); } @@ -53,6 +53,7 @@ fn state_file_round_trip_is_atomic_and_tolerant() { let st = State { projects: vec![Project { id: "1".into(), path: "/games/a".into(), name: "A".into(), play_account: Some("p".into()), apple_account: None, added: "2026-10-10T00:00:00Z".into() }], accounts: vec![], + ..State::default() }; store::save(dir.path(), &st).unwrap(); assert_eq!(store::load(dir.path()), st); diff --git a/apps/desktop/src-tauri/tests/workspace.rs b/apps/desktop/src-tauri/tests/workspace.rs new file mode 100644 index 0000000..143331c --- /dev/null +++ b/apps/desktop/src-tauri/tests/workspace.rs @@ -0,0 +1,160 @@ +//! Desktop D3: studios, store app keys and store-only targets, pairing / ignore overrides, settings, old state files. +use serde_json::json; +use storebound_desktop::cache::Cache; +use storebound_desktop::policy::{sanitize_js_call, Kind}; +use storebound_desktop::store::{self, State}; +use storebound_desktop::workspace::*; + +const A1: &str = "0123456789abcdef"; +const A2: &str = "fedcba9876543210"; + +#[test] +fn studio_names_colours_and_logos() { + assert_eq!(check_studio_name(" Example Games ").unwrap(), "Example Games"); + assert!(check_studio_name("").is_err()); + assert!(check_studio_name(&"x".repeat(49)).is_err()); + assert!(check_studio_name("a\nb").is_err()); + for c in STUDIO_COLORS { + assert!(check_color(c).is_ok()); + } + assert!(check_color("#ff0000").is_err()); + assert!(check_color("red; background:url(x)").is_err()); + assert!(logo_data_url(&[0x89, b'P', b'N', b'G', 1, 2]).unwrap().starts_with("data:image/png;base64,")); + assert!(logo_data_url(&[0xff, 0xd8, 0xff, 0]).unwrap().starts_with("data:image/jpeg;base64,")); + assert!(logo_data_url(b"RIFF\0\0\0\0WEBPVP8 ").unwrap().starts_with("data:image/webp;")); + assert!(logo_data_url(b"").is_err(), "no SVG (scripts) as a logo"); + assert!(logo_data_url(&vec![0x89; LOGO_MAX + 1]).is_err()); +} + +#[test] +fn store_app_keys() { + assert_eq!(StoreAppKey::parse(&format!("ios:{A1}:6400000101")).unwrap(), StoreAppKey::Ios { account: A1.into(), app_id: "6400000101".into() }); + assert_eq!(StoreAppKey::parse(&format!("android:{A2}:com.example.puzzle")).unwrap().account(), A2); + for bad in [ + format!("ios:{A1}:com.example.puzzle"), + format!("android:{A1}:6400000101"), + "ios:nothex0123456789:1".to_string(), + format!("mac:{A1}:1"), + format!("android:{A1}:com.example.puzzle/../x"), + format!("android:{A1}:.example"), + format!("ios:{}:1", A1.to_uppercase()), + ] { + assert!(StoreAppKey::parse(&bad).is_err(), "{bad}"); + } +} + +#[test] +fn store_only_targets_become_virtual_projects_with_store_ids_only() { + let t = StoreTarget::parse(&format!("store:ios:{A1}:6400000101:com.example.puzzle;android:{A2}:com.example.puzzle")).unwrap(); + assert_eq!(t.accounts(), vec![A1, A2]); + assert_eq!( + t.virtual_project(), + json!({ "name": "com.example.puzzle", "apple": { "bundleId": "com.example.puzzle", "appId": "6400000101" }, "play": { "packageName": "com.example.puzzle" } }) + ); + let only = StoreTarget::parse(&format!("store:android:{A2}:com.example.runner")).unwrap(); + assert_eq!(only.virtual_project(), json!({ "name": "com.example.runner", "play": { "packageName": "com.example.runner" } })); + for bad in [ + "store:".to_string(), + "ios:x".to_string(), + format!("store:ios:{A1}:6400000101"), + format!("store:ios:{A1}:6400000101:com.example.a;ios:{A1}:6400000102:com.example.b"), + format!("store:android:{A2}:com.example.a;android:{A2}:com.example.b"), + format!("store:android:{A2}:com.example.a;path:/etc"), + format!("store:ios:{A1}:6400000101:../../etc"), + format!("store:android:{A2}:com.example.a;{}", "x".repeat(400)), + ] { + assert!(StoreTarget::parse(&bad).is_err(), "{bad}"); + } +} + +#[test] +fn overrides_are_checked_entry_by_entry() { + let ok = Overrides { + pairs: vec![Pair { ios: format!("ios:{A1}:6400000101"), android: format!("android:{A2}:com.example.puzzle") }], + unpairs: vec![Pair { ios: format!("ios:{A1}:6400000102"), android: format!("android:{A2}:com.example.notes") }], + links: vec![Link { key: format!("ios:{A1}:6400000103"), project: "p1".into() }], + app_studio: vec![AppStudio { key: format!("android:{A2}:com.example.runner"), studio: "s1".into() }, AppStudio { key: "project:p1".into(), studio: "s2".into() }], + ignored: vec![format!("app:ios:{A1}:6400000104"), format!("account:{A2}"), "project:p9".into()], + }; + assert!(check_overrides(&ok).is_ok()); + let mut swapped = ok.clone(); + swapped.pairs = vec![Pair { ios: format!("android:{A2}:com.example.puzzle"), android: format!("ios:{A1}:6400000101") }]; + assert!(check_overrides(&swapped).is_err()); + for bad in ["app:ios:x:1", "account:short", "project:", "everything", "app:"] { + let mut o = ok.clone(); + o.ignored.push(bad.into()); + assert!(check_overrides(&o).is_err(), "{bad}"); + } + let many = Overrides { ignored: (0..=MAX_OVERRIDES).map(|i| format!("project:p{i}")).collect(), ..Default::default() }; + assert!(check_overrides(&many).is_err()); + // camelCase on the wire + let v = serde_json::to_value(&ok).unwrap(); + assert!(v.get("appStudio").is_some()); +} + +#[test] +fn settings_have_safe_defaults_and_bounds() { + let d = Settings::default(); + assert!(check_settings(&d).is_ok()); + assert_eq!((d.refresh.auto_minutes, d.refresh.on_launch, d.refresh.parallel, d.cache.keep_days, d.channel.as_str()), (0, false, 4, 30, "stable")); + let mut s = d.clone(); + s.refresh.parallel = 0; + assert!(check_settings(&s).is_err()); + s = d.clone(); + s.refresh.parallel = 9; + assert!(check_settings(&s).is_err()); + s = d.clone(); + s.refresh.auto_minutes = 1; + assert!(check_settings(&s).is_err(), "no tight polling of the store APIs"); + s = d.clone(); + s.cache.keep_days = 3; + assert!(check_settings(&s).is_err()); + s = d; + s.channel = "nightly".into(); + assert!(check_settings(&s).is_err()); + let v = serde_json::to_value(Settings::default()).unwrap(); + assert_eq!(v["refresh"]["autoMinutes"], 0); + assert_eq!(v["cache"]["keepDays"], 30); + assert_eq!(v["notify"]["lowReviews"], true); +} + +#[test] +fn a_d2_state_file_still_loads_with_empty_d3_parts() { + let dir = tempfile::tempdir().unwrap(); + let d2 = json!({ + "projects": [{ "id": "p1", "path": "/x", "name": "X", "playAccount": null, "appleAccount": null, "added": "2026-10-01T00:00:00Z" }], + "accounts": [{ "id": A1, "label": "Play", "kind": "play", "created": "2026-10-01T00:00:00Z" }] + }); + std::fs::write(dir.path().join(store::FILE), d2.to_string()).unwrap(); + let st = store::load(dir.path()); + assert_eq!(st.projects.len(), 1); + assert_eq!(st.accounts[0].studio, None); + assert!(st.studios.is_empty()); + assert_eq!(st.overrides, Overrides::default()); + assert_eq!(st.settings, Settings::default()); + store::save(dir.path(), &st).unwrap(); + assert_eq!(store::load(dir.path()), st); + assert_eq!(State::default().settings.refresh.parallel, 4); +} + +#[test] +fn account_reads_are_the_hosts() { + // the window cannot call apps.list / account.check directly: only the account commands (one key per call) + assert!(sanitize_js_call("apps.list", Some(Kind::Account), &json!({ "credentials": {} })).is_err()); + assert!(sanitize_js_call("account.check", Some(Kind::Account), &json!({})).is_err()); + assert_eq!(Kind::parse("account"), Some(Kind::Account)); +} + +#[test] +fn cache_info_and_pruning_by_age() { + let c = Cache::in_memory().unwrap(); + c.put("p", "health", &json!({}), &json!({ "n": 1 }), "2026-01-01T00:00:00Z").unwrap(); + c.put("p", "reviews.list", &json!({}), &json!({ "n": 2 }), "2026-10-01T00:00:00Z").unwrap(); + c.put("acct:x", "apps.list", &json!({}), &json!({ "apps": [] }), "2026-10-10T00:00:00Z").unwrap(); + let (rows, bytes, oldest) = c.info().unwrap(); + assert_eq!((rows, oldest.as_deref()), (3, Some("2026-01-01T00:00:00Z"))); + assert!(bytes > 0); + assert_eq!(c.prune_before("2026-09-01T00:00:00Z").unwrap(), 1); + assert!(c.get("p", "health", &json!({})).unwrap().is_none()); + assert!(c.get("p", "reviews.list", &json!({})).unwrap().is_some()); +} diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index f424edb..ac703b9 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -1,27 +1,34 @@ -// Shell: sidebar (apps with their icons, workspace), top bar (breadcrumbs, last read, refresh), the screen, the -// command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. +// 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. import { useCallback, useEffect, useMemo, useState } from 'react'; import { FIXTURES, onDeepLink } from './api'; import { devSwitch } from './dev/switches'; import { type Key, t } from './i18n'; import { ago } from './lib/format'; -import { APP_TABS, NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, WORKSPACE, type WorkspaceScreen } from './nav'; +import { groupByStudio, type UnifiedApp } from './lib/identity'; +import { NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav'; import { usePrefs } from './prefs-ctx'; import { Accounts } from './screens/Accounts'; import { AppFolders } from './screens/AppFolders'; import { AppView } from './screens/AppView'; import { Dependencies } from './screens/Dependencies'; +import { Ignored } from './screens/Ignored'; import { Onboarding } from './screens/Onboarding'; import { Portfolio } from './screens/Portfolio'; import { Settings } from './screens/Settings'; import { useData } from './store'; import { Icon, type IconName, Mark } from './ui/icons'; -import { AppIcon, Kbd, MOD } from './ui/kit'; +import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit'; import { type Command, Palette } from './ui/Palette'; import { Toasts } from './ui/Toasts'; -const WS_ICON: Record = { apps: 'folder', accounts: 'key', dependencies: 'package', settings: 'settings' }; -const WS_KEY: Record = { apps: 'nav.apps', accounts: 'nav.accounts', dependencies: 'nav.dependencies', settings: 'nav.settings' }; +const WS_ICON: Record = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' }; +export const WS_KEY: Record = { apps: 'nav.apps', accounts: 'nav.accounts', ignored: 'nav.ignored', dependencies: 'nav.dependencies', settings: 'nav.settings' }; + +const SIDE_KEY = 'storebound.side.v1'; +function loadCollapsed(): string[] { + try { const v = JSON.parse(localStorage.getItem(SIDE_KEY) ?? '[]') as unknown; return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; } +} export function App({ onTheme }: { onTheme: () => void }) { const d = useData(); @@ -30,8 +37,15 @@ export function App({ onTheme }: { onTheme: () => void }) { const [palette, setPalette] = useState(false); const [welcome, setWelcome] = useState(false); const [started, setStarted] = useState(false); + const [collapsed, setCollapsed] = useState(loadCollapsed); const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []); + const visible = useMemo(() => d.apps.filter(a => !a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]); + const toggleGroup = (id: string) => setCollapsed(c => { + const next = c.includes(id) ? c.filter(x => x !== id) : [...c, id]; + try { localStorage.setItem(SIDE_KEY, JSON.stringify(next)); } catch { /* private mode */ } + return next; + }); // first screen: dev switch (VITE_START), else the welcome guide on a first run useEffect(() => { @@ -40,69 +54,92 @@ export function App({ onTheme }: { onTheme: () => void }) { const v = devSwitch('start'); if (v === 'welcome' || v.startsWith('welcome:')) { setWelcome(true); return; } if (v === 'palette') setPalette(true); - const r = parseStart(v, d.projects.map(p => p.id)); + const r = parseStart(v, d.apps.filter(a => !a.ignored).map(a => a.key)); if (r) { go(r); return; } - if (!d.projects.length && !prefs.onboarded) setWelcome(true); - }, [d.ready, d.projects, started, go, prefs.onboarded]); + if (!d.projects.length && !d.accounts.length && !prefs.onboarded) setWelcome(true); + }, [d.ready, d.apps, d.projects, d.accounts, started, go, prefs.onboarded]); useEffect(() => { const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); }); return () => { un.then(f => f()); }; - }, [d.projects, go]); + }, [go]); - // keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-5 workspace, Cmd/Ctrl+Shift+[ ] app tabs + const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined; + const tabs = app ? tabsFor(!!app.project) : []; + + // keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-6 workspace, Cmd/Ctrl+Shift+[ ] app tabs useEffect(() => { const onKey = (e: KeyboardEvent) => { const mod = e.metaKey || e.ctrlKey; if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette(p => !p); return; } if (palette || welcome) return; - if (mod && !e.shiftKey && !e.altKey && /^[1-5]$/.test(e.key)) { + if (mod && !e.shiftKey && !e.altKey && /^[1-6]$/.test(e.key)) { e.preventDefault(); const n = Number(e.key); go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! }); return; } - if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app') { + if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app' && tabs.length) { e.preventDefault(); - const i = APP_TABS.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1); - go({ ...route, tab: APP_TABS[(i + APP_TABS.length) % APP_TABS.length]! }); + const i = tabs.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1); + go({ ...route, tab: tabs[(i + tabs.length) % tabs.length]! }); } }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); - }, [palette, welcome, route, go]); + }, [palette, welcome, route, go, tabs]); const closeWelcome = useCallback(() => { setWelcome(false); if (!prefs.onboarded) update({ ...prefs, onboarded: true }); }, [prefs, update]); - const app = route.screen === 'app' ? d.projects.find(p => p.id === route.appId) : undefined; - useEffect(() => { if (route.screen === 'app' && d.ready && !app) go({ screen: 'portfolio' }); }, [route, app, d.ready, go]); + useEffect(() => { if (route.screen === 'app' && d.ready && d.apps.length && !app) go({ screen: 'portfolio' }); }, [route, app, d.ready, d.apps.length, go]); const commands = useMemo(() => { const c: Command[] = []; const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions') }; - for (const p of d.projects) c.push({ id: `app-${p.id}`, group: G.apps, title: d.statusOf(p)?.app?.name ?? p.name, hint: t('palette.openApp'), app: { name: p.name, icon: d.icons[p.id] }, run: () => go({ screen: 'app', appId: p.id, tab: route.screen === 'app' ? route.tab : 'releases' }) }); + const studioName = (a: UnifiedApp) => d.studios.find(s => s.id === a.studio)?.name; + for (const a of visible) c.push({ id: `app-${a.key}`, group: G.apps, title: a.name, hint: studioName(a) ?? t('palette.openApp'), keywords: `${a.ios?.app.bundleId ?? ''} ${a.android?.app.id ?? ''} ${a.project?.name ?? ''}`, app: { name: a.name, icon: d.iconFor(a) }, + run: () => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' }) }); c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) }); WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) })); - if (app) for (const tab of APP_TABS) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.id, tab }) }); - else if (d.projects[0]) for (const p of d.projects) for (const tab of APP_TABS) c.push({ id: `tab-${p.id}-${tab}`, group: G.tabs, title: `${p.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], keywords: 'tab', run: () => go({ screen: 'app', appId: p.id, tab }) }); + for (const s of d.studios) c.push({ id: `studio-${s.id}`, group: G.go, title: s.name, icon: 'building', keywords: 'studio', hint: t('palette.studio'), run: () => go({ screen: 'accounts', section: s.id }) }); + if (app) for (const tab of tabs) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.key, tab }) }); c.push({ id: 'act-live', group: G.act, title: t('action.readStores'), icon: 'refresh', keywords: 'refresh sync', run: () => { d.refreshPortfolio(true); } }); + c.push({ id: 'act-import', group: G.act, title: t('action.importApps'), icon: 'download', keywords: 'import sync accounts', run: () => { d.importApps(); } }); c.push({ id: 'act-check', group: G.act, title: t('action.checkConfigs'), icon: 'shield', run: () => { d.refreshPortfolio(false); } }); c.push({ id: 'act-add', group: G.act, title: t('action.addFolder'), icon: 'folderPlus', run: () => go({ screen: 'apps' }) }); c.push({ id: 'act-account', group: G.act, title: t('action.addAccount'), icon: 'key', run: () => go({ screen: 'accounts' }) }); c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme }); c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) }); return c; - }, [d, app, route, go, onTheme]); + }, [d, visible, app, tabs, route, go, onTheme]); const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }] - : route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.id, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }] + : route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }] : [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }]; const lastRead = d.live?.at ?? null; const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]); - const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) ? 'page' : undefined); + const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) || (r.screen !== 'app' && r.screen !== 'portfolio' && r.screen === route.screen) ? 'page' : undefined); + const groups = d.studios.length ? groupByStudio(visible.map(a => ({ app: a })), d.studios) : [{ studio: null as string | null, rows: visible.map(a => ({ app: a })) }]; + const ignoredCount = d.apps.filter(a => a.ignored).length + d.overrides.ignored.filter(i => i.startsWith('account:')).length; + + const appItem = (a: UnifiedApp) => { + const e = d.statusFor(a); + const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0); + return ( +
+ +
+ ); + }; return ( @@ -117,32 +154,32 @@ export function App({ onTheme }: { onTheme: () => void }) {
-
{t('nav.appsLabel')} +
{d.studios.length ? t('nav.studiosLabel') : t('nav.appsLabel')}
-
- {d.projects.map(p => { - const e = d.statusOf(p); - const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0); - return ( -
- -
- ); - })} - {!d.projects.length &&

{t('nav.noApps')}

} -
+ {groups.map(g => { + const s = d.studios.find(x => x.id === g.studio) ?? null; + const gid = g.studio ?? 'none'; + const open = !collapsed.includes(gid); + if (!d.studios.length) return
{g.rows.map(r => appItem(r.app))}
; + return ( +
+ + {open &&
{g.rows.map(r => appItem(r.app))}
} +
+ ); + })} + {!visible.length &&

{t('nav.noApps')}

}
{t('nav.workspace')}
{WORKSPACE.map((s, i) => ( ))}
@@ -165,17 +202,18 @@ export function App({ onTheme }: { onTheme: () => void }) { {FIXTURES && {t('dev.fixtures')}} {lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')} -
{route.screen === 'portfolio' && } - {route.screen === 'app' && app && } + {route.screen === 'app' && app && } {route.screen === 'apps' && } - {route.screen === 'accounts' && } + {route.screen === 'accounts' && } + {route.screen === 'ignored' && } {route.screen === 'dependencies' && } - {route.screen === 'settings' && } + {route.screen === 'settings' && }
diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 881cc95..e97a1e6 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -3,10 +3,11 @@ // release builds, so that branch and the fixture module are dropped from them (tests/webview.test.ts checks dist/). import { invoke as tauriInvoke } from '@tauri-apps/api/core'; import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event'; -import type { DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol'; +import type { AccountCheck, AppsListResult, DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol'; +import type { Overrides } from './lib/identity'; export type { - AppIdentity, AppStatus, CatalogParity, DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, + AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, } from '../../../cli/lib/desktop-protocol'; @@ -17,7 +18,21 @@ export interface SidecarStatus { running: boolean; version: string; protocol: st /** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */ export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string } export type AccountKind = 'play' | 'apple'; -export interface Account { id: string; label: string; kind: AccountKind; created: string } +export interface Account { id: string; label: string; kind: AccountKind; created: string; studio?: string | null } +export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const; +export type StudioColor = (typeof STUDIO_COLORS)[number]; +/** A user-named group of store accounts (and so of apps). */ +export interface Studio { id: string; name: string; color: StudioColor; logo: string | null; created: string } +export interface Settings { + refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean }; + cache: { keepDays: 0 | 7 | 30 | 90 | 365 }; + notify: { reviewState: boolean; lowReviews: boolean; crash: boolean }; + channel: 'stable' | 'beta'; +} +export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' }; +export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings } +export interface AccountApps { account: string; entry: CacheEntry | null } +export interface CacheInfo { rows: number; bytes: number; oldest: string | null; file_bytes: number } export interface WriteOutcome { confirmed: boolean; stage: 'dry-run' | 'dialog' | 'done'; dryRun: ToolResult; result?: ToolResult } export interface CacheEntry { 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 } @@ -70,10 +85,28 @@ export const api = { removeProject: (id: string) => invoke('project_remove', { id }), setProjectAccounts: (id: string, play: string | null, apple: string | null) => invoke('project_set_accounts', { id, play, apple }), accounts: () => invoke('accounts_list'), - addPlayAccount: (label: string) => invoke('account_add_play', { label }), - addAppleAccount: (label: string, keyId: string, issuerId: string) => invoke('account_add_apple', { label, keyId, issuerId }), + addPlayAccount: (label: string, studio: string | null = null) => invoke('account_add_play', { label, studio }), + addAppleAccount: (label: string, keyId: string, issuerId: string, studio: string | null = null) => invoke('account_add_apple', { label, keyId, issuerId, studio }), removeAccount: (id: string) => invoke('account_remove', { id }), - portfolio: (live = false, job?: string) => invoke('portfolio_status', { live, job: job ?? null }), + updateAccount: (id: string, label: string, studio: string | null) => invoke('account_update', { id, label, studio }), + /** Does the key work, can it see apps (live, not cached). */ + checkAccount: (id: string, job?: string) => invoke('account_check', { id, job: job ?? null }), + /** Reads the apps an account can see from its store and keeps the list. */ + refreshStoreApps: (id: string, job?: string) => invoke>('store_apps_refresh', { id, job: job ?? null }), + storeAppsCached: () => invoke('store_apps_cached'), + workspace: () => invoke('workspace_get'), + saveStudio: (id: string | null, name: string, color: StudioColor) => invoke('studio_save', { id, name, color }), + removeStudio: (id: string) => invoke('studio_remove', { id }), + studioLogo: (id: string, clear = false) => invoke('studio_logo', { id, clear }), + setOverrides: (overrides: Overrides) => invoke('overrides_set', { overrides }), + setSettings: (settings: Settings) => invoke('settings_set', { settings }), + cacheInfo: () => invoke('cache_info'), + revealData: () => invoke('data_reveal'), + notify: (title: string, body: string) => invoke('notify', { title, body }), + /** Native confirmation first; true when everything was forgotten. */ + reset: () => invoke('app_reset'), + /** Offline (folders) or live; live also reads the given store-only apps (store targets). */ + portfolio: (live = false, job?: string, stores: string[] = []) => invoke('portfolio_status', { live, stores, job: job ?? null }), openExternal: (url: string) => invoke('open_external', { url }), toolsInfo: () => invoke('tools_info'), installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke('tools_install', { tool, job }), diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 06c9226..1af6778 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -3,7 +3,9 @@ // screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window // shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do // not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER). -import type { Account, AppStatus, CacheEntry, DownloadEvent, DraftsResult, ListingField, ListingsResult, PortfolioResult, Project, ProjectSummary, StoreRelease, ToolResult } from '../api'; +import { type Account, type AccountCheck, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, + type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api'; +import { buildApps, type Overrides } from '../lib/identity'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model'; export const FIXTURE_MARKER = 'storebound-dev-fixtures'; @@ -32,16 +34,88 @@ const ICONS: Record = { 'p-tidy': svg(``), }; -// ---- workspace ---- +// ---- workspace: 3 studios, 2 Play service accounts + 3 App Store Connect teams, 2 app folders, store-only apps ---- +// Placeholder names only (example.com style): no real studio, person, team or id. +const P1 = '0a1b2c3d4e5f6071', P2 = '1b2c3d4e5f607182', A1 = '2c3d4e5f60718293', A2 = '3d4e5f6071829304', A3 = '4e5f607182930415'; +const S1 = 's-example', S2 = 's-sample', S3 = 's-demo'; +let studios: Studio[] = [ + { id: S1, name: 'Example Games', color: 'indigo', logo: null, created: iso(60 * 24 * 30) }, + { id: S2, name: 'Sample Labs', color: 'emerald', logo: null, created: iso(60 * 24 * 20) }, + { id: S3, name: 'Demo Indie', color: 'amber', logo: null, created: iso(60 * 24 * 9) }, +]; let projects: Project[] = [ - { id: 'p-prism', path: `${HOME}/apps/prism-puddle`, name: 'Prism Puddle', playAccount: 'a-play', appleAccount: 'a-apple', added: iso(60 * 24 * 12) }, - { id: 'p-tidy', path: `${HOME}/apps/tidy-lists`, name: 'Tidy Lists', playAccount: 'a-play', appleAccount: 'a-apple', added: iso(60 * 24 * 5) }, + { id: 'p-prism', path: `${HOME}/apps/prism-puddle`, name: 'Prism Puddle', playAccount: P1, appleAccount: A1, added: iso(60 * 24 * 12) }, + { id: 'p-tidy', path: `${HOME}/apps/tidy-lists`, name: 'Tidy Lists', playAccount: P1, appleAccount: A2, added: iso(60 * 24 * 5) }, ]; let accounts: Account[] = [ - { id: 'a-play', label: 'Example Studio · Play', kind: 'play', created: iso(60 * 24 * 12) }, - { id: 'a-apple', label: 'Example Studio · App Store', kind: 'apple', created: iso(60 * 24 * 12) }, + { id: P1, label: 'Example Games · Play', kind: 'play', created: iso(60 * 24 * 30), studio: S1 }, + { id: A1, label: 'Example Games · App Store (company)', kind: 'apple', created: iso(60 * 24 * 30), studio: S1 }, + { id: P2, label: 'Sample Labs · Play', kind: 'play', created: iso(60 * 24 * 20), studio: S2 }, + { id: A2, label: 'Sample Labs · App Store', kind: 'apple', created: iso(60 * 24 * 20), studio: S2 }, + { id: A3, label: 'Demo Indie · App Store (individual)', kind: 'apple', created: iso(60 * 24 * 9), studio: S3 }, ]; -if (import.meta.env.VITE_FIXTURES === 'empty') { projects = []; accounts = []; } +if (import.meta.env.VITE_FIXTURES === 'empty') { projects = []; accounts = []; studios = []; } + +/** Small drawn icons for the store apps (fixture art). */ +const glyph = (a: string, b: string, inner: string) => `data:image/svg+xml;base64,${btoa(`${inner}`)}`; +const G = { + orbit: glyph('#0ea5e9', '#6366f1', ''), + block: glyph('#22c55e', '#15803d', ''), + lantern: glyph('#f59e0b', '#b45309', 'W'), + tycoon: glyph('#a855f7', '#6d28d9', '$'), + racer: glyph('#ef4444', '#991b1b', ''), + habit: glyph('#14b8a6', '#0f766e', ''), + focus: glyph('#f43f5e', '#be123c', ''), + sketch: glyph('#fb923c', '#ea580c', ''), + night: glyph('#1e293b', '#4338ca', ''), + mood: glyph('#ec4899', '#8b5cf6', ''), +}; +const ios = (id: string, bundleId: string, name: string, icon: string | null, latest: [string, string] | null): StoreApp => + ({ store: 'ios', id, bundleId, name, platforms: ['IOS'], sku: null, primaryLocale: 'en-US', latest: latest ? { version: latest[0], state: latest[1], platform: 'IOS' } : null, icon }); +const droid = (pkg: string, name: string, icon: string | null): StoreApp => ({ store: 'android', id: pkg, bundleId: pkg, name, platforms: ['ANDROID'], sku: null, primaryLocale: null, latest: null, icon }); +const STORE_APPS: Record = { + // one Play service account invited to two developer accounts: it sees Example Games' and Sample Labs' Play apps + [P1]: [ + droid('com.example.prismpuddle', 'Prism Puddle', null), droid('com.example.tidylists', 'Tidy Lists', null), droid('com.example.orbithop', 'Orbit Hop', G.orbit), + droid('com.example.blockgarden', 'Block Garden', G.block), droid('com.example.lantern.words', 'Word Lantern', G.lantern), droid('com.example.pockettycoon', 'Pocket Tycoon', G.tycoon), + droid('com.example.nightnotes.free', 'Nightnotes Free', G.night), droid('com.example.moodgrid', 'Mood Grid', G.mood), + ], + [A1]: [ + ios('6400000001', 'com.example.prismpuddle', 'Prism Puddle', null, ['2.4.0', 'WAITING_FOR_REVIEW']), ios('6400000011', 'com.example.orbithop', 'Orbit Hop', G.orbit, ['3.1.0', 'READY_FOR_SALE']), + ios('6400000012', 'com.example.blockgarden.ios', 'Block Garden', G.block, ['1.2.0', 'IN_REVIEW']), ios('6400000013', 'com.example.wordlantern', 'Word Lantern', G.lantern, ['2.0.1', 'READY_FOR_SALE']), + ios('6400000014', 'com.example.oldracer', 'Old Racer', G.racer, ['1.9.3', 'REMOVED_FROM_SALE']), + ], + [A2]: [ + ios('6400000002', 'com.example.tidylists', 'Tidy Lists', null, ['1.5.0', 'PREPARE_FOR_SUBMISSION']), ios('6400000021', 'com.example.habithatch', 'Habit Hatch', G.habit, ['1.0.4', 'READY_FOR_SALE']), + ios('6400000022', 'com.example.focustimer', 'Focus Timer Mini', G.focus, ['2.2.0', 'READY_FOR_SALE']), + ], + [A3]: [ios('6400000031', 'com.example.starsketch', 'Star Sketch', G.sketch, ['1.1.0', 'READY_FOR_SALE']), ios('6400000032', 'com.example.nightnotes', 'Night Notes', G.night, ['4.0.0', 'READY_FOR_SALE'])], +}; +// Sample Labs' Play service account was never invited: no app list, and its check says what to do +const IMPORTED: Record = { [P1]: 60 * 3, [A1]: 60 * 3, [A2]: 60 * 3, [A3]: 60 * 26 }; +let overrides: Overrides = { + pairs: [{ ios: `ios:${A3}:6400000032`, android: `android:${P1}:com.example.nightnotes.free` }], + unpairs: [], links: [], + appStudio: [{ key: `android:${P1}:com.example.moodgrid`, studio: S3 }], + ignored: [`app:ios:${A1}:6400000014`], +}; +if (import.meta.env.VITE_FIXTURES === 'empty') overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] }; +let settings: Settings = { ...DEFAULT_SETTINGS, refresh: { ...DEFAULT_SETTINGS.refresh, autoMinutes: 60 } }; +const PLAY_INVITE = (who: string) => `Play Console > Users and permissions > Invite new users: add ${who}. Account permissions: "View app information and download bulk reports (read-only)"; per app, as needed: "Manage store presence", "Manage testing tracks", "Release to production, exclude devices and use Play App Signing" (rollouts), "Reply to reviews", "Manage orders and subscriptions". One service account can be invited to several developer accounts.`; +const CHECKS: Record = { + [P1]: { store: 'android', status: 'ok', principal: 'storebound@example-games-123.iam.gserviceaccount.com', apps: 8, message: 'The service account can see 8 apps.', fix: null, docs: null }, + [P2]: { store: 'android', status: 'permission', principal: 'storebound@sample-labs-456.iam.gserviceaccount.com', apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: PLAY_INVITE('storebound@sample-labs-456.iam.gserviceaccount.com'), docs: 'https://play.google.com/console/developers/users-and-permissions' }, + [A1]: { store: 'ios', status: 'ok', principal: null, apps: 5, message: 'The key works and can read the team\'s apps.', fix: null, docs: null }, + [A2]: { store: 'ios', status: 'ok', principal: null, apps: 3, message: 'The key works and can read the team\'s apps.', fix: null, docs: null }, + [A3]: { store: 'ios', status: 'ok', principal: null, apps: 2, message: 'The key works and can read the team\'s apps.', fix: null, docs: null }, +}; +const appsEntry = (id: string): CacheEntry | null => (STORE_APPS[id] && IMPORTED[id] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold' + ? { value: { store: accounts.find(a => a.id === id)?.kind === 'play' ? 'android' : 'ios', apps: STORE_APPS[id]!, warnings: [], at: iso(IMPORTED[id]!) }, at: iso(IMPORTED[id]!) } : null); +/** Store-only apps as the window pairs them (so the cached live read covers them too). */ +const storeTargets = () => buildApps({ + projects, accounts, overrides, summaryOf: p => SUMMARY[p.id], + storeApps: accounts.map(a => ({ account: a.id, apps: appsEntry(a.id)?.value.apps ?? [] })), +}).filter(a => !a.project && !a.ignored); const SUMMARY: Record = { 'p-prism': { @@ -98,7 +172,39 @@ function status(id: string, live: boolean): AppStatus { storeErrors: {}, errors: [], }; } -const portfolio = (live: boolean): PortfolioResult => ({ apps: projects.map(p => status(p.id, live)), at: live ? iso(14) : iso(0) }); +/** Store-only app releases (fixture), by bundle id / package name. */ +const STORE_RELEASES: Record = { + 'com.example.orbithop': [rel('ios', '3.1.0', 'live', { build: '88', state: 'READY_FOR_SALE', date: iso(60 * 24 * 6) }), rel('android', '3.1.0', 'rollout', { build: '310', state: 'inProgress', fraction: 0.5 })], + 'com.example.blockgarden.ios': [rel('ios', '1.2.0', 'review', { build: '17', state: 'IN_REVIEW', date: iso(60 * 5) }), rel('ios', '1.1.2', 'live', { build: '15', state: 'READY_FOR_SALE', date: iso(60 * 24 * 40) })], + 'com.example.blockgarden': [rel('android', '1.2.0', 'live', { build: '120', state: 'completed' })], + 'com.example.wordlantern': [rel('ios', '2.0.1', 'live', { build: '41', state: 'READY_FOR_SALE', date: iso(60 * 24 * 18) })], + 'com.example.lantern.words': [rel('android', '2.0.1', 'halted', { build: '201', state: 'halted', fraction: 0.1 })], + 'com.example.pockettycoon': [rel('android', '5.4.0', 'live', { build: '540', state: 'completed' })], + 'com.example.habithatch': [rel('ios', '1.0.4', 'live', { build: '9', state: 'READY_FOR_SALE', date: iso(60 * 24 * 60) })], + 'com.example.focustimer': [rel('ios', '2.2.0', 'live', { build: '30', state: 'READY_FOR_SALE', date: iso(60 * 24 * 3) }), rel('ios', '2.3.0', 'rejected', { build: '31', state: 'REJECTED', date: iso(60 * 10) })], + 'com.example.starsketch': [rel('ios', '1.1.0', 'live', { build: '12', state: 'READY_FOR_SALE', date: iso(60 * 24 * 12) })], + 'com.example.nightnotes': [rel('ios', '4.0.0', 'live', { build: '77', state: 'READY_FOR_SALE', date: iso(60 * 24 * 2) })], + 'com.example.nightnotes.free': [rel('android', '4.0.0', 'rollout', { build: '400', state: 'inProgress', fraction: 0.2 })], + 'com.example.moodgrid': [rel('android', '0.9.0', 'testing', { build: '9', state: 'completed', track: 'beta' })], +}; +function storeStatus(target: string, live: boolean): AppStatus { + const ios = /ios:[^:]+:(\d+):([^;]+)/.exec(target), android = /android:[^:]+:([^;]+)/.exec(target); + const bundle = ios?.[2] ?? null, pkg = android?.[1] ?? null; + const all = [...(bundle ? STORE_RELEASES[bundle] ?? [] : []), ...(pkg ? STORE_RELEASES[pkg] ?? [] : [])]; + const name = Object.values(STORE_APPS).flat().find(a => a.bundleId === (bundle ?? pkg))?.name ?? bundle ?? pkg ?? '?'; + const versions = [...new Set(all.map(r => r.version!))].sort().reverse(); + const live1 = versions.find(v => all.some(r => r.version === v && ['live', 'rollout', 'halted'].includes(r.phase))) ?? null; + const next1 = versions.find(v => !live1 || v > live1) ?? null; + const s: ProjectSummary = { dir: '', config: '', name, languages: ['en'], play: pkg ? { packageName: pkg } : null, apple: bundle ? { bundleId: bundle, appId: ios![1]! } : null, + platforms: [...(bundle ? ['ios' as const] : []), ...(pkg ? ['android' as const] : [])], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0 }; + return { + project: target, ok: true, virtual: true, summary: s, check: { ok: true, problems: [], warnings: [] }, + app: { id: target, name, platforms: { ios: bundle ? { bundleId: bundle, ascAppId: ios![1]! } : null, android: pkg ? { packageName: pkg } : null } }, + release: live ? { source: 'live', current: live1 ? train(all, live1) : null, next: next1 && next1 !== live1 ? train(all, next1) : null, all } : { source: 'none', current: null, next: null }, + catalog: { checked: 'config', products: 0, subscriptions: 0, onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [], ok: true }, storeErrors: {}, errors: [], + }; +} +const portfolio = (live: boolean, stores: string[] = []): PortfolioResult => ({ apps: [...projects.map(p => status(p.id, live)), ...(live ? stores.map(s => storeStatus(s, true)) : [])], at: live ? iso(14) : iso(0) }); // ---- per-app store reads ---- const series = (n: number, base: number, drift: number, seed: number): number[] => @@ -282,7 +388,23 @@ let chromeInstalled = false; const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data }); +const STORE_REVIEWS: Review[] = [ + R('apple', 's-a1', 5, 'Lovely', 'Simple and quick, does exactly what it says.', 'USA', 1), + R('play', 's-p1', 1, 'Stuck on loading', 'Since the last update it stays on the loading screen on my tablet.', 'en', 1), + R('apple', 's-a2', 4, 'Nice update', 'The new widgets are great. Please add a dark icon.', 'GBR', 3), + R('play', 's-p2', 2, 'Too many ads', 'An ad after every round is too much.', 'en', 5), + R('apple', 's-a3', 5, 'Harika', 'Her gün kullanıyorum, çok sade.', 'TUR', 7), +]; function read(method: string, id: string): ToolResult { + if (id.startsWith('store:')) { + const play = /android:/.test(id); + switch (method) { + case 'health': return ok(method, play ? HEALTH['p-tidy'] : { date: day(0), apple: HEALTH['p-tidy']!.apple }); + case 'reviews.list': return ok(method, STORE_REVIEWS.filter(r => (play || r.store === 'apple') && (/ios:/.test(id) || r.store === 'play'))); + case 'apple.testflight_status': return ok(method, TF['p-tidy']); + default: return { method, ok: false, exitCode: 1, dryRun: false, command: `storebound ${method}`, output: `fixture: ${method} needs an app folder` }; + } + } switch (method) { case 'project.icon': return ok(method, { path: SUMMARY[id]?.icon ?? null, dataUrl: ICONS[id] ?? null }); case 'project.listings': return ok(method, LISTINGS[id]); @@ -316,21 +438,48 @@ async function answer(cmd: string, a: Record): Promise case 'sidecar_status': return { running: true, version: '0.5.0', protocol: 'storebound-desktop/1', methods: Array.from({ length: 64 }, (_, i) => ({ method: `m${i}` })), tools: { tools: TOOLS.map(x => (x.id === 'chrome' && chromeInstalled ? { ...x, found: true, name: 'Chrome for Testing', version: '141.0.7390.54', source: 'app' } : x)) } }; case 'projects_list': return projects; case 'accounts_list': return accounts; + case 'workspace_get': return { studios, overrides, settings }; + case 'store_apps_cached': return accounts.map(x => ({ account: x.id, entry: appsEntry(x.id) })); + case 'store_apps_refresh': { + const id = a.id as string; + await progressLines(job, ['[apps] reading the account\'s apps', '[apps] icons']); + if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; + if (!STORE_APPS[id]) throw { code: -32603, message: `Google Play: ${CHECKS[id]?.message ?? 'no apps'}` }; + IMPORTED[id] = 0; + return appsEntry(id); + } + case 'account_check': await sleep(350); return CHECKS[a.id as string]; + case 'studio_save': { + const s = a.id ? studios.find(x => x.id === a.id)! : { id: `s-${studios.length + 1}`, logo: null, created: iso(0) } as Studio; + Object.assign(s, { name: a.name, color: a.color }); + if (!a.id) studios = [...studios, s]; + return s; + } + case 'studio_remove': studios = studios.filter(s => s.id !== a.id); accounts = accounts.map(x => (x.studio === a.id ? { ...x, studio: null } : x)); return null; + case 'studio_logo': return null; + case 'account_update': { const x = accounts.find(y => y.id === a.id)!; x.label = a.label as string; x.studio = (a.studio as string | null) ?? null; return x; } + case 'overrides_set': overrides = a.overrides as Overrides; return overrides; + case 'settings_set': settings = a.settings as Settings; return settings; + 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 'app_reset': return false; case 'portfolio_status': { + const stores = (a.stores as string[] | undefined) ?? []; if (a.live) { - for (let n = 1; n <= projects.length; n++) { - await sleep(700); + const total = projects.length + stores.length; + for (let n = 1; n <= total; n++) { + await sleep(total > 6 ? 180 : 700); if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; - emit('sidecar-progress', { params: { requestId: 0, n, total: projects.length, project: projects[n - 1]!.path }, job }); + emit('sidecar-progress', { params: { requestId: 0, n, total, project: projects[n - 1]?.path ?? stores[n - 1 - projects.length] }, job }); } - return portfolio(true); + return portfolio(true, stores); } await sleep(120); return portfolio(false); } case 'cache_get': { const method = a.method as string, id = a.projectId as string; - if (id === '*' && method === 'portfolio.status') return projects.length ? { value: portfolio(true), at: iso(14) } satisfies CacheEntry : null; + if (id === '*' && method === 'portfolio.status') return projects.length ? { value: portfolio(true, storeTargets().map(x => x.target)), at: iso(14) } satisfies CacheEntry : null; if (method === 'project.icon') return ICONS[id] ? { value: read(method, id), at: iso(60) } : null; if (CACHED_AGO[method] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold') return { value: read(method, id), at: iso(CACHED_AGO[method]!) }; return null; diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 372bf62..4da4161 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -8,7 +8,7 @@ export const en = { 'nav.appsLabel': 'Apps', 'nav.workspace': 'Workspace', 'nav.apps': 'App folders', - 'nav.accounts': 'Accounts', + 'nav.accounts': 'Studios & accounts', 'nav.dependencies': 'Dependencies', 'nav.settings': 'Settings', 'nav.noApps': 'No apps yet', @@ -557,4 +557,221 @@ export const en = { 'wz.back': 'Back', 'wz.next': 'Next', 'wz.finish': 'Finish', + + 'nav.ignored': 'Ignored', + 'nav.studios': 'Studios', + 'nav.studiosLabel': 'Studios', + 'palette.studio': 'Studio', + 'action.importApps': 'Import apps', + 'action.importAppsHint': 'Read-only: every app each store account can see, from App Store Connect and Google Play', + 'apps.storeOnly': 'Store only', + 'apps.storeOnlyHint': 'On a store account, no app folder yet: store data only (read-only)', + 'common.save': 'Save', + 'studio.studio': 'Studio', + 'studio.none': 'No studio', + 'studio.noneSub': 'Accounts not in a studio yet', + 'studio.new': 'New studio', + 'studio.newSub': 'A studio groups store accounts, and with them their apps', + 'studio.name': 'Name', + 'studio.namePlaceholder': 'Example Games', + 'studio.color': 'Colour', + 'studio.add': 'Add a studio', + 'studio.added': 'Studio {name} added', + 'studio.edit': 'Edit', + 'studio.logo': 'Logo', + 'studio.logoClear': 'Remove logo', + 'studio.remove': 'Remove', + 'studio.removeHint': 'Removes the studio only: its accounts and apps stay, without a studio', + 'studio.counts': '{count} accounts · {apps} apps · {store} store only', + 'studio.noAccounts': 'No store account in this studio yet: add one below and pick this studio.', + 'studio.allAssigned': 'Every account is in a studio.', + 'color.indigo': 'Indigo', + 'color.violet': 'Violet', + 'color.rose': 'Rose', + 'color.amber': 'Amber', + 'color.emerald': 'Emerald', + 'color.teal': 'Teal', + 'color.sky': 'Sky', + 'color.slate': 'Slate', + 'accounts.leadStudios': 'Studios group your store accounts: Google Play service accounts and App Store Connect team keys. Keys stay in the system keychain; apps come in with Import apps.', + 'accounts.emptyTextStudios': 'Add a studio, then its Google Play service account and App Store Connect keys. Import apps then lists every app those keys can see.', + 'accounts.playSubMany': 'Service account JSON key. One service account can be invited to several Play developer accounts: it sees all their apps.', + 'accounts.appleSubMany': 'One API key per team (company or individual): key id, issuer id and the .p8 file.', + 'accounts.safetyStudios': 'Keys are read once from the file you pick, stored in the system keychain and never shown again. storebound gets one account\'s key in memory for one call. Studio names, labels and app lists stay on this computer.', + 'acct.ok': 'Works', + 'acct.noApps': 'No apps', + 'acct.permission': 'Permission missing', + 'acct.revoked': 'Key revoked', + 'acct.apiDisabled': 'API off', + 'acct.error': 'Not reachable', + 'acct.notTested': 'Not tested', + 'acct.kindPlay': 'Google Play service account', + 'acct.kindApple': 'App Store Connect team key', + 'acct.appsRead': '{count} apps, read {when}', + 'acct.appsRead_one': '1 app, read {when}', + 'acct.notImported': 'apps not imported yet', + 'acct.folders': 'used by {count} folders', + 'acct.folders_one': 'used by 1 folder', + 'acct.test': 'Test', + 'acct.testAll': 'Test all accounts', + 'acct.import': 'Import apps', + 'acct.edit': 'Rename or move to a studio', + 'acct.editAria': 'Edit {label}', + 'acct.ignore': 'Ignore this account', + 'acct.ignoreHint': 'Ignore: leave this account\'s apps out of the portfolio and store reads', + 'acct.unignore': 'Show this account again', + 'acct.ignored': 'Ignored', + 'acct.openFix': 'Open', + 'ignored.lead': 'Apps and accounts left out of the portfolio, the sidebar and store reads. Nothing on the stores changes.', + 'ignored.restoreAll': 'Restore all', + 'ignored.restore': 'Restore', + 'ignored.emptyTitle': 'Nothing is ignored', + 'ignored.emptyText': 'Ignore an app from its page (or a whole account in Studios & accounts) to keep test apps and old titles out of the way.', + 'ignored.apps': 'Apps', + 'ignored.appsSub': '{count} ignored', + 'ignored.accounts': 'Accounts', + 'ignored.accountsSub': 'Every app of these accounts is left out', + 'ignored.accountApps': '{count} apps', + 'ignored.accountApps_one': '1 app', + 'ignored.noApps': 'No ignored app.', + 'ignored.noAccounts': 'No ignored account.', + 'ignored.howTo': 'Pairing and single-store apps:', + 'ignored.toPairing': 'Settings > App pairing', + 'pair.folder': 'From its app folder', + 'pair.manual': 'Paired by hand', + 'pair.id': 'Paired: same bundle id and package name', + 'pair.close': 'Paired: close ids', + 'pair.name': 'Paired: same name', + 'pair.single': 'One store only', + 'app.moveStudio': 'Move to a studio', + 'app.pairWith': 'Pair with', + 'app.pairWithName': 'Pair {name} with', + 'app.pick': 'Pick an app', + 'app.unpair': 'Unpair', + 'app.ignore': 'Ignore', + 'app.ignoreHint': 'Leave this app out of the portfolio and store reads (Ignored lists it to restore)', + 'app.studioHint': 'Open the studio', + 'app.storeOnlyTitle': 'Store only.', + 'app.storeOnlyText': 'This app is on your store accounts but has no app folder: releases, reviews, health and TestFlight are shown read-only. Link its folder, or start one, to manage listings, products and checks.', + 'app.linkFolder': 'Link a folder', + 'app.initHere': 'Start an app folder here', + 'app.linked': '{name} is linked', + 'app.linkFailed': 'Could not link the folder', + 'portfolio.subStudios': '{count} apps · {stores} store listings · {studios} studios', + 'portfolio.emptyAccounts': 'Add a studio and its accounts', + 'portfolio.notImported': 'Apps of {count} accounts are not imported yet: Import apps lists everything those keys can see.', + 'portfolio.notImported_one': 'Apps of 1 account are not imported yet: Import apps lists everything its key can see.', + 'portfolio.toolbar': 'Filter and sort the apps', + 'portfolio.search': 'Search apps, bundle ids, packages', + 'portfolio.studioFilter': 'Studio', + 'portfolio.allStudios': 'All studios', + 'portfolio.sort': 'Sort', + 'portfolio.sortAttention': 'Needs attention', + 'portfolio.sortRecent': 'Recently updated', + 'portfolio.sortName': 'Name', + 'portfolio.group': 'Group by studio', + 'portfolio.groupCount': '{count} apps', + 'portfolio.noConfig': 'No config', + 'portfolio.storeOnlyCheck': 'Store only', + 'portfolio.noMatch': 'No app matches', + 'portfolio.noMatchText': 'Clear the search or pick another studio.', + 'portfolio.studiosN': '{count} studios', + 'portfolio.studiosN_one': '1 studio', + 'portfolio.folders': 'App folders', + 'portfolio.foldersN': '{count} folders · {store} store only', + 'portfolio.ignoredN': '{count} apps', + 'portfolio.ignoredN_one': '1 app', + 'kpi.appsSubStore': 'iOS {ios} · Android {android} · {store} store only', + 'toast.importing': 'Importing apps', + 'toast.importingDetail': 'Every app each account can see (read-only)', + 'toast.importDone': '{count} apps on your accounts', + 'toast.importDone_one': '1 app on your accounts', + 'toast.importDoneDetail': 'from {count} accounts', + 'toast.importDoneDetail_one': 'from 1 account', + 'toast.importPartial': '{count} accounts could not be read', + 'toast.importPartial_one': '1 account could not be read', + 'toast.saveFailed': 'Not saved', + 'notify.releaseTitle': '{name}: store state changed', + 'notify.releaseBody': '{store} {version}: {phase}', + 'notify.lowTitle': '{name}: {count} new low ratings', + 'notify.lowTitle_one': '{name}: a new low rating', + 'notify.crashTitle': '{name}: over the Play threshold', + 'set.lead': 'Studios, accounts, store reads, the offline cache, language, theme, notifications and more. Everything stays on this computer.', + 'set.sections': 'Settings sections', + 'set.studios': 'Studios & accounts', + 'set.studiosSub': 'Which accounts belong to which studio', + 'set.studioLine': 'Play {play} · App Store {apple} · {apps} apps', + 'set.noStudios': 'No studio yet. Studios group accounts and their apps in the portfolio and the sidebar.', + 'set.manage': 'Manage', + 'set.pairing': 'App pairing & ignore list', + 'set.pairingSub': 'An iOS and an Android app become one card when their ids or names match; pair or split them by hand here', + 'set.pairedHow': 'Pairing', + 'set.noCandidates': 'Nothing to pair with', + 'set.noStoreOnly': 'Every app has its folder: pairing comes from the configs.', + 'set.ignoredLine': 'Ignored: {count} apps, {accounts} accounts.', + 'set.openIgnored': 'Open the list', + 'set.refresh': 'Store reads', + 'set.refreshSub': 'Reads use each account\'s API quota: they run when you ask, or on the schedule here', + 'set.autoRefresh': 'Read the stores automatically', + 'set.autoHint': 'While the app is open. Off by default.', + 'set.off': 'Off', + 'set.min': '{n} min', + 'set.hour': '{n} h', + 'set.onLaunch': 'Read when the app starts', + 'set.onLaunchHint': 'Imports the apps of every account, then reads every app\'s store status', + 'set.icons': 'Store icons on import', + 'set.iconsHint': 'One extra request per app; folders use their own icon', + 'set.parallel': 'Apps read at the same time', + 'set.parallelHint': 'Fewer is gentler on rate limits', + 'set.cache': 'Offline cache', + 'set.cacheSub': 'The last store reads, shown with their time when you are offline', + 'set.cacheSize': 'On disk', + 'set.cacheRows': '{count} saved reads', + 'set.cacheRows_one': '1 saved read', + 'set.cacheOldest': 'Oldest', + 'set.keep': 'Keep saved reads', + 'set.days': '{n} days', + 'set.year': '1 year', + 'set.always': 'Always', + 'set.notifications': 'Notifications', + 'set.notificationsSub': 'After a read, when something changed since the previous one', + 'set.nReview': 'Review and release state changes', + 'set.nReviewHint': 'In review, approved, rejected, live, halted', + 'set.nLow': 'New 1 or 2 star reviews', + 'set.nLowHint': 'When the Reviews tab reads new ones', + 'set.nCrash': 'Crash or ANR rate over the threshold', + 'set.nCrashHint': 'Google Play bad behavior thresholds', + 'set.testNotify': 'Send a test notification', + 'set.testTitle': 'storebound', + 'set.testBody': 'Notifications work.', + 'set.appCopy': 'app copy', + 'set.depsText': 'Store work needs no local tool. Screenshots, previews and icons use ffmpeg and Chrome: one click on the Dependencies screen.', + 'set.cli': 'CLI sidecar', + 'set.protocol': 'Protocol', + 'set.state': 'State', + 'set.running': 'Running', + 'set.writes': 'Writes', + 'set.writesText': 'Dry run first, then your Apply in a system dialog. Submit, release and publish stay in the consoles.', + 'set.privacy': 'Privacy', + 'set.p1': 'No telemetry, no analytics, no crash reports: the app talks only to the stores, with your keys, when you ask.', + 'set.p2': 'Store keys live in the system keychain; the app data folder holds names, settings and saved reads, never keys.', + 'set.p3': 'Nothing is written into your app folders unless you confirm it in a system dialog.', + 'set.p4': 'Tester emails stay masked; review drafts stay in each app folder\'s .storebound/ (gitignored).', + 'set.reveal': 'Show the data folder', + 'set.scQuit': 'Quit', + 'set.updates': 'Updates', + 'set.channel': 'Channel', + 'set.stable': 'Stable', + 'set.beta': 'Beta', + 'set.updatesText': 'Signed updates from storebound.dev arrive with the first public desktop release; the channel is kept for then.', + '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.resetButton': 'Reset the app', + 'set.resetDone': 'storebound desktop was reset', + 'set.footer': '{n} apps known to this computer', + + 'studio.counts_one': '1 account · {apps} apps · {store} store only', + 'portfolio.groupCount_one': '1 app', + 'portfolio.groupAccounts': '{count} accounts', + 'portfolio.groupAccounts_one': '1 account', } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 3d71e9d..2837eee 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -10,7 +10,7 @@ export const tr: Record = { 'nav.appsLabel': 'Uygulamalar', 'nav.workspace': 'Çalışma alanı', 'nav.apps': 'Uygulama klasörleri', - 'nav.accounts': 'Hesaplar', + 'nav.accounts': 'Stüdyolar ve hesaplar', 'nav.dependencies': 'Bağımlılıklar', 'nav.settings': 'Ayarlar', 'nav.noApps': 'Henüz uygulama yok', @@ -559,4 +559,221 @@ export const tr: Record = { 'wz.back': 'Geri', 'wz.next': 'İleri', 'wz.finish': 'Bitir', + + 'nav.ignored': 'Yok sayılanlar', + 'nav.studios': 'Stüdyolar', + 'nav.studiosLabel': 'Stüdyolar', + 'palette.studio': 'Stüdyo', + 'action.importApps': 'Uygulamaları içe aktar', + 'action.importAppsHint': 'Salt okunur: her mağaza hesabının gördüğü tüm uygulamalar, App Store Connect ve Google Play\'den', + 'apps.storeOnly': 'Yalnızca mağaza', + 'apps.storeOnlyHint': 'Bir mağaza hesabında, henüz uygulama klasörü yok: yalnızca mağaza verisi (salt okunur)', + 'common.save': 'Kaydet', + 'studio.studio': 'Stüdyo', + 'studio.none': 'Stüdyosuz', + 'studio.noneSub': 'Henüz bir stüdyoda olmayan hesaplar', + 'studio.new': 'Yeni stüdyo', + 'studio.newSub': 'Stüdyo mağaza hesaplarını, onlarla birlikte uygulamalarını gruplar', + 'studio.name': 'Ad', + 'studio.namePlaceholder': 'Örnek Oyunlar', + 'studio.color': 'Renk', + 'studio.add': 'Stüdyo ekle', + 'studio.added': '{name} stüdyosu eklendi', + 'studio.edit': 'Düzenle', + 'studio.logo': 'Logo', + 'studio.logoClear': 'Logoyu kaldır', + 'studio.remove': 'Kaldır', + 'studio.removeHint': 'Yalnızca stüdyoyu kaldırır: hesapları ve uygulamaları stüdyosuz kalır', + 'studio.counts': '{count} hesap · {apps} uygulama · {store} yalnızca mağazada', + 'studio.noAccounts': 'Bu stüdyoda henüz mağaza hesabı yok: aşağıdan bir hesap ekleyip bu stüdyoyu seçin.', + 'studio.allAssigned': 'Her hesap bir stüdyoda.', + 'color.indigo': 'Çivit', + 'color.violet': 'Mor', + 'color.rose': 'Gül', + 'color.amber': 'Kehribar', + 'color.emerald': 'Zümrüt', + 'color.teal': 'Deniz mavisi', + 'color.sky': 'Gök mavisi', + 'color.slate': 'Arduvaz', + 'accounts.leadStudios': 'Stüdyolar mağaza hesaplarınızı gruplar: Google Play hizmet hesapları ve App Store Connect ekip anahtarları. Anahtarlar sistem anahtar zincirinde kalır; uygulamalar "Uygulamaları içe aktar" ile gelir.', + 'accounts.emptyTextStudios': 'Bir stüdyo, sonra onun Google Play hizmet hesabını ve App Store Connect anahtarlarını ekleyin. "Uygulamaları içe aktar" bu anahtarların gördüğü tüm uygulamaları listeler.', + 'accounts.playSubMany': 'Hizmet hesabı JSON anahtarı. Bir hizmet hesabı birden çok Play geliştirici hesabına davet edilebilir: hepsinin uygulamalarını görür.', + 'accounts.appleSubMany': 'Ekip başına bir API anahtarı (şirket ya da bireysel): anahtar kimliği, issuer kimliği ve .p8 dosyası.', + 'accounts.safetyStudios': 'Anahtarlar seçtiğiniz dosyadan bir kez okunur, sistem anahtar zincirine kaydedilir ve bir daha gösterilmez. storebound bir hesabın anahtarını tek bir çağrı için bellekte alır. Stüdyo adları, etiketler ve uygulama listeleri bu bilgisayarda kalır.', + 'acct.ok': 'Çalışıyor', + 'acct.noApps': 'Uygulama yok', + 'acct.permission': 'İzin eksik', + 'acct.revoked': 'Anahtar iptal', + 'acct.apiDisabled': 'API kapalı', + 'acct.error': 'Ulaşılamadı', + 'acct.notTested': 'Sınanmadı', + 'acct.kindPlay': 'Google Play hizmet hesabı', + 'acct.kindApple': 'App Store Connect ekip anahtarı', + 'acct.appsRead': '{count} uygulama, {when} okundu', + 'acct.appsRead_one': '1 uygulama, {when} okundu', + 'acct.notImported': 'uygulamalar henüz içe aktarılmadı', + 'acct.folders': '{count} klasör kullanıyor', + 'acct.folders_one': '1 klasör kullanıyor', + 'acct.test': 'Sına', + 'acct.testAll': 'Tüm hesapları sına', + 'acct.import': 'Uygulamaları al', + 'acct.edit': 'Yeniden adlandır ya da stüdyoya taşı', + 'acct.editAria': '{label} düzenle', + 'acct.ignore': 'Bu hesabı yok say', + 'acct.ignoreHint': 'Yok say: bu hesabın uygulamalarını portföy ve mağaza okumalarının dışında bırak', + 'acct.unignore': 'Bu hesabı yeniden göster', + 'acct.ignored': 'Yok sayıldı', + 'acct.openFix': 'Aç', + 'ignored.lead': 'Portföy, kenar çubuğu ve mağaza okumalarının dışında bırakılan uygulamalar ve hesaplar. Mağazalarda hiçbir şey değişmez.', + 'ignored.restoreAll': 'Tümünü geri getir', + 'ignored.restore': 'Geri getir', + 'ignored.emptyTitle': 'Yok sayılan bir şey yok', + 'ignored.emptyText': 'Test uygulamalarını ve eski başlıkları uzak tutmak için bir uygulamayı kendi sayfasından (ya da bütün bir hesabı Stüdyolar ve hesaplar\'dan) yok sayın.', + 'ignored.apps': 'Uygulamalar', + 'ignored.appsSub': '{count} yok sayıldı', + 'ignored.accounts': 'Hesaplar', + 'ignored.accountsSub': 'Bu hesapların tüm uygulamaları dışarıda', + 'ignored.accountApps': '{count} uygulama', + 'ignored.accountApps_one': '1 uygulama', + 'ignored.noApps': 'Yok sayılan uygulama yok.', + 'ignored.noAccounts': 'Yok sayılan hesap yok.', + 'ignored.howTo': 'Eşleştirme ve tek mağazalı uygulamalar:', + 'ignored.toPairing': 'Ayarlar > Uygulama eşleştirme', + 'pair.folder': 'Uygulama klasöründen', + 'pair.manual': 'Elle eşleştirildi', + 'pair.id': 'Eşleşti: aynı bundle id ve paket adı', + 'pair.close': 'Eşleşti: benzer kimlikler', + 'pair.name': 'Eşleşti: aynı ad', + 'pair.single': 'Tek mağaza', + 'app.moveStudio': 'Bir stüdyoya taşı', + 'app.pairWith': 'Şununla eşleştir', + 'app.pairWithName': '{name} uygulamasını şununla eşleştir', + 'app.pick': 'Bir uygulama seçin', + 'app.unpair': 'Eşleşmeyi ayır', + 'app.ignore': 'Yok say', + 'app.ignoreHint': 'Bu uygulamayı portföy ve mağaza okumalarının dışında bırak (Yok sayılanlar ekranından geri getirilir)', + 'app.studioHint': 'Stüdyoyu aç', + 'app.storeOnlyTitle': 'Yalnızca mağaza.', + 'app.storeOnlyText': 'Bu uygulama mağaza hesaplarınızda ama uygulama klasörü yok: sürümler, yorumlar, sağlık ve TestFlight salt okunur gösterilir. Mağaza metinlerini, ürünleri ve denetimleri yönetmek için klasörünü bağlayın ya da yeni bir klasör başlatın.', + 'app.linkFolder': 'Klasör bağla', + 'app.initHere': 'Burada uygulama klasörü başlat', + 'app.linked': '{name} bağlandı', + 'app.linkFailed': 'Klasör bağlanamadı', + 'portfolio.subStudios': '{count} uygulama · {stores} mağaza kaydı · {studios} stüdyo', + 'portfolio.emptyAccounts': 'Stüdyo ve hesaplarını ekle', + 'portfolio.notImported': '{count} hesabın uygulamaları henüz içe aktarılmadı: "Uygulamaları içe aktar" bu anahtarların gördüğü her şeyi listeler.', + 'portfolio.notImported_one': '1 hesabın uygulamaları henüz içe aktarılmadı: "Uygulamaları içe aktar" anahtarının gördüğü her şeyi listeler.', + 'portfolio.toolbar': 'Uygulamaları süz ve sırala', + 'portfolio.search': 'Uygulama, bundle id, paket ara', + 'portfolio.studioFilter': 'Stüdyo', + 'portfolio.allStudios': 'Tüm stüdyolar', + 'portfolio.sort': 'Sırala', + 'portfolio.sortAttention': 'Dikkat isteyen', + 'portfolio.sortRecent': 'Son güncellenen', + 'portfolio.sortName': 'Ad', + 'portfolio.group': 'Stüdyoya göre grupla', + 'portfolio.groupCount': '{count} uygulama', + 'portfolio.noConfig': 'Yapılandırma yok', + 'portfolio.storeOnlyCheck': 'Yalnızca mağaza', + 'portfolio.noMatch': 'Eşleşen uygulama yok', + 'portfolio.noMatchText': 'Aramayı temizleyin ya da başka bir stüdyo seçin.', + 'portfolio.studiosN': '{count} stüdyo', + 'portfolio.studiosN_one': '1 stüdyo', + 'portfolio.folders': 'Uygulama klasörleri', + 'portfolio.foldersN': '{count} klasör · {store} yalnızca mağazada', + 'portfolio.ignoredN': '{count} uygulama', + 'portfolio.ignoredN_one': '1 uygulama', + 'kpi.appsSubStore': 'iOS {ios} · Android {android} · {store} yalnızca mağazada', + 'toast.importing': 'Uygulamalar içe aktarılıyor', + 'toast.importingDetail': 'Her hesabın gördüğü tüm uygulamalar (salt okunur)', + 'toast.importDone': 'Hesaplarınızda {count} uygulama', + 'toast.importDone_one': 'Hesaplarınızda 1 uygulama', + 'toast.importDoneDetail': '{count} hesaptan', + 'toast.importDoneDetail_one': '1 hesaptan', + 'toast.importPartial': '{count} hesap okunamadı', + 'toast.importPartial_one': '1 hesap okunamadı', + 'toast.saveFailed': 'Kaydedilmedi', + 'notify.releaseTitle': '{name}: mağaza durumu değişti', + 'notify.releaseBody': '{store} {version}: {phase}', + 'notify.lowTitle': '{name}: {count} yeni düşük puan', + 'notify.lowTitle_one': '{name}: yeni bir düşük puan', + 'notify.crashTitle': '{name}: Play eşiğinin üstünde', + 'set.lead': 'Stüdyolar, hesaplar, mağaza okumaları, çevrimdışı önbellek, dil, tema, bildirimler ve dahası. Hepsi bu bilgisayarda kalır.', + 'set.sections': 'Ayar bölümleri', + 'set.studios': 'Stüdyolar ve hesaplar', + 'set.studiosSub': 'Hangi hesap hangi stüdyoya ait', + 'set.studioLine': 'Play {play} · App Store {apple} · {apps} uygulama', + 'set.noStudios': 'Henüz stüdyo yok. Stüdyolar hesapları ve uygulamalarını portföyde ve kenar çubuğunda gruplar.', + 'set.manage': 'Yönet', + 'set.pairing': 'Uygulama eşleştirme ve yok sayılanlar', + 'set.pairingSub': 'Bir iOS ve bir Android uygulaması kimlikleri ya da adları eşleşince tek kart olur; burada elle eşleştirin ya da ayırın', + 'set.pairedHow': 'Eşleştirme', + 'set.noCandidates': 'Eşleştirilecek bir şey yok', + 'set.noStoreOnly': 'Her uygulamanın klasörü var: eşleştirme yapılandırmalardan gelir.', + 'set.ignoredLine': 'Yok sayılan: {count} uygulama, {accounts} hesap.', + 'set.openIgnored': 'Listeyi aç', + 'set.refresh': 'Mağaza okumaları', + 'set.refreshSub': 'Okumalar her hesabın API kotasını kullanır: siz istediğinizde ya da buradaki zamanlamayla çalışır', + 'set.autoRefresh': 'Mağazaları otomatik oku', + 'set.autoHint': 'Uygulama açıkken. Varsayılan olarak kapalı.', + 'set.off': 'Kapalı', + 'set.min': '{n} dk', + 'set.hour': '{n} sa', + 'set.onLaunch': 'Uygulama açılınca oku', + 'set.onLaunchHint': 'Her hesabın uygulamalarını içe aktarır, sonra her uygulamanın mağaza durumunu okur', + 'set.icons': 'İçe aktarırken mağaza simgeleri', + 'set.iconsHint': 'Uygulama başına bir ek istek; klasörler kendi simgelerini kullanır', + 'set.parallel': 'Aynı anda okunan uygulama', + 'set.parallelHint': 'Daha az, hız sınırlarına daha nazik', + 'set.cache': 'Çevrimdışı önbellek', + 'set.cacheSub': 'Son mağaza okumaları, çevrimdışıyken zamanlarıyla gösterilir', + 'set.cacheSize': 'Diskte', + 'set.cacheRows': '{count} kayıtlı okuma', + 'set.cacheRows_one': '1 kayıtlı okuma', + 'set.cacheOldest': 'En eski', + 'set.keep': 'Kayıtlı okumaları sakla', + 'set.days': '{n} gün', + 'set.year': '1 yıl', + 'set.always': 'Her zaman', + 'set.notifications': 'Bildirimler', + 'set.notificationsSub': 'Bir okumadan sonra, öncekinden beri bir şey değiştiyse', + 'set.nReview': 'İnceleme ve yayın durumu değişiklikleri', + 'set.nReviewHint': 'İncelemede, onaylandı, reddedildi, yayında, durduruldu', + 'set.nLow': 'Yeni 1 ya da 2 yıldızlı yorumlar', + 'set.nLowHint': 'Yorumlar sekmesi yenilerini okuduğunda', + 'set.nCrash': 'Çökme ya da ANR oranı eşiğin üstünde', + 'set.nCrashHint': 'Google Play kötü davranış eşikleri', + 'set.testNotify': 'Deneme bildirimi gönder', + 'set.testTitle': 'storebound', + 'set.testBody': 'Bildirimler çalışıyor.', + 'set.appCopy': 'uygulama kopyası', + 'set.depsText': 'Mağaza işleri yerel araç gerektirmez. Ekran görüntüleri, önizlemeler ve simgeler ffmpeg ve Chrome kullanır: Bağımlılıklar ekranında tek tık.', + 'set.cli': 'CLI yardımcısı', + 'set.protocol': 'Protokol', + 'set.state': 'Durum', + 'set.running': 'Çalışıyor', + 'set.writes': 'Yazmalar', + 'set.writesText': 'Önce deneme, sonra sistem penceresinde sizin Uygula onayınız. Gönderme, yayınlama ve yayımlama konsollarda kalır.', + 'set.privacy': 'Gizlilik', + 'set.p1': 'Telemetri, analiz ya da çökme raporu yok: uygulama yalnızca siz istediğinizde, anahtarlarınızla mağazalarla konuşur.', + 'set.p2': 'Mağaza anahtarları sistem anahtar zincirinde durur; uygulama veri klasöründe adlar, ayarlar ve kayıtlı okumalar vardır, anahtar asla.', + 'set.p3': 'Siz bir sistem penceresinde onaylamadıkça uygulama klasörlerinize hiçbir şey yazılmaz.', + 'set.p4': 'Test kullanıcısı e-postaları maskeli kalır; yorum taslakları her uygulama klasörünün .storebound/ klasöründe (gitignore) kalır.', + 'set.reveal': 'Veri klasörünü göster', + 'set.scQuit': 'Çık', + 'set.updates': 'Güncellemeler', + 'set.channel': 'Kanal', + 'set.stable': 'Kararlı', + '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.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.resetButton': 'Uygulamayı sıfırla', + 'set.resetDone': 'storebound masaüstü sıfırlandı', + 'set.footer': 'Bu bilgisayarın bildiği {n} uygulama', + + 'studio.counts_one': '1 hesap · {apps} uygulama · {store} yalnızca mağazada', + 'portfolio.groupCount_one': '1 uygulama', + 'portfolio.groupAccounts': '{count} hesap', + 'portfolio.groupAccounts_one': '1 hesap', }; diff --git a/apps/desktop/src/lib/identity.ts b/apps/desktop/src/lib/identity.ts new file mode 100644 index 0000000..248f3a1 --- /dev/null +++ b/apps/desktop/src/lib/identity.ts @@ -0,0 +1,225 @@ +// One app card per product, across studios and store accounts. Pure, so tests/identity.test.ts pins every rule. +// +// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and +// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list). +// Order of matching: +// 1. a folder takes the store apps its config names (explicit link > App Store app id > bundle id / package name), +// preferring the accounts mapped to the folder; +// 2. the remaining store apps pair iOS + Android: manual pairs, then the same bundle id and package name, then a +// close id (".ios" / ".android" suffixes, case, punctuation) or the same name; unpairs block an automatic pair; +// 3. what is left is a single-platform store-only app. +// A store-only app is read through a "store target" (store:ios:::;android::). +import type { Account, AppStatus, Project, StoreApp } from '../api'; + +export interface Pair { ios: string; android: string } +export interface Overrides { + pairs: Pair[]; + unpairs: Pair[]; + links: { key: string; project: string }[]; + appStudio: { key: string; studio: string }[]; + ignored: string[]; +} +export const NO_OVERRIDES: Overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] }; + +/** One app record of one store account. */ +export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp } + +export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single'; + +export interface UnifiedApp { + /** Route and list key: the project id, else the store target. */ + key: string; + /** What reads use: the project id, else the store target ("store:..."). */ + target: string; + name: string; + project: Project | null; + ios: StoreRef | null; + android: StoreRef | null; + studio: string | null; + pairing: Pairing; + /** The keys an "ignore" puts on the list ("project:" or "app:"). */ + ignoreKeys: string[]; + ignored: boolean; + /** Store icon (data URL) when the folder has none. */ + storeIcon: string | null; +} + +export const refKey = (account: string, a: StoreApp): string => `${a.store}:${account}:${a.id}`; + +/** Store target of a store-only app. */ +export function storeTarget(ios: StoreRef | null, android: StoreRef | null): string { + const parts: string[] = []; + if (ios) parts.push(`ios:${ios.account}:${ios.app.id}:${ios.app.bundleId}`); + if (android) parts.push(`android:${android.account}:${android.app.id}`); + return `store:${parts.join(';')}`; +} + +/** "com.example.Puzzle.ios" -> "comexamplepuzzle": ids that differ only by a platform suffix, case or punctuation. */ +export function normId(id: string): string { + return id.toLowerCase().replace(/[._-](ios|iphone|android|droid|app)$/g, '').replace(/[^a-z0-9]/g, ''); +} +export const normName = (n: string): string => n.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]/g, ''); + +const samePair = (p: Pair, ios: string, android: string) => p.ios === ios && p.android === android; + +export interface BuildInput { + projects: Project[]; + /** Store ids of each folder's config (from the offline portfolio read). */ + summaryOf: (p: Project) => AppStatus['summary'] | undefined; + accounts: Account[]; + /** The last app list of each account. */ + storeApps: { account: string; apps: StoreApp[] }[]; + overrides: Overrides; +} + +export function buildApps(i: BuildInput): UnifiedApp[] { + const o = i.overrides; + const ignoredAccounts = new Set(o.ignored.filter(x => x.startsWith('account:')).map(x => x.slice(8))); + const accountStudio = new Map(i.accounts.map(a => [a.id, a.studio ?? null] as const)); + const known = new Set(i.accounts.map(a => a.id)); + // every store app of every (not ignored) account + const refs: StoreRef[] = []; + for (const s of i.storeApps) { + if (!known.has(s.account) || ignoredAccounts.has(s.account)) continue; + for (const app of s.apps) refs.push({ key: refKey(s.account, app), account: s.account, store: app.store, app }); + } + const used = new Set(); + const take = (r: StoreRef | null | undefined): StoreRef | null => { if (!r || used.has(r.key)) return null; used.add(r.key); return r; }; + const studioOverride = new Map(o.appStudio.map(x => [x.key, x.studio] as const)); + const ignored = new Set(o.ignored); + const out: UnifiedApp[] = []; + + // 1. folders + for (const p of i.projects) { + const s = i.summaryOf(p); + const mine = (r: StoreRef) => r.account === (r.store === 'ios' ? p.appleAccount : p.playAccount); + const rank = (rs: StoreRef[]) => [...rs].sort((a, b) => Number(mine(b)) - Number(mine(a))); + const linked = o.links.filter(l => l.project === p.id).map(l => refs.find(r => r.key === l.key)).filter((r): r is StoreRef => !!r && !used.has(r.key)); + let ios = take(linked.find(r => r.store === 'ios')); + let android = take(linked.find(r => r.store === 'android')); + if (!ios && s?.apple) { + const free = refs.filter(r => r.store === 'ios' && !used.has(r.key) && !o.links.some(l => l.key === r.key)); + ios = take(rank(free.filter(r => s.apple!.appId && r.app.id === s.apple!.appId))[0] ?? rank(free.filter(r => r.app.bundleId === s.apple!.bundleId))[0]); + } + if (!android && s?.play) { + const free = refs.filter(r => r.store === 'android' && !used.has(r.key) && !o.links.some(l => l.key === r.key)); + android = take(rank(free.filter(r => r.app.id === s.play!.packageName))[0]); + } + const studio = studioOverride.get(`project:${p.id}`) + ?? (p.appleAccount && accountStudio.get(p.appleAccount)) ?? (p.playAccount && accountStudio.get(p.playAccount)) + ?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null; + out.push({ + key: p.id, target: p.id, name: p.name, project: p, ios, android, studio, pairing: 'folder', + ignoreKeys: [`project:${p.id}`], ignored: ignored.has(`project:${p.id}`), storeIcon: ios?.app.icon ?? android?.app.icon ?? null, + }); + } + + // 2. pairs among the remaining store apps + const freeIos = () => refs.filter(r => r.store === 'ios' && !used.has(r.key)); + const freeAndroid = () => refs.filter(r => r.store === 'android' && !used.has(r.key)); + const blocked = (a: StoreRef, b: StoreRef) => o.unpairs.some(p => samePair(p, a.key, b.key)); + const sameStudio = (a: StoreRef, b: StoreRef) => (accountStudio.get(a.account) ?? null) === (accountStudio.get(b.account) ?? null); + const pairs: [StoreRef, StoreRef, Pairing][] = []; + for (const m of o.pairs) { + const a = freeIos().find(r => r.key === m.ios), b = freeAndroid().find(r => r.key === m.android); + if (a && b) { take(a); take(b); pairs.push([a, b, 'manual']); } + } + const auto = (how: Pairing, match: (a: StoreRef, b: StoreRef) => boolean) => { + for (const a of freeIos()) { + const cands = freeAndroid().filter(b => !blocked(a, b) && match(a, b)).sort((x, y) => Number(sameStudio(a, y)) - Number(sameStudio(a, x))); + const b = cands[0]; + if (b) { take(a); take(b); pairs.push([a, b, how]); } + } + }; + auto('id', (a, b) => a.app.bundleId === b.app.id); + auto('close', (a, b) => normId(a.app.bundleId) !== '' && normId(a.app.bundleId) === normId(b.app.id)); + auto('name', (a, b) => normName(a.app.name) !== '' && normName(a.app.name) === normName(b.app.name)); + + const storeOnly = (ios: StoreRef | null, android: StoreRef | null, pairing: Pairing) => { + const target = storeTarget(ios, android); + const keys = [ios, android].filter((r): r is StoreRef => !!r).map(r => r.key); + const studio = keys.map(k => studioOverride.get(k)).find(Boolean) + ?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null; + out.push({ + key: target, target, name: ios?.app.name ?? android?.app.name ?? '?', project: null, ios, android, studio, pairing, + ignoreKeys: keys.map(k => `app:${k}`), ignored: keys.some(k => ignored.has(`app:${k}`)), storeIcon: ios?.app.icon ?? android?.app.icon ?? null, + }); + }; + for (const [a, b, how] of pairs) storeOnly(a, b, how); + // 3. singles + for (const r of refs) if (!used.has(r.key)) { used.add(r.key); storeOnly(r.store === 'ios' ? r : null, r.store === 'android' ? r : null, 'single'); } + return out; +} + +/** Candidates to pair a single-platform app with (the other store's single apps), closest first. */ +export function pairCandidates(app: UnifiedApp, all: UnifiedApp[]): UnifiedApp[] { + if (app.project || (app.ios && app.android)) return []; + const want = app.ios ? 'android' : 'ios'; + const me = (app.ios ?? app.android)!; + const score = (x: UnifiedApp) => { + const r = (want === 'ios' ? x.ios : x.android)!; + return (normId(r.app.bundleId) === normId(me.app.bundleId) ? 4 : 0) + (normName(r.app.name) === normName(me.app.name) ? 2 : 0) + (x.studio === app.studio ? 1 : 0); + }; + return all.filter(x => !x.project && !x.ignored && (want === 'ios' ? x.ios && !x.android : x.android && !x.ios)).sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name)); +} + +/** Overrides after pairing two single store apps by hand (drops an unpair of the same two). */ +export function withPair(o: Overrides, ios: string, android: string): Overrides { + return { ...o, pairs: [...o.pairs.filter(p => p.ios !== ios && p.android !== android), { ios, android }], unpairs: o.unpairs.filter(p => !samePair(p, ios, android)) }; +} + +/** Overrides after splitting a paired app (keeps it apart from now on). */ +export function withUnpair(o: Overrides, ios: string, android: string): Overrides { + return { ...o, pairs: o.pairs.filter(p => !samePair(p, ios, android)), unpairs: [...o.unpairs.filter(p => !samePair(p, ios, android)), { ios, android }] }; +} + +export function withIgnored(o: Overrides, keys: string[], on: boolean): Overrides { + const set = new Set(o.ignored); + for (const k of keys) { if (on) set.add(k); else set.delete(k); } + return { ...o, ignored: [...set] }; +} + +/** Moves an app to a studio (null: back to its accounts' studio). */ +export function withStudio(o: Overrides, app: UnifiedApp, studio: string | null): Overrides { + const keys = app.project ? [`project:${app.project.id}`] : [app.ios?.key, app.android?.key].filter((k): k is string => !!k); + const rest = o.appStudio.filter(x => !keys.includes(x.key)); + return { ...o, appStudio: studio ? [...rest, ...keys.map(key => ({ key, studio }))] : rest }; +} + +/** Links the store apps of a store-only app to a folder. */ +export function withLink(o: Overrides, app: UnifiedApp, project: string): Overrides { + const keys = [app.ios?.key, app.android?.key].filter((k): k is string => !!k); + return { ...o, links: [...o.links.filter(l => !keys.includes(l.key)), ...keys.map(key => ({ key, project }))] }; +} + +// ---- Portfolio list: filter, search, sort, group ---- + +export type SortBy = 'attention' | 'recent' | 'name'; +export interface ListRow { app: UnifiedApp; attention: number; blockers: number; updated: string | null } + +export function filterSort(rows: ListRow[], o: { studio: string | 'all' | 'none'; query: string; sort: SortBy }): ListRow[] { + const q = o.query.trim().toLowerCase(); + const hit = (r: ListRow) => !q || [r.app.name, r.app.ios?.app.bundleId, r.app.android?.app.id, r.app.project?.path.split(/[\\/]/).pop()] + .some(s => s && s.toLowerCase().includes(q)); + const inStudio = (r: ListRow) => o.studio === 'all' || (o.studio === 'none' ? !r.app.studio : r.app.studio === o.studio); + const by = { + attention: (a: ListRow, b: ListRow) => b.blockers - a.blockers || b.attention - a.attention || a.app.name.localeCompare(b.app.name), + recent: (a: ListRow, b: ListRow) => (b.updated ?? '').localeCompare(a.updated ?? '') || a.app.name.localeCompare(b.app.name), + name: (a: ListRow, b: ListRow) => a.app.name.localeCompare(b.app.name), + }[o.sort]; + return rows.filter(r => !r.app.ignored && inStudio(r) && hit(r)).sort(by); +} + +/** Groups by studio in the studios' order, apps without a studio last. */ +export function groupByStudio(rows: T[], studios: { id: string }[]): { studio: string | null; rows: T[] }[] { + const order = [...studios.map(s => s.id as string | null), null]; + const known = new Set(studios.map(s => s.id)); + return order.map(id => ({ studio: id, rows: rows.filter(r => (id === null ? !r.app.studio || !known.has(r.app.studio) : r.app.studio === id)) })).filter(g => g.rows.length); +} + +/** Per studio: visible apps (not ignored). */ +export function studioCounts(apps: UnifiedApp[]): Record { + const m: Record = {}; + for (const a of apps) if (!a.ignored) m[a.studio ?? ''] = (m[a.studio ?? ''] ?? 0) + 1; + return m; +} diff --git a/apps/desktop/src/lib/notify.ts b/apps/desktop/src/lib/notify.ts new file mode 100644 index 0000000..3be6d31 --- /dev/null +++ b/apps/desktop/src/lib/notify.ts @@ -0,0 +1,41 @@ +// What deserves a desktop notification after a read (Settings > Notifications). Pure: compares the previous read with +// the new one and never fires on a first read (nothing to compare with = no flood). +import type { PortfolioResult } from '../api'; +import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from './model'; + +export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string } + +/** Phase changes of the same version on the same store that the owner waits for: review in / out, approved, rejected, live, halted. */ +export function releaseChanges(prev: PortfolioResult | null | undefined, next: PortfolioResult): ReleaseChange[] { + if (!prev) return []; + const WATCH = new Set(['review', 'approved', 'rejected', 'live', 'halted']); + const out: ReleaseChange[] = []; + for (const a of next.apps) { + const before = prev.apps.find(p => p.project === a.project); + if (!before || before.release.source !== 'live' || a.release.source !== 'live') continue; + for (const r of a.release.all ?? []) { + if (!r.version) continue; + const old = (before.release.all ?? []).find(x => x.store === r.store && x.version === r.version); + if (!old || old.phase === r.phase) continue; + if (WATCH.has(r.phase) || WATCH.has(old.phase)) out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase }); + } + } + return out; +} + +/** New 1-2 star reviews since the previous read. */ +export function newLowReviews(prev: Review[] | null | undefined, next: Review[]): Review[] { + if (!prev) return []; + const seen = new Set(prev.map(r => `${r.store}:${r.id}`)); + return next.filter(r => r.rating <= 2 && !seen.has(`${r.store}:${r.id}`)); +} + +/** Crash or ANR rate that went over the Play bad behavior threshold since the previous read. */ +export function crashCrossed(prev: HealthSnapshot | null | undefined, next: HealthSnapshot): ('crash' | 'anr')[] { + if (!prev?.play || isError(prev.play) || !next.play || isError(next.play)) return []; + const out: ('crash' | 'anr')[] = []; + const was = { crash: healthSeries(prev.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(prev.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) }; + const now = { crash: healthSeries(next.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(next.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) }; + for (const k of ['crash', 'anr'] as const) if (now[k].tone === 'bad' && was[k].tone !== 'bad') out.push(k); + return out; +} diff --git a/apps/desktop/src/nav.ts b/apps/desktop/src/nav.ts index ede44b2..f5fe8d7 100644 --- a/apps/desktop/src/nav.ts +++ b/apps/desktop/src/nav.ts @@ -1,25 +1,30 @@ // Routes: Portfolio -> one App (tabs) plus the workspace screens. Pure, so tests can check the deep links. +// An app is keyed by its project id, or (store-only apps, no folder) by its store target ("store:..."). import { createContext, useContext } from 'react'; import type { Key } from './i18n'; import type { IconName } from './ui/icons'; export const APP_TABS = ['releases', 'catalog', 'listings', 'health', 'reviews', 'testflight', 'checks'] as const; export type AppTab = (typeof APP_TABS)[number]; +/** Tabs of a store-only app: store reads only (catalog, listings and checks need the app folder). */ +export const STORE_TABS: readonly AppTab[] = ['releases', 'health', 'reviews', 'testflight']; +export const tabsFor = (hasFolder: boolean): readonly AppTab[] => (hasFolder ? APP_TABS : STORE_TABS); export const TAB_KEY: Record = { releases: 'tab.releases', catalog: 'tab.catalog', listings: 'tab.listings', health: 'tab.health', reviews: 'tab.reviews', testflight: 'tab.testflight', checks: 'tab.checks' }; export const TAB_ICON: Record = { releases: 'rocket', catalog: 'tag', listings: 'text', health: 'activity', reviews: 'message', testflight: 'plane', checks: 'shield' }; -export const WORKSPACE = ['apps', 'accounts', 'dependencies', 'settings'] as const; +export const WORKSPACE = ['apps', 'accounts', 'ignored', 'dependencies', 'settings'] as const; export type WorkspaceScreen = (typeof WORKSPACE)[number]; -export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen }; +export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen; section?: string }; /** storebound:// deep links and the dev-only start switch ("app:health" = first app, Health tab; - * "app:health:2" = second app). `apps` are the project ids in list order. */ + * "app:health:2" = second app; "settings:refresh" = a Settings section). `apps` are the app keys in list order. */ export function parseStart(v: string, apps: string[]): Route | null { const [screen, tab, n] = v.split(':'); const app = apps[Math.max(0, (Number(n) || 1) - 1)]; if (screen === 'app' && app) return { screen: 'app', appId: app, tab: APP_TABS.includes(tab as AppTab) ? tab as AppTab : 'releases' }; if (screen === 'portfolio') return { screen: 'portfolio' }; - return (WORKSPACE as readonly string[]).includes(screen ?? '') ? { screen: screen as WorkspaceScreen } : null; + if (!(WORKSPACE as readonly string[]).includes(screen ?? '')) return null; + return tab ? { screen: screen as WorkspaceScreen, section: tab } : { screen: screen as WorkspaceScreen }; } export const sameRoute = (a: Route, b: Route): boolean => JSON.stringify(a) === JSON.stringify(b); diff --git a/apps/desktop/src/screens/Accounts.tsx b/apps/desktop/src/screens/Accounts.tsx index 307df75..673e88a 100644 --- a/apps/desktop/src/screens/Accounts.tsx +++ b/apps/desktop/src/screens/Accounts.tsx @@ -1,88 +1,227 @@ -// Store accounts: the keys live in the system keychain; the app keeps a label only and hands a key to storebound in -// memory for one call. -import { useState } from 'react'; -import { type Account, api, errorText } from '../api'; -import { t } from '../i18n'; -import { date } from '../lib/format'; -import { useData } from '../store'; +// Studios & accounts: studios (name, colour, logo) group store accounts; each account is a Google Play service account +// (one JSON key; it can be invited to several Play developer accounts) or an App Store Connect team key (key id, +// issuer id, .p8). Keys live in the system keychain; the app keeps a label and the studio only. Per account: a health +// check (key works / permission missing / revoked, with the fix) and "Import apps" (every app the key can see). +import { type FormEvent, useEffect, useState } from 'react'; +import { type Account, type AccountCheck, api, errorText, STUDIO_COLORS, type Studio, type StudioColor } from '../api'; +import { type Key, t } from '../i18n'; +import { ago } from '../lib/format'; +import { withIgnored } from '../lib/identity'; +import { type AccountHealth, useData } from '../store'; import { Icon, StoreGlyph } from '../ui/icons'; -import { Card, Chip, Empty, Notice } from '../ui/kit'; +import { Card, Chip, Empty, Notice, StudioMark } from '../ui/kit'; +import type { Tone } from '../lib/model'; -export function Accounts() { +const STATUS: Record = { + ok: ['ok', 'acct.ok'], 'no-apps': ['warn', 'acct.noApps'], permission: ['warn', 'acct.permission'], revoked: ['bad', 'acct.revoked'], 'api-disabled': ['warn', 'acct.apiDisabled'], error: ['bad', 'acct.error'], +}; + +export function HealthChip({ h }: { h: AccountHealth | undefined }) { + if (!h) return {t('acct.notTested')}; + if (h.error || !h.check) return {t('acct.error')}; + const [tone, key] = STATUS[h.check.status]; + return {t(key)}; +} + +function Swatches({ value, onChange, name }: { value: StudioColor; onChange: (c: StudioColor) => void; name: string }) { + return ( +
+ {STUDIO_COLORS.map(c => ( + + ))} + {name} +
+ ); +} + +function AccountRow({ a, busy, setBusy, onError }: { a: Account; busy: string | null; setBusy: (b: string | null) => void; onError: (e: string | null) => void }) { + const d = useData(); + const [edit, setEdit] = useState(false); + const [label, setLabel] = useState(a.label); + const [studio, setStudio] = useState(a.studio ?? ''); + const h = d.accountHealth[a.id]; + const list = d.storeApps[a.id]; + const ignored = d.overrides.ignored.includes(`account:${a.id}`); + const used = d.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).length; + const run = async (key: string, fn: () => Promise) => { + setBusy(key); onError(null); + try { await fn(); } catch (e) { onError(errorText(e)); } finally { setBusy(null); } + }; + const save = (e: FormEvent) => { e.preventDefault(); run(`ed-${a.id}`, async () => { await api.updateAccount(a.id, label, studio || null); await d.reload(); setEdit(false); }); }; + const check = h?.check; + return ( +
+
+ +
+
{a.label}{ignored && {t('acct.ignored')}}
+
+ {a.kind === 'play' ? t('acct.kindPlay') : t('acct.kindApple')} + {' · '}{list ? t('acct.appsRead', { count: list.value.apps.length, when: ago(list.at) }) : t('acct.notImported')} + {used ? ` · ${t('acct.folders', { count: used })}` : ''} + {check?.principal ? <> · {check.principal} : null} +
+
+
+ + + + + +
+
+ {edit && ( +
+
setLabel(e.target.value)} maxLength={60} />
+
+
+
+
+ )} + {check && check.status !== 'ok' && check.fix && ( +
+ api.openExternal(check.docs!).catch(e => onError(errorText(e)))}>{t('acct.openFix')} : undefined}> + {check.message}
{check.fix} +
+
+ )} + {h?.error &&
{h.error}
} +
+ ); +} + +function StudioCard({ s, accounts, focus }: { s: Studio | null; accounts: Account[]; focus: boolean }) { + const d = useData(); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(null); + const [edit, setEdit] = useState(false); + const [name, setName] = useState(s?.name ?? ''); + const [color, setColor] = useState(s?.color ?? 'indigo'); + const apps = d.apps.filter(a => !a.ignored && (a.studio ?? null) === (s?.id ?? null)); + const storeOnly = apps.filter(a => !a.project).length; + const act = async (key: string, fn: () => Promise) => { setBusy(key); setError(null); try { await fn(); await d.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(null); } }; + const id = s ? `studio-${s.id}` : 'studio-none'; + useEffect(() => { if (focus) document.getElementById(id)?.scrollIntoView({ block: 'start' }); }, [focus, id]); + return ( +
+
+
+ +
+

{s?.name ?? t('studio.none')}

+
{s ? t('studio.counts', { count: accounts.length, apps: apps.length, store: storeOnly }) : t('studio.noneSub')}
+
+
+ {s && ( +
+ + + {s.logo && } + +
+ )} +
+ {s && edit && ( +
{ e.preventDefault(); act('save', async () => { await api.saveStudio(s.id, name, color); setEdit(false); }); }}> +
setName(e.target.value)} maxLength={48} />
+
{t('studio.color')}
+
+
+ )} + {error &&
{error}
} + {accounts.length ?
{accounts.map(a => )}
+ :

{s ? t('studio.noAccounts') : t('studio.allAssigned')}

} +
+ ); +} + +export function Accounts({ focus }: { focus?: string }) { const d = useData(); const [error, setError] = useState(null); const [busy, setBusy] = useState(null); + const [studioName, setStudioName] = useState(''); + const [studioColor, setStudioColor] = useState('indigo'); const [playLabel, setPlayLabel] = useState(''); + const [playStudio, setPlayStudio] = useState(''); const [appleLabel, setAppleLabel] = useState(''); + const [appleStudio, setAppleStudio] = useState(''); const [keyId, setKeyId] = useState(''); const [issuerId, setIssuerId] = useState(''); - const act = async (key: string, fn: () => Promise) => { + const act = async (key: string, fn: () => Promise, ok?: (r: Account | Studio) => string) => { setBusy(key); setError(null); try { const r = await fn(); - if (r) d.toast({ kind: 'ok', title: t('accounts.saved', { label: r.label }), detail: t('accounts.savedDetail') }); + if (r && ok) d.toast({ kind: 'ok', title: ok(r), detail: 'kind' in r ? t('accounts.savedDetail') : undefined }); await d.reload(); + return r; } catch (e) { setError(errorText(e)); } finally { setBusy(null); } }; - const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel); if (a) setPlayLabel(''); return a; }); - const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }); - const used = (a: Account) => d.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).map(p => p.name); + const addStudio = () => act('studio', async () => { const s = await api.saveStudio(null, studioName, studioColor); setStudioName(''); return s; }, r => t('studio.added', { name: (r as Studio).name })); + const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel, playStudio || null); if (a) setPlayLabel(''); return a; }, r => t('accounts.saved', { label: (r as Account).label })); + const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId, appleStudio || null); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }, r => t('accounts.saved', { label: (r as Account).label })); + const testAll = async () => { setBusy('all'); await Promise.all(d.accounts.map(a => d.checkAccount(a.id))); setBusy(null); }; + const unassigned = d.accounts.filter(a => !a.studio || !d.studios.some(s => s.id === a.studio)); + const studioSelect = (id: string, value: string, set: (v: string) => void) => ( +
+
+ ); return (
-

{t('nav.accounts')}

{t('accounts.lead')}

+
+

{t('nav.accounts')}

{t('accounts.leadStudios')}

+
+ + +
+
{error && {error}} - - {!d.accounts.length ? {t('accounts.emptyText')} : ( - - - - {d.accounts.map(a => ( - - - - - - - - ))} - -
{t('col.name')}{t('col.store')}{t('col.usedBy')}{t('col.added')}{t('col.actions')}
{a.label}{a.kind === 'play' ? 'Google Play' : 'App Store Connect'}{used(a).length ? used(a).join(', ') : {t('accounts.unused')}}{date(a.created)}
- )} -
-
- + {!d.accounts.length && !d.studios.length && {t('accounts.emptyTextStudios')}} + {d.studios.map(s => a.studio === s.id)} focus={focus === s.id} />)} + {(unassigned.length > 0 || !d.studios.length) && d.accounts.length > 0 && } + +
+ +
{ e.preventDefault(); addStudio(); }}> +
setStudioName(e.target.value)} maxLength={48} placeholder={t('studio.namePlaceholder')} autoComplete="off" />
+
{t('studio.color')}
+
+
+
+
{ e.preventDefault(); addPlay(); }}> -
- - setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" /> -
+
+ setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" />
+ {studioSelect('play-studio', playStudio, setPlayStudio)}

{t('accounts.playHow')}

- +
{ e.preventDefault(); addApple(); }}> -
- - setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" /> -
+
+ setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" />
+ {studioSelect('apple-studio', appleStudio, setAppleStudio)}
-
- - setKeyId(e.target.value.toUpperCase())} placeholder="ABC123DEFG" maxLength={10} autoComplete="off" spellCheck={false} /> -
-
- - setIssuerId(e.target.value)} placeholder="UUID" maxLength={36} autoComplete="off" spellCheck={false} /> -
+
+ setKeyId(e.target.value.toUpperCase())} placeholder="ABC123DEFG" maxLength={10} autoComplete="off" spellCheck={false} />
+
+ setIssuerId(e.target.value)} placeholder="UUID" maxLength={36} autoComplete="off" spellCheck={false} />
- {t('accounts.safety')} + {t('accounts.safetyStudios')}
); } diff --git a/apps/desktop/src/screens/AppView.tsx b/apps/desktop/src/screens/AppView.tsx index becee55..c469c48 100644 --- a/apps/desktop/src/screens/AppView.tsx +++ b/apps/desktop/src/screens/AppView.tsx @@ -1,12 +1,15 @@ -// One app across both stores: header (icon, ids, store state), then the tabs. -import { type KeyboardEvent, useRef } from 'react'; -import { api, type Project } from '../api'; -import { t } from '../i18n'; -import { APP_TABS, type AppTab, TAB_ICON, TAB_KEY, useNav } from '../nav'; +// One app across both stores: header (icon, studio, ids, store state, pairing), then the tabs. A store-only app (no +// app folder) shows its store reads (releases, health, reviews, TestFlight) read-only, with "Link a folder" and +// "Start an app folder here" to make it a full app. +import { type KeyboardEvent, useRef, useState } from 'react'; +import { api, errorText } from '../api'; +import { type Key, t } from '../i18n'; +import { pairCandidates, type UnifiedApp, withIgnored, withLink, withPair, withStudio, withUnpair } from '../lib/identity'; import { storeNow } from '../lib/model'; +import { type AppTab, TAB_ICON, TAB_KEY, tabsFor, useNav } from '../nav'; import { useData } from '../store'; import { Icon } from '../ui/icons'; -import { AppIcon, Chip, PhaseChip, StoreBadge } from '../ui/kit'; +import { AppIcon, Chip, Notice, PhaseChip, StoreBadge, StoreOnlyTag, StudioMark } from '../ui/kit'; import { CatalogTab } from './tabs/Catalog'; import { ChecksTab } from './tabs/Checks'; import { HealthTab } from './tabs/Health'; @@ -18,23 +21,88 @@ import { TestFlightTab } from './tabs/TestFlight'; export const ascUrl = (appId: string | null | undefined): string => (appId ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(appId)}/distribution` : 'https://appstoreconnect.apple.com/apps'); export const PLAY_CONSOLE = 'https://play.google.com/console/'; -export function AppView({ project, tab }: { project: Project; tab: AppTab }) { +const PAIRING: Record = { folder: 'pair.folder', manual: 'pair.manual', id: 'pair.id', close: 'pair.close', name: 'pair.name', single: 'pair.single' }; + +/** Pairing, studio and ignore controls of one app. */ +function AppControls({ app }: { app: UnifiedApp }) { const d = useData(); const nav = useNav(); - const e = d.statusOf(project); - const l = d.liveOf(project); - const ios = e?.app?.platforms.ios, android = e?.app?.platforms.android; - const name = e?.app?.name ?? project.name; - const tabs = useRef<(HTMLButtonElement | null)[]>([]); - const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: project.id, tab: x }); + const cands = pairCandidates(app, d.apps); + const canUnpair = !app.project && !!app.ios && !!app.android; + return ( +
+ {t(PAIRING[app.pairing])} + + {cands.length > 0 && ( + + )} + {canUnpair && } + +
+ ); +} + +function StoreOnlyBanner({ app }: { app: UnifiedApp }) { + const d = useData(); + const [busy, setBusy] = useState(false); + const [profile, setProfile] = useState<'app' | 'game' | 'subscription-app'>('app'); + const link = async (init: boolean) => { + setBusy(true); + try { + const p = init ? await api.initProject(profile) : await api.addProject(); + if (p) { + await d.updateOverrides(o => withLink(o, app, p.id)); + await d.reload(); + d.toast({ kind: 'ok', title: t('app.linked', { name: p.name }), detail: init ? t('folders.startedDetail') : undefined }); + } + } catch (e) { d.toast({ kind: 'bad', title: t('app.linkFailed'), detail: errorText(e) }); } finally { setBusy(false); } + }; + return ( + + + + +
}> + {t('app.storeOnlyTitle')} {t('app.storeOnlyText')} + + ); +} + +export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) { + const d = useData(); + const nav = useNav(); + const e = d.statusFor(app); + const l = d.liveFor(app); + const ios = e?.app?.platforms.ios ?? (app.ios ? { bundleId: app.ios.app.bundleId, ascAppId: app.ios.app.id } : null); + const android = e?.app?.platforms.android ?? (app.android ? { packageName: app.android.app.id } : null); + const name = (app.project && e?.app?.name) || app.name; + const tabs = tabsFor(!!app.project); + const tabRefs = useRef<(HTMLButtonElement | null)[]>([]); + const studio = d.studios.find(s => s.id === app.studio) ?? null; + const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: app.key, tab: x }); const onKey = (ev: KeyboardEvent) => { - const i = APP_TABS.indexOf(tab); - const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? APP_TABS.length - 1 : null; + const i = tabs.indexOf(tab); + const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? tabs.length - 1 : null; if (j === null) return; ev.preventDefault(); - const n = (j + APP_TABS.length) % APP_TABS.length; - setTab(APP_TABS[n]!); - tabs.current[n]?.focus(); + const n = (j + tabs.length) % tabs.length; + setTab(tabs[n]!); + tabRefs.current[n]?.focus(); }; const all = l?.release.all ?? []; const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null; @@ -44,15 +112,17 @@ export function AppView({ project, tab }: { project: Project; tab: AppTab }) {
- +

{name}

- {e?.summary?.profile && {t(`profile.${e.summary.profile}` as 'profile.app')}} + {e?.summary?.profile && app.project && {t(`profile.${e.summary.profile}` as 'profile.app')}} + {!app.project && } +
- {iosNow && <>{iosNow.version}} - {androidNow && <>{androidNow.version}} + {iosNow && <>{iosNow.version}} + {androidNow && <>{androidNow.version}}
@@ -61,22 +131,24 @@ export function AppView({ project, tab }: { project: Project; tab: AppTab }) { {android && }
+ + {!app.project && }
- {APP_TABS.map((x, i) => ( - ))}
- {tab === 'releases' && } - {tab === 'catalog' && } - {tab === 'listings' && } - {tab === 'health' && } - {tab === 'reviews' && } - {tab === 'testflight' && } - {tab === 'checks' && } + {tab === 'releases' && } + {tab === 'catalog' && app.project && } + {tab === 'listings' && app.project && } + {tab === 'health' && } + {tab === 'reviews' && } + {tab === 'testflight' && } + {tab === 'checks' && app.project && }
); diff --git a/apps/desktop/src/screens/Ignored.tsx b/apps/desktop/src/screens/Ignored.tsx new file mode 100644 index 0000000..6095165 --- /dev/null +++ b/apps/desktop/src/screens/Ignored.tsx @@ -0,0 +1,66 @@ +// Ignored: apps and whole store accounts left out of the portfolio, the sidebar and store reads. Restore brings them +// back (nothing on the stores changes either way). +import { t } from '../i18n'; +import { withIgnored } from '../lib/identity'; +import { useNav } from '../nav'; +import { useData } from '../store'; +import { Icon, StoreGlyph } from '../ui/icons'; +import { AppIcon, Card, Empty, StoreOnlyTag, StudioMark } from '../ui/kit'; + +export function Ignored() { + const d = useData(); + const nav = useNav(); + const apps = d.apps.filter(a => a.ignored).sort((a, b) => a.name.localeCompare(b.name)); + const accounts = d.accounts.filter(a => d.overrides.ignored.includes(`account:${a.id}`)); + const restoreAll = () => d.updateOverrides(o => ({ ...o, ignored: [] })); + const empty = !apps.length && !accounts.length; + return ( +
+
+

{t('nav.ignored')}

{t('ignored.lead')}

+ {!empty &&
} +
+ {empty ? {t('ignored.emptyText')} : ( + <> + + {apps.length ? ( +
+ {apps.map(a => { + const s = d.studios.find(x => x.id === a.studio) ?? null; + return ( +
+ +
+ {a.name}{!a.project && } + + {s?.name ?? t('studio.none')} + {a.ios && {a.ios.app.bundleId}} + {a.android && {a.android.app.id}} + +
+ +
+ ); + })} +
+ ) :

{t('ignored.noApps')}

} +
+ + {accounts.length ? ( +
+ {accounts.map(a => ( +
+ +
{a.label}{a.kind === 'play' ? t('acct.kindPlay') : t('acct.kindApple')} · {t('ignored.accountApps', { count: d.storeApps[a.id]?.value.apps.length ?? 0 })}
+ +
+ ))} +
+ ) :

{t('ignored.noAccounts')}

} +
+ + )} +

{t('ignored.howTo')}

+
+ ); +} diff --git a/apps/desktop/src/screens/Portfolio.tsx b/apps/desktop/src/screens/Portfolio.tsx index 4b1ed21..0995f14 100644 --- a/apps/desktop/src/screens/Portfolio.tsx +++ b/apps/desktop/src/screens/Portfolio.tsx @@ -1,14 +1,16 @@ -// Portfolio: every app on both stores. KPIs, one row per app (live version and state per store with its place on -// the release track, next version, catalog parity, config check), what needs attention, and the workspace state. -import { useEffect, useState } from 'react'; -import { api, type AppStatus, type Project, type StoreRelease, type ToolResult } from '../api'; +// Portfolio: every app of every studio on both stores. KPIs, a toolbar (search, studio chips with counts, sort, +// grouping), one row per app (live version and state per store with its place on the release track, next version, +// crash rate, catalog parity, config check), grouped by studio; then what needs attention and the workspace state. +import { useEffect, useMemo, useState } from 'react'; +import { api, type AppStatus, type StoreRelease, type ToolResult } from '../api'; import { type Key, t } from '../i18n'; import { ago, pct, share } from '../lib/format'; +import { filterSort, groupByStudio, type ListRow, type SortBy, studioCounts, type UnifiedApp } from '../lib/identity'; import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; import { useNav } from '../nav'; import { useData } from '../store'; import { Icon, StoreGlyph } from '../ui/icons'; -import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Skeleton, Sparkline } from '../ui/kit'; +import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Seg, Skeleton, Sparkline, StudioMark } from '../ui/kit'; /** Tag of one app's offline config check. */ export function checkState(e: Pick | undefined): { text: string; tone: Tone } { @@ -29,9 +31,8 @@ export function Pips({ r, store }: { r: StoreRelease | null; store: 'ios' | 'and ); } -function StoreCell({ e, store, project }: { e: AppStatus | undefined; store: 'ios' | 'android'; project: AppStatus | undefined }) { - const on = store === 'ios' ? project?.app?.platforms.ios : project?.app?.platforms.android; - if (project && !on) return {t('app.notOnStore')}; +function StoreCell({ e, store, on }: { e: AppStatus | undefined; store: 'ios' | 'android'; on: boolean }) { + if (!on) return {t('app.notOnStore')}; if (!e) return {t('common.unknown')}; const err = e.storeErrors[store]; if (err) return {t('portfolio.unreadable')}; @@ -64,18 +65,19 @@ function NextCell({ e }: { e: AppStatus | undefined }) { } /** Last cached health read of every app (the Health tab reads it; the portfolio only shows what is saved). */ -function useCachedHealth(projects: Project[]): Record { +function useCachedHealth(targets: string[]): Record { const [m, set] = useState>({}); - const key = projects.map(p => p.id).join(); + const key = targets.join(); useEffect(() => { - for (const p of projects) { - api.cached('health', p.id).then(c => set(x => ({ ...x, [p.id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {}); + for (const id of targets) { + api.cached('health', id).then(c => set(x => ({ ...x, [id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {}); } }, [key]); // eslint-disable-line react-hooks/exhaustive-deps return m; } -function HealthCell({ c }: { c: { h: HealthSnapshot; at: string } | null | undefined }) { +function HealthCell({ c, android }: { c: { h: HealthSnapshot; at: string } | null | undefined; android: boolean }) { + if (!android) return {t('portfolio.healthNoPlay')}; if (!c) return {t('portfolio.healthNotRead')}; const play = c.h.play; if (!play) return {t('portfolio.healthNoPlay')}; @@ -105,44 +107,110 @@ function AttentionList({ items }: { items: Attention[] }) { ); } +/** Newest store activity of an app (release record date), else when its folder was added. */ +function updatedAt(a: UnifiedApp, l: AppStatus | undefined): string | null { + const dates = (l?.release.all ?? []).map(r => r.date).filter((x): x is string => !!x); + return dates.sort().at(-1) ?? a.project?.added ?? null; +} + +const VIEW_KEY = 'storebound.portfolio.v1'; +interface View { studio: string; sort: SortBy; group: boolean } +function loadView(): View { + try { + const v = JSON.parse(localStorage.getItem(VIEW_KEY) ?? '{}') as Partial; + return { studio: typeof v.studio === 'string' ? v.studio : 'all', sort: v.sort === 'recent' || v.sort === 'name' ? v.sort : 'attention', group: v.group !== false }; + } catch { return { studio: 'all', sort: 'attention', group: true }; } +} + export function Portfolio() { const d = useData(); const nav = useNav(); - const open = (p: Project) => nav.go({ screen: 'app', appId: p.id, tab: 'releases' }); + const [view, setViewState] = useState(loadView); + const [query, setQuery] = useState(''); + const setView = (v: Partial) => setViewState(x => { const n = { ...x, ...v }; try { localStorage.setItem(VIEW_KEY, JSON.stringify(n)); } catch { /* private mode */ } return n; }); + const visible = useMemo(() => d.apps.filter(a => !a.ignored), [d.apps]); + const health = useCachedHealth(visible.map(a => a.target)); + const open = (a: UnifiedApp) => nav.go({ screen: 'app', appId: a.key, tab: 'releases' }); - if (d.ready && !d.projects.length) { + const all = useMemo(() => visible.map(app => { + const e = d.statusFor(app), l = d.liveFor(app); + const att = attention(app.key, app.name, e, l, health[app.target]?.h); + return { app, e, l, att, attention: att.length, blockers: att.filter(x => x.tone === 'bad').length, updated: updatedAt(app, l) }; + }), [visible, d, health]); + const counts = useMemo(() => studioCounts(visible), [visible]); + const studioOk = view.studio === 'all' || view.studio === 'none' || d.studios.some(s => s.id === view.studio); + const rows = filterSort(all as (ListRow & typeof all[number])[], { studio: studioOk ? view.studio : 'all', query, sort: view.sort }) as typeof all; + const grouped = view.group && d.studios.length ? groupByStudio(rows, d.studios) : [{ studio: undefined as string | null | undefined, rows }]; + + if (d.ready && !visible.length) { return (

{t('nav.portfolio')}

{t('portfolio.lead')}

- - + + + }>{t('portfolio.emptyText')}
); } - const health = useCachedHealth(d.projects); - const rows = d.projects.map(p => ({ p, e: d.statusOf(p), l: d.liveOf(p) })); - const lives = rows.map(r => r.l).filter((x): x is AppStatus => !!x); - const all = lives.flatMap(l => l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x)); - const stores = rows.reduce((n, r) => n + (r.e?.app?.platforms.ios ? 1 : 0) + (r.e?.app?.platforms.android ? 1 : 0), 0); - const liveCount = lives.reduce((n, l) => n + (l.release.current?.ios ? 1 : 0) + (l.release.current?.android ? 1 : 0), 0); - const rolling = all.filter(r => r.phase === 'rollout'); - const review = all.filter(r => r.phase === 'review'); - const att = rows.flatMap(r => attention(r.p.id, r.e?.app?.name ?? r.p.name, r.e, r.l, health[r.p.id]?.h)); + const shown = rows.map(r => r.l).filter((x): x is AppStatus => !!x); + const releases = shown.flatMap(l => l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x)); + const stores = rows.reduce((n, r) => n + (r.app.ios || r.e?.app?.platforms.ios ? 1 : 0) + (r.app.android || r.e?.app?.platforms.android ? 1 : 0), 0); + const liveCount = shown.reduce((n, l) => n + (l.release.current?.ios ? 1 : 0) + (l.release.current?.android ? 1 : 0), 0); + const rolling = releases.filter(r => r.phase === 'rollout'); + const review = releases.filter(r => r.phase === 'review'); + const att = rows.flatMap(r => r.att); const blockers = att.filter(a => a.tone === 'bad').length; - const known = lives.length > 0; - const iosApps = rows.filter(r => r.e?.app?.platforms.ios).length, androidApps = rows.filter(r => r.e?.app?.platforms.android).length; + const known = shown.length > 0; + const iosApps = rows.filter(r => r.app.ios || r.e?.app?.platforms.ios).length, androidApps = rows.filter(r => r.app.android || r.e?.app?.platforms.android).length; + const storeOnly = rows.filter(r => !r.app.project).length; + const neverImported = d.accounts.filter(a => !d.storeApps[a.id]).length; + + const row = (r: typeof all[number]) => { + const { app, e, l } = r; + const st = app.project ? checkState(e) : null; + const cat = l?.catalog ?? e?.catalog; + const ios = !!(app.ios || e?.app?.platforms.ios), android = !!(app.android || e?.app?.platforms.android); + const sub = app.ios?.app.bundleId ?? e?.app?.platforms.ios?.bundleId ?? app.android?.app.id ?? e?.app?.platforms.android?.packageName ?? ''; + return ( + open(app)}> + +
+ +
+ +
{sub}{!app.project && {t('apps.storeOnly')}}
+
+
+ + {e || !app.project ? : } + {e || !app.project ? : } + + + + {!app.project ? {t('portfolio.noConfig')} : cat ? ( +
+ {t('portfolio.products', { count: cat.products })} · {t('portfolio.subs', { count: cat.subscriptions })} + {cat.checked === 'live' ? (cat.ok ? {t('portfolio.inParity')} : {t('portfolio.differs', { count: cat.missingIos.length + cat.missingAndroid.length + cat.onlyIos.length + cat.onlyAndroid.length })}) + : {t('portfolio.configOnly')}} +
+ ) : –} + + {st ? {st.text} : –} + + ); + }; return (
-

{t('nav.portfolio')}

{t('portfolio.sub', { count: d.projects.length, stores })}

+

{t('nav.portfolio')}

{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}

- + @@ -150,67 +218,66 @@ export function Portfolio() {
{d.portfolioError && {d.portfolioError}} + {neverImported > 0 && d.importApps()} disabled={d.importBusy}>{t('action.importApps')}}>{t('portfolio.notImported', { count: neverImported })}} {!known && d.ready && d.refreshPortfolio(true)}>{t('action.readStores')}}>{t('portfolio.notReadNotice')}}
- + r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} /> `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} />
+
+
setQuery(e.target.value)} placeholder={t('portfolio.search')} aria-label={t('portfolio.search')} />
+
+ + {d.studios.map(s => ( + + ))} + {d.studios.length > 0 && (counts[''] ?? 0) > 0 && } +
+ + setView({ sort })} label={t('portfolio.sort')} options={[['attention', t('portfolio.sortAttention'), 'alert'], ['recent', t('portfolio.sortRecent'), 'clock'], ['name', t('portfolio.sortName')]]} /> + {d.studios.length > 0 && } +
+ {t('legend.done')}{t('legend.stages')}
}> -
- - - - - - {rows.map(({ p, e, l }) => { - const st = checkState(e); - const cat = l?.catalog ?? e?.catalog; + {rows.length ? ( +
+
{t('col.app')}App StoreGoogle Play{t('col.next')}{t('col.crash')}{t('col.catalog')}{t('col.config')}
+ + + + {grouped.map(g => { + const s = g.studio === undefined ? undefined : d.studios.find(x => x.id === g.studio) ?? null; return ( - open(p)}> - - - - - - - - + + {s !== undefined && ( + + )} + {g.rows.map(row)} + ); })} - -
{t('col.app')}App StoreGoogle Play{t('col.next')}{t('col.crash')}{t('col.catalog')}{t('col.config')}
-
- -
- -
{e?.app?.platforms.ios?.bundleId ?? e?.app?.platforms.android?.packageName ?? ''}
-
-
-
{e ? : }{e ? : } - {cat ? ( -
- {t('portfolio.products', { count: cat.products })} · {t('portfolio.subs', { count: cat.subscriptions })} - {cat.checked === 'live' ? (cat.ok ? {t('portfolio.inParity')} : {t('portfolio.differs', { count: cat.missingIos.length + cat.missingAndroid.length + cat.onlyIos.length + cat.onlyAndroid.length })}) - : {t('portfolio.configOnly')}} -
- ) : –} -
{st.text}
+ {s?.name ?? t('studio.none')}{t('portfolio.groupCount', { count: g.rows.length })} · {t('portfolio.groupAccounts', { count: d.accounts.filter(a => (a.studio ?? null) === (g.studio ?? null)).length })} +
-
+ +
+ ) : {t('portfolio.noMatchText')}}
- + (a.tone === 'bad' ? 0 : 1) - (b.tone === 'bad' ? 0 : 1))} />
+
{t('nav.studios')}
{d.studios.length ? t('portfolio.studiosN', { count: d.studios.length }) : }
{t('nav.accounts')}
{d.accounts.length ? t('portfolio.accounts', { play: d.accounts.filter(a => a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length }) : }
+
{t('portfolio.folders')}
{t('portfolio.foldersN', { count: d.projects.length, store: storeOnly })}
+
{t('nav.ignored')}
{d.apps.filter(a => a.ignored).length ? : t('kpi.none')}
{t('portfolio.storesRead')}
{d.live ? ago(d.live.at) : t('time.never')}
-
{t('portfolio.tools')}
{d.sidecar?.tools ? t('portfolio.toolsFound', { found: d.sidecar.tools.tools.filter(x => x.found).length, total: d.sidecar.tools.tools.length }) : '–'}
CLI
{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? '–'}
diff --git a/apps/desktop/src/screens/Settings.tsx b/apps/desktop/src/screens/Settings.tsx index 35087e3..8f13196 100644 --- a/apps/desktop/src/screens/Settings.tsx +++ b/apps/desktop/src/screens/Settings.tsx @@ -1,65 +1,241 @@ -import { useState } from 'react'; -import { api, errorText } from '../api'; -import { t } from '../i18n'; +// Settings, every part of the app in one place: studios and accounts, app pairing and the ignore list, store reads +// (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. +import { useEffect, useState } from 'react'; +import { api, type CacheInfo, errorText, type Settings as S } from '../api'; +import { type Key, t } from '../i18n'; +import { ago, bytes, date, num } from '../lib/format'; +import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/identity'; import { useNav } from '../nav'; import { usePrefs } from '../prefs-ctx'; import { useData } from '../store'; -import { Icon } from '../ui/icons'; -import { Card, Kbd, MOD, Notice, Seg } from '../ui/kit'; +import { Icon, type IconName, StoreGlyph } from '../ui/icons'; +import { AppIcon, Card, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit'; -export function Settings({ onTheme: _onTheme }: { onTheme: () => void }) { +export const SECTIONS: [string, IconName, Key][] = [ + ['studios', 'building', 'set.studios'], ['pairing', 'link', 'set.pairing'], ['refresh', 'refresh', 'set.refresh'], ['cache', 'database', 'set.cache'], + ['appearance', 'sun', 'settings.appearance'], ['notifications', 'bell', 'set.notifications'], ['dependencies', 'package', 'nav.dependencies'], ['cli', 'terminal', 'set.cli'], + ['privacy', 'shield', 'set.privacy'], ['shortcuts', 'keyboard', 'settings.shortcuts'], ['updates', 'download', 'set.updates'], ['reset', 'rotate', 'set.reset'], +]; + +function Toggle({ id, label, hint, checked, onChange }: { id: string; label: string; hint?: string; checked: boolean; onChange: (v: boolean) => void }) { + return ( + + ); +} + +function PairRow({ app, all }: { app: UnifiedApp; all: UnifiedApp[] }) { + const d = useData(); + const cands = pairCandidates(app, all); + const r = (app.ios ?? app.android)!; + return ( + +
{app.name}
{r.app.bundleId}
+ {app.ios && app.android ? {t(`pair.${app.pairing}` as Key)} + : {t('pair.single')}} + + {app.ios && app.android ? + : cands.length ? ( + + ) : {t('set.noCandidates')}} + + + ); +} + +export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; section?: string }) { const d = useData(); const nav = useNav(); const { prefs, update } = usePrefs(); const [error, setError] = useState(null); + const [cache, setCache] = useState(null); + const [active, setActive] = useState(section ?? 'studios'); + const s = d.settings; const tools = d.sidecar?.tools; - const clear = () => api.clearCache().then(() => d.toast({ kind: 'ok', title: t('settings.cacheCleared') }), e => setError(errorText(e))); + const set = (patch: (x: S) => S) => d.updateSettings(patch(s)); + const loadCache = () => api.cacheInfo().then(setCache, () => {}); + useEffect(() => { loadCache(); }, []); + useEffect(() => { if (section) { setActive(section); document.getElementById(`set-${section}`)?.scrollIntoView({ block: 'start' }); } }, [section]); + const jump = (id: string) => { setActive(id); document.getElementById(`set-${id}`)?.scrollIntoView({ block: 'start', behavior: prefs.motion === 'reduce' ? 'auto' : 'smooth' }); }; + const clear = () => api.clearCache().then(() => { d.toast({ kind: 'ok', title: t('settings.cacheCleared') }); loadCache(); }, e => setError(errorText(e))); + const reset = async () => { + try { + if (await api.reset()) { + try { localStorage.clear(); } catch { /* private mode */ } + await d.reload(); + d.toast({ kind: 'ok', title: t('set.resetDone') }); + nav.openWelcome(); + } + } catch (e) { setError(errorText(e)); } + }; + const storeOnly = d.apps.filter(a => !a.project && !a.ignored); + const paired = storeOnly.filter(a => a.ios && a.android); + const singles = storeOnly.filter(a => !(a.ios && a.android)); return (
-

{t('nav.settings')}

{t('settings.lead')}

+

{t('nav.settings')}

{t('set.lead')}

{error && {error}} -
- -
-
{t('settings.theme')} - update({ ...prefs, theme })} label={t('settings.theme')} options={[['system', t('settings.system'), 'settings'], ['light', t('settings.light'), 'sun'], ['dark', t('settings.dark'), 'moon']]} />
-
{t('settings.motion')} - update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} />
-
{t('settings.language')} - update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} />
-
-
- -
-
{t('settings.scPalette')}
-
{t('nav.portfolio')}
-
{t('settings.scWorkspace')}
–
-
{t('settings.scTabs')}
-
{t('settings.scTabArrows')}
-
{t('settings.scClose')}
-
-
- -
-

{t('settings.dataText')}

-
- - +
+ +
+ nav.go({ screen: 'accounts' })}>{t('set.manage')}}> + {d.studios.length ? ( +
+ {d.studios.map(st => { + const accts = d.accounts.filter(a => a.studio === st.id); + return ( + + ); + })} +
+ ) :

{t('set.noStudios')}

} +
+ + + {storeOnly.length ? ( + + + {[...paired, ...singles].map(a => )} +
{t('col.app')}{t('set.pairedHow')}{t('col.actions')}
+ ) :

{t('set.noStoreOnly')}

} +
{t('set.ignoredLine', { count: d.apps.filter(a => a.ignored).length, accounts: d.overrides.ignored.filter(i => i.startsWith('account:')).length })} +
+
+ + +
+
{t('set.autoRefresh')} + set(x => ({ ...x, refresh: { ...x.refresh, autoMinutes: Number(v) as S['refresh']['autoMinutes'] } }))} + options={[['0', t('set.off')], ['15', t('set.min', { n: 15 })], ['30', t('set.min', { n: 30 })], ['60', t('set.hour', { n: 1 })], ['180', t('set.hour', { n: 3 })], ['720', t('set.hour', { n: 12 })]]} /> + {t('set.autoHint')}
+ set(x => ({ ...x, refresh: { ...x.refresh, onLaunch: v } }))} /> + set(x => ({ ...x, refresh: { ...x.refresh, icons: v } }))} /> +
+ {t('set.parallelHint')}
+
+ + + {d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')} +
-
- - -
-
{t('settings.app')}
{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''}` : '–'}
-
CLI
{d.sidecar ? `storebound ${d.sidecar.version} · ${d.sidecar.protocol} · ${t('settings.methods', { count: d.sidecar.methods.length })}` : d.sidecarError ?? t('foot.cliStarting')}
-
{t('settings.tools')}
{tools ? t('portfolio.toolsFound', { found: tools.tools.filter(x => x.found).length, total: tools.tools.length }) : '–'}
-
{t('settings.telemetry')}
{t('settings.telemetryNone')}
-
-
- -
-
+ + + +
+
+
{t('set.cacheSize')}
{cache ? `${bytes(cache.file_bytes)} · ${t('set.cacheRows', { count: cache.rows })}` : '–'}
+
{t('set.cacheOldest')}
{cache?.oldest ? `${date(cache.oldest)} (${ago(cache.oldest)})` : '–'}
+
+
{t('set.keep')} + set(x => ({ ...x, cache: { keepDays: Number(v) as S['cache']['keepDays'] } })).then(loadCache)} + options={[['7', t('set.days', { n: 7 })], ['30', t('set.days', { n: 30 })], ['90', t('set.days', { n: 90 })], ['365', t('set.year')], ['0', t('set.always')]]} />
+
+

{t('settings.dataText')}

+
+
+ + +
+
{t('settings.language')} + update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} />
+
{t('settings.theme')} + update({ ...prefs, theme })} label={t('settings.theme')} options={[['system', t('settings.system'), 'settings'], ['light', t('settings.light'), 'sun'], ['dark', t('settings.dark'), 'moon']]} />
+
{t('settings.motion')} + update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} />
+
+
+ + +
+ set(x => ({ ...x, notify: { ...x.notify, reviewState: v } }))} /> + set(x => ({ ...x, notify: { ...x.notify, lowReviews: v } }))} /> + set(x => ({ ...x, notify: { ...x.notify, crash: v } }))} /> +
+
+
+ + nav.go({ screen: 'dependencies' })}>{t('set.manage')}}> + {tools ? ( +
+ {tools.tools.map(x => {x.name}{x.version ? {x.version} : null}{x.source === 'app' && {t('set.appCopy')}})} +
+ ) :

–

} +

{t('set.depsText')}

+
+ + +
+
{t('settings.app')}
{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''} · ${d.info.platform}` : '–'}
+
CLI
{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? t('foot.cliStarting')}
+
{t('set.protocol')}
{d.sidecar ? `${d.sidecar.protocol} · ${t('settings.methods', { count: d.sidecar.methods.length })}` : '–'}
+
{t('set.state')}
{d.sidecar?.running ? t('set.running') : d.sidecarError ? t('foot.cliDown') : t('foot.cliStarting')}
+
{t('set.writes')}
{t('set.writesText')}
+
+
+ + +
    +
  • {t('set.p1')}
  • +
  • {t('set.p2')}
  • +
  • {t('set.p3')}
  • +
  • {t('set.p4')}
  • +
+
+ + +
+
+ + +
+
{t('settings.scPalette')}
+
{t('nav.portfolio')}
+
{t('settings.scWorkspace')}
–
+
{t('settings.scTabs')}
+
{t('settings.scTabArrows')}
+
{t('settings.scClose')}
+
{t('set.scQuit')}
+
+
+ + +
+
{t('set.channel')} + set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} />
+

{t('set.updatesText')}

+
+
+ + +
+

{t('set.resetText', { accounts: d.accounts.length, studios: d.studios.length, folders: d.projects.length })}

+
+ + +
+
+
+

{t('set.footer', { n: num(d.apps.length) })}

+
); diff --git a/apps/desktop/src/screens/tabs/Health.tsx b/apps/desktop/src/screens/tabs/Health.tsx index 4f07064..4f4c900 100644 --- a/apps/desktop/src/screens/tabs/Health.tsx +++ b/apps/desktop/src/screens/tabs/Health.tsx @@ -1,6 +1,6 @@ // Health: Google Play vitals (user-perceived crash and ANR rate per day against the bad behavior thresholds, worst // devices, top issues) and App Store diagnostics (power and performance metrics, signatures, TestFlight crashes). -import type { Project } from '../../api'; +import type { UnifiedApp } from '../../lib/identity'; import { t } from '../../i18n'; import { ago, date, num, pct } from '../../lib/format'; import { type AppleHealth, healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type PlayHealth, type Series } from '../../lib/model'; @@ -122,8 +122,8 @@ function Apple({ h }: { h: AppleHealth }) { ); } -export function HealthTab({ project }: { project: Project }) { - const r = useRead(project.id, 'health', { network: true, title: t('tab.health') }); +export function HealthTab({ app }: { app: UnifiedApp }) { + const r = useRead(app.target, 'health', { network: true, title: t('tab.health'), appName: app.name }); const refresh = ; if (!r.data) { if (r.loading && !r.error) return ; diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index 8ddb316..8a75b19 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -1,6 +1,7 @@ // Releases: the release timeline (one version on both stores on one track: build -> testing -> review -> live -> // rollout %), then every version read from the stores. Submit and release stay in the consoles. -import { api, type Project, type ReleaseTrain } from '../../api'; +import { api, type ReleaseTrain } from '../../api'; +import type { UnifiedApp } from '../../lib/identity'; import { type Key, t } from '../../i18n'; import { ago, date, share } from '../../lib/format'; import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model'; @@ -60,10 +61,11 @@ function Train({ title, train, tf, tone }: { title: string; train: ReleaseTrain; ); } -export function ReleasesTab({ project }: { project: Project }) { +export function ReleasesTab({ app }: { app: UnifiedApp }) { const d = useData(); - const l = d.liveOf(project); - const tf = useRead(project.id, 'apple.testflight_status', { network: true, title: 'TestFlight' }); + const l = d.liveFor(app); + const project = app.project; + const tf = useRead(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight', skip: !app.ios && !d.statusFor(app)?.app?.platforms.ios }); const open = (url: string) => { api.openExternal(url).catch(() => {}); }; if (!l) { @@ -71,7 +73,7 @@ export function ReleasesTab({ project }: { project: Project }) { - {!project.playAccount && !project.appleAccount && {t('releases.noAccounts')}} + {project && !project.playAccount && !project.appleAccount && {t('releases.noAccounts')}} }>{t('releases.notReadText')} ); diff --git a/apps/desktop/src/screens/tabs/Reviews.tsx b/apps/desktop/src/screens/tabs/Reviews.tsx index 964786f..d3c2ba1 100644 --- a/apps/desktop/src/screens/tabs/Reviews.tsx +++ b/apps/desktop/src/screens/tabs/Reviews.tsx @@ -2,7 +2,8 @@ // (.storebound/replies) with the send checks. Approving a draft is a local, confirmed write; sending stays in the // terminal (`storebound reviews send`): replies are public. import { useMemo, useState } from 'react'; -import { api, type DraftsResult, errorText, newJob, type Project, type ReplyDraft } from '../../api'; +import { api, type DraftsResult, errorText, newJob, type ReplyDraft } from '../../api'; +import type { UnifiedApp } from '../../lib/identity'; import { t } from '../../i18n'; import { ago, date, num } from '../../lib/format'; import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model'; @@ -56,10 +57,11 @@ function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft | ); } -export function ReviewsTab({ project }: { project: Project }) { +export function ReviewsTab({ app }: { app: UnifiedApp }) { const d = useData(); - const list = useRead(project.id, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews') }); - const drafts = useRead(project.id, 'reviews.drafts', { network: false }); + const project = app.project; + const list = useRead(app.target, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews'), appName: app.name }); + const drafts = useRead(app.target, 'reviews.drafts', { network: false, skip: !project }); const [f, setF] = useState({ store: 'all', stars: [], unanswered: false, query: '' }); const [sel, setSel] = useState(null); const [busy, setBusy] = useState(false); @@ -74,6 +76,7 @@ export function ReviewsTab({ project }: { project: Project }) { setBusy(true); const job = newJob(method); try { + if (!project) return; const o = await api.writeWithConfirm(method, project.id, args, job); if (o.confirmed && o.result?.ok) { d.toast({ kind: 'ok', title, detail: undefined }); await drafts.refresh(); } else if (o.stage === 'dry-run') d.toast({ kind: 'bad', title: t('write.dryFailed'), detail: o.dryRun.output.split('\n').filter(Boolean).at(-1) }); diff --git a/apps/desktop/src/screens/tabs/TestFlight.tsx b/apps/desktop/src/screens/tabs/TestFlight.tsx index a9376fd..fa7191e 100644 --- a/apps/desktop/src/screens/tabs/TestFlight.tsx +++ b/apps/desktop/src/screens/tabs/TestFlight.tsx @@ -1,6 +1,6 @@ // TestFlight: beta groups (internal / external, testers, builds, public link) and the recent builds with their // processing and beta review states. -import type { Project } from '../../api'; +import type { UnifiedApp } from '../../lib/identity'; import { t } from '../../i18n'; import { ago, date, num } from '../../lib/format'; import type { TestFlightStatus, Tone } from '../../lib/model'; @@ -23,11 +23,11 @@ function State({ s }: { s: string | null }) { return s ? {b.text} : –; } -export function TestFlightTab({ project }: { project: Project }) { +export function TestFlightTab({ app }: { app: UnifiedApp }) { const d = useData(); - const e = d.statusOf(project); - const r = useRead(project.id, 'apple.testflight_status', { network: true, title: 'TestFlight' }); - if (e && !e.app?.platforms.ios) return {t('tf.noIosText')}; + const e = d.statusFor(app); + const r = useRead(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight' }); + if ((e && !e.app?.platforms.ios) || (!e && !app.project && !app.ios)) return {t('tf.noIosText')}; if (!r.data) { if (r.loading && !r.error) return ; return ( diff --git a/apps/desktop/src/store.tsx b/apps/desktop/src/store.tsx index 6dcfb68..2b74ae3 100644 --- a/apps/desktop/src/store.tsx +++ b/apps/desktop/src/store.tsx @@ -1,11 +1,15 @@ -// App data shared by every screen: app folders, accounts, the sidecar, the portfolio (offline check + the last live -// read from the cache), app icons, and background jobs shown as toasts with progress and cancel. +// App data shared by every screen: app folders, studios, store accounts and the apps they see, the pairing / ignore +// overrides, settings, the sidecar, the portfolio (offline check + the last live read from the cache), app icons, and +// background jobs shown as toasts with progress and cancel. import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { - type Account, api, type AppInfo, type AppStatus, type CacheEntry, errorText, newJob, onDownload, onProgress, type PortfolioResult, type Project, reads, - type SidecarStatus, type ToolResult, + type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload, + onProgress, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult, } from './api'; import { t } from './i18n'; +import { buildApps, NO_OVERRIDES, type Overrides, type UnifiedApp } from './lib/identity'; +import { isError, type HealthSnapshot, type Review } from './lib/model'; +import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify'; export type ToastKind = 'job' | 'ok' | 'bad' | 'info'; export interface Toast { @@ -19,11 +23,22 @@ export interface Toast { job?: string; } +export interface AccountHealth { check?: AccountCheck; error?: string; at: string } + export interface Data { ready: boolean; info: AppInfo | null; projects: Project[]; accounts: Account[]; + studios: Studio[]; + overrides: Overrides; + settings: Settings; + /** Last app list read of each account (null: never read). */ + storeApps: Record | null>; + /** Last account check of this session. */ + accountHealth: Record; + /** Every app across studios and accounts, ignored ones included (`ignored: true`). */ + apps: UnifiedApp[]; sidecar: SidecarStatus | null; sidecarError: string | null; /** Latest portfolio read (offline check, or live when just read). */ @@ -32,11 +47,21 @@ export interface Data { live: CacheEntry | null; portfolioBusy: 'offline' | 'live' | null; portfolioError: string | null; + importBusy: boolean; icons: Record; refreshPortfolio: (live?: boolean) => Promise; + /** Reads the apps of one account (or all) from the stores. */ + importApps: (account?: string) => Promise; + checkAccount: (id: string) => Promise; reload: () => Promise; + updateOverrides: (fn: (o: Overrides) => Overrides) => Promise; + updateSettings: (s: Settings) => Promise; statusOf: (p: Project) => AppStatus | undefined; liveOf: (p: Project) => AppStatus | undefined; + statusFor: (a: UnifiedApp) => AppStatus | undefined; + liveFor: (a: UnifiedApp) => AppStatus | undefined; + iconFor: (a: UnifiedApp) => string | null; + appByKey: (key: string) => UnifiedApp | undefined; toasts: Toast[]; toast: (t: Omit & { id?: string }) => string; updateToast: (id: string, patch: Partial) => void; @@ -58,15 +83,25 @@ export function DataProvider({ children }: { children: ReactNode }) { const [info, setInfo] = useState(null); const [projects, setProjects] = useState([]); const [accounts, setAccounts] = useState([]); + const [studios, setStudios] = useState([]); + const [overrides, setOverrides] = useState(NO_OVERRIDES); + const [settings, setSettings] = useState(DEFAULT_SETTINGS); + const [storeApps, setStoreApps] = useState | null>>({}); + const [accountHealth, setAccountHealth] = useState>({}); const [sidecar, setSidecar] = useState(null); const [sidecarError, setSidecarError] = useState(null); const [portfolio, setPortfolio] = useState(null); const [live, setLive] = useState | null>(null); const [portfolioBusy, setBusy] = useState(null); const [portfolioError, setPortfolioError] = useState(null); + const [importBusy, setImportBusy] = useState(false); const [icons, setIcons] = useState>({}); const [toasts, setToasts] = useState([]); const timers = useRef(new Map>()); + const liveRef = useRef(live); + liveRef.current = live; + const settingsRef = useRef(settings); + settingsRef.current = settings; const dismiss = useCallback((id: string) => { setToasts(ts => ts.filter(x => x.id !== id)); @@ -92,20 +127,36 @@ export function DataProvider({ children }: { children: ReactNode }) { const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []); const reload = useCallback(async () => { - const [p, a] = await Promise.all([api.projects(), api.accounts()]); + const [p, a, w, s] = await Promise.all([api.projects(), api.accounts(), api.workspace(), api.storeAppsCached()]); setProjects(p); setAccounts(a); + setStudios(w.studios); + setOverrides(w.overrides); + setSettings(w.settings); + setStoreApps(Object.fromEntries(s.map(x => [x.account, x.entry]))); }, []); + const apps = useMemo(() => buildApps({ + projects, accounts, overrides, + summaryOf: p => portfolio?.apps.find(a => a.project === p.path)?.summary ?? liveRef.current?.value.apps.find(a => a.project === p.path)?.summary, + storeApps: Object.entries(storeApps).filter(([, e]) => !!e).map(([account, e]) => ({ account, apps: e!.value.apps })), + }), [projects, accounts, overrides, portfolio, storeApps]); + const appsRef = useRef(apps); + appsRef.current = apps; + const refreshPortfolio = useCallback(async (liveRead = false) => { const job = newJob(liveRead ? 'portfolio-live' : 'portfolio'); setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null); const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; try { - const r = await api.portfolio(liveRead, job); + const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : []; + const r = await api.portfolio(liveRead, job, stores); setPortfolio(r); if (liveRead) { + const changes = releaseChanges(liveRef.current?.value, r); setLive({ value: r, at: r.at }); + if (settingsRef.current.notify.reviewState) for (const c of changes.slice(0, 5)) + api.notify(t('notify.releaseTitle', { name: c.name }), t('notify.releaseBody', { store: c.store === 'ios' ? 'App Store' : 'Google Play', version: c.version, phase: t(`phase.${c.to}` as 'phase.live') })).catch(() => {}); const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length; if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined } : { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined }); @@ -117,7 +168,54 @@ export function DataProvider({ children }: { children: ReactNode }) { } finally { setBusy(null); } }, [toast, updateToast]); - // start: app info, folders, accounts, sidecar, cached live portfolio + const importApps = useCallback(async (account?: string) => { + const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`)); + if (!ids.length) return; + const job = newJob('import'); + setImportBusy(true); + const tid = toast({ id: job, kind: 'job', title: t('toast.importing'), detail: t('toast.importingDetail'), progress: { done: 0, total: ids.length }, job }); + let ok = 0, apps = 0; + const errors: string[] = []; + for (const [n, id] of ids.entries()) { + try { + const e = await api.refreshStoreApps(id, job); + setStoreApps(m => ({ ...m, [id]: e })); + ok++; apps += e.value.apps.length; + } catch (e) { + const msg = errorText(e); + if (/cancel/i.test(msg)) { updateToast(tid, { kind: 'info', title: t('toast.cancelled'), detail: undefined, progress: undefined, job: undefined }); setImportBusy(false); return; } + errors.push(`${accounts.find(a => a.id === id)?.label ?? id}: ${msg}`); + } + updateToast(tid, { progress: { done: n + 1, total: ids.length } }); + } + setImportBusy(false); + updateToast(tid, errors.length ? { kind: ok ? 'info' : 'bad', title: t('toast.importPartial', { count: errors.length }), detail: errors[0], progress: undefined, job: undefined } + : { kind: 'ok', title: t('toast.importDone', { count: apps }), detail: t('toast.importDoneDetail', { count: ok }), progress: undefined, job: undefined }); + }, [accounts, overrides.ignored, toast, updateToast]); + + const checkAccount = useCallback(async (id: string) => { + try { + const check = await api.checkAccount(id, newJob('check')); + setAccountHealth(m => ({ ...m, [id]: { check, at: new Date().toISOString() } })); + } catch (e) { setAccountHealth(m => ({ ...m, [id]: { error: errorText(e), at: new Date().toISOString() } })); } + }, []); + + const updateOverrides = useCallback(async (fn: (o: Overrides) => Overrides) => { + const next = fn(overrides); + setOverrides(next); + try { setOverrides(await api.setOverrides(next)); } catch (e) { + setOverrides(overrides); + toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) }); + } + }, [overrides, toast]); + + const updateSettings = useCallback(async (s: Settings) => { + const old = settings; + setSettings(s); + try { setSettings(await api.setSettings(s)); } catch (e) { setSettings(old); toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) }); } + }, [settings, toast]); + + // start: app info, folders, accounts, workspace, sidecar, cached live portfolio useEffect(() => { api.appInfo().then(setInfo, () => {}); reload().catch(() => {}).finally(() => setReady(true)); @@ -127,6 +225,22 @@ export function DataProvider({ children }: { children: ReactNode }) { useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]); + // Settings > Refresh: on launch, then every N minutes (store reads use the accounts' API quota: off by default) + const launched = useRef(false); + useEffect(() => { + if (!ready || launched.current) return; + launched.current = true; + if (settings.refresh.onLaunch && (projects.length || accounts.length)) importApps().finally(() => refreshPortfolio(true)); + }, [ready, settings.refresh.onLaunch, projects.length, accounts.length, importApps, refreshPortfolio]); + const busyRef = useRef(portfolioBusy); + busyRef.current = portfolioBusy; + useEffect(() => { + const m = settings.refresh.autoMinutes; + if (!m) return; + const tm = setInterval(() => { if (!busyRef.current) refreshPortfolio(true); }, m * 60_000); + return () => clearInterval(tm); + }, [settings.refresh.autoMinutes, refreshPortfolio]); + // icons: cached first, then read (offline, cheap) useEffect(() => { for (const p of projects) { @@ -163,11 +277,18 @@ export function DataProvider({ children }: { children: ReactNode }) { const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live'); return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path); }, [portfolio, live]); + const statusFor = useCallback((a: UnifiedApp) => (a.project ? statusOf(a.project) : portfolio?.apps.find(x => x.project === a.target) ?? live?.value.apps.find(x => x.project === a.target)), [statusOf, portfolio, live]); + const liveFor = useCallback((a: UnifiedApp) => (a.project ? liveOf(a.project) : portfolio?.apps.find(x => x.project === a.target && x.release.source === 'live') ?? live?.value.apps.find(x => x.project === a.target)), [liveOf, portfolio, live]); + const iconFor = useCallback((a: UnifiedApp) => (a.project ? icons[a.project.id] ?? a.storeIcon : a.storeIcon), [icons]); + const appByKey = useCallback((key: string) => apps.find(a => a.key === key), [apps]); const value = useMemo(() => ({ - ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons, - refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob, - }), [ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons, refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob]); + ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, + importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, + toasts, toast, updateToast, dismiss, cancelJob, + }), [ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, + importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, + toasts, toast, updateToast, dismiss, cancelJob]); return {children}; } @@ -183,16 +304,31 @@ export interface ReadState { refresh: () => Promise; } +/** Notifications a fresh read may trigger (Settings > Notifications), compared with the read it replaces. */ +function notifyAfterRead(method: string, prev: unknown, next: unknown, settings: Settings, appName: string | undefined): void { + const name = appName ?? ''; + if (method === 'reviews.list' && settings.notify.lowReviews && Array.isArray(next)) { + const fresh = newLowReviews(prev as Review[] | null, next as Review[]); + if (fresh.length) api.notify(t('notify.lowTitle', { name, count: fresh.length }), `${'★'.repeat(fresh[0]!.rating)} ${fresh[0]!.title ?? ''} ${fresh[0]!.body}`.trim()).catch(() => {}); + } + if (method === 'health' && settings.notify.crash && next && typeof next === 'object') { + const crossed = crashCrossed(prev as HealthSnapshot | null, next as HealthSnapshot); + if (crossed.length && !isError((next as HealthSnapshot).play)) api.notify(t('notify.crashTitle', { name }), crossed.map(k => (k === 'crash' ? t('health.crash') : t('health.anr'))).join(', ')).catch(() => {}); + } +} + /** - * One read method of one app. The cached value shows at once with its time; offline reads (`network: false`) then - * refresh by themselves, store reads only on demand (they use the account's API quota). A failed read keeps the last - * good value and says so: never an empty "all fine". + * One read method of one app (a project id, or a store-only app's store target). The cached value shows at once with + * its time; offline reads (`network: false`) then refresh by themselves, store reads only on demand (they use the + * account's API quota). A failed read keeps the last good value and says so: never an empty "all fine". */ -export function useRead(projectId: string, method: string, o: { network: boolean; args?: Record; title?: string }): ReadState { +export function useRead(target: string, method: string, o: { network: boolean; args?: Record; title?: string; appName?: string; skip?: boolean }): ReadState { const d = useData(); const argsKey = JSON.stringify(o.args ?? {}); const [s, set] = useState, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); const seq = useRef(0); + const dataRef = useRef(null); + dataRef.current = s.data; const refresh = useCallback(async () => { const my = ++seq.current; @@ -200,9 +336,10 @@ export function useRead(projectId: string, method: string, o: { network: bool set(x => ({ ...x, loading: true, error: null })); const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null; try { - const r = await api.call(method, projectId, { args: JSON.parse(argsKey) as Record }, job); + const r = await api.call(method, target, { args: JSON.parse(argsKey) as Record }, job); if (my !== seq.current) return; if (r.ok && r.data !== undefined) { + notifyAfterRead(method, dataRef.current, r.data, d.settings, o.appName); set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command }); if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined }); } else { @@ -216,19 +353,20 @@ export function useRead(projectId: string, method: string, o: { network: bool set(x => ({ ...x, loading: false, error: msg })); if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined }); } - }, [projectId, method, argsKey, o.network, o.title]); // eslint-disable-line react-hooks/exhaustive-deps + }, [target, method, argsKey, o.network, o.title, o.appName, d.settings]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { let alive = true; + if (o.skip) { set({ data: null, at: null, fromCache: false, loading: false, error: null, command: null }); return; } set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); - api.cached(method, projectId, JSON.parse(argsKey) as Record).then(c => { + api.cached(method, target, JSON.parse(argsKey) as Record).then(c => { if (!alive) return; if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command }); else set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); }, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } }); return () => { alive = false; }; - }, [projectId, method, argsKey]); // eslint-disable-line react-hooks/exhaustive-deps + }, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps return { ...s, refresh }; } diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index 3c1db63..de4c9c8 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -632,3 +632,119 @@ h2[tabindex="-1"]:focus, h2[tabindex="-1"]:focus-visible { outline: none; } .tbad { color: var(--bad-ink); } .twarn { color: var(--warn-ink); } .table .mini, .table .mini > * { white-space: nowrap; } .table .mini .row { flex-wrap: nowrap; } + +/* ---- D3: studios, store-only apps, toolbar, accounts, settings ---- */ +:root { + --st-indigo: #4f46e5; --st-violet: #7c3aed; --st-rose: #e11d48; --st-amber: #b45309; + --st-emerald: #047857; --st-teal: #0f766e; --st-sky: #0369a1; --st-slate: #475569; +} +.studio-indigo { --st: var(--st-indigo); } .studio-violet { --st: var(--st-violet); } .studio-rose { --st: var(--st-rose); } .studio-amber { --st: var(--st-amber); } +.studio-emerald { --st: var(--st-emerald); } .studio-teal { --st: var(--st-teal); } .studio-sky { --st: var(--st-sky); } .studio-slate { --st: var(--st-slate); } + +.studio-mark { display: inline-grid; place-items: center; flex: none; overflow: hidden; color: #fff; font-weight: 760; letter-spacing: .02em; + background: linear-gradient(140deg, color-mix(in srgb, var(--st, var(--st-slate)) 82%, #fff), var(--st, var(--st-slate))); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .08); } +.studio-mark img { width: 100%; height: 100%; object-fit: cover; } +.studio-mark.sm { width: 16px; height: 16px; border-radius: 5px; font-size: 7.5px; } +.studio-mark.md { width: 28px; height: 28px; border-radius: 8px; font-size: 11px; } +.studio-mark.lg { width: 40px; height: 40px; border-radius: 11px; font-size: 14px; } +.studio-mark.none { background: transparent; box-shadow: inset 0 0 0 1.5px var(--line-2); border: 0; } +.studio-mark.none.sm { box-shadow: inset 0 0 0 1.5px var(--faint); } + +.so-tag { height: 20px; padding: 0 7px; font-size: 10.5px; gap: 4px; } +.so-tag svg { width: 12px; height: 12px; } +.so-dot { display: inline-grid; place-items: center; color: var(--faint); } +.so-dot svg { width: 13px; height: 13px; } +.nav[aria-current="page"] .so-dot svg { color: var(--faint); } + +/* sidebar studio groups */ +.side-group { margin-top: 2px; } +.side-group-head { all: unset; box-sizing: border-box; width: 100%; display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 8px 0 6px; border-radius: 7px; cursor: pointer; + font-size: var(--t-meta); font-weight: 650; color: var(--ink-2); transition: background-color var(--speed) var(--ease); } +.side-group-head:hover { background: var(--hover); color: var(--ink); } +.side-group-head:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; } +.side-group-head .chev { width: 12px; height: 12px; color: var(--muted); transition: transform var(--speed) var(--ease); } +.side-group-head[aria-expanded="true"] .chev { transform: rotate(90deg); } +.side-group-head .grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.side-group-head .count { font-size: var(--t-micro); color: var(--muted); font-weight: 560; font-variant-numeric: tabular-nums; } +.side-group [role="list"] { padding-left: 12px; margin-left: 13px; border-left: 1px solid var(--line); } +.side-group .nav-app { height: 32px; } + +/* portfolio toolbar */ +.toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; } +.toolbar .search-input { width: 260px; } +.toolbar .search-input .input { height: 32px; } +.toolbar .grow { flex: 1; } +.fchips { display: flex; flex-wrap: wrap; gap: 6px; } +.fchip { all: unset; box-sizing: border-box; display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 11px 0 9px; border-radius: 999px; cursor: pointer; + background: var(--surface); border: 1px solid var(--line); color: var(--ink-2); font-size: var(--t-meta); font-weight: 600; box-shadow: var(--shadow-1); + transition: background-color var(--speed) var(--ease), border-color var(--speed) var(--ease); } +.fchip:hover { background: var(--hover); color: var(--ink); } +.fchip:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; } +.fchip .n { font-size: var(--t-micro); font-weight: 650; color: var(--muted); font-variant-numeric: tabular-nums; padding: 1px 6px; border-radius: 999px; background: var(--bg-sunken); } +.fchip[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--accent); } +.fchip[aria-pressed="true"] .n { background: var(--surface); color: var(--accent); } +.table tbody tr.group-row td { background: var(--surface-2); padding-top: 9px; padding-bottom: 9px; border-top: 1px solid var(--line); } +.table tbody tr.group-row b { font-weight: 680; } +.table tbody tr.group-row:hover td { background: var(--surface-2); } +.table tbody + tbody tr.group-row td { border-top: 1px solid var(--line-2); } + +/* studios & accounts */ +.studio-card .card-head { align-items: center; } +.studio-card.focus { box-shadow: var(--shadow-2), 0 0 0 2px var(--accent-line); } +.studio-edit { display: grid; grid-template-columns: minmax(200px, 320px) 1fr auto; gap: 16px; align-items: end; border-bottom: 1px solid var(--line); } +.acct-list { display: grid; } +.acct { border-top: 1px solid var(--line); } +.acct.is-ignored .acct-row { opacity: .62; } +.acct-row { display: flex; align-items: center; gap: 14px; padding: 12px 18px; } +.acct-glyph { width: 32px; height: 32px; border-radius: 9px; display: grid; place-items: center; flex: none; background: var(--bg-sunken); border: 1px solid var(--line); } +.acct-glyph svg { width: 16px; height: 16px; } +.acct-main { flex: 1; min-width: 0; display: grid; gap: 3px; } +.acct-main .small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.acct-edit { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(180px, 1fr) auto; gap: 12px; align-items: end; padding: 0 18px 14px 64px; } +.acct-fix { padding: 0 18px 14px 64px; } +.swatches { display: flex; flex-wrap: wrap; gap: 8px; } +.swatch { all: unset; box-sizing: border-box; width: 26px; height: 26px; border-radius: 8px; display: grid; place-items: center; cursor: pointer; color: #fff; + background: var(--st); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .1); transition: transform var(--speed) var(--ease); } +.swatch:hover { transform: translateY(-1px); } +.swatch:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +.swatch[aria-checked="true"] { box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--st); } +.swatch svg { width: 14px; height: 14px; } + +/* app page: studio pill, pairing controls */ +.studio-pill { all: unset; box-sizing: border-box; display: inline-flex; align-items: center; gap: 7px; height: 24px; padding: 0 10px 0 5px; border-radius: 999px; cursor: pointer; + background: var(--surface); border: 1px solid var(--line); font-size: var(--t-micro); font-weight: 650; color: var(--ink-2); } +.studio-pill:hover { background: var(--hover); color: var(--ink); } +.studio-pill:focus-visible { outline: 2px solid var(--focus); } +.app-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; padding: 8px 12px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface-2); } +.input.input-sm, select.input.input-sm { height: 28px; padding: 0 8px; font-size: var(--t-meta); width: auto; max-width: 280px; } + +/* settings */ +.set-layout { display: grid; grid-template-columns: 210px minmax(0, 1fr); gap: 24px; align-items: start; } +.set-nav { position: sticky; top: 0; display: grid; gap: 1px; padding: 6px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--surface); box-shadow: var(--shadow-1); } +.set-nav .nav { height: 30px; font-size: var(--t-meta); } +.set-nav .nav[aria-current="true"] { background: var(--accent-soft); color: var(--accent); font-weight: 650; } +.set-nav .nav[aria-current="true"] svg { color: var(--accent); } +.set-body .card { scroll-margin-top: 12px; } +.toggle-row { display: flex; align-items: center; gap: 16px; padding: 10px 0; border-top: 1px solid var(--line); cursor: pointer; } +.toggle-row:first-child { border-top: 0; padding-top: 0; } +.toggle-row .grow { display: grid; gap: 2px; } +.switch { appearance: none; -webkit-appearance: none; flex: none; width: 36px; height: 21px; border-radius: 999px; background: var(--line-2); position: relative; cursor: pointer; margin: 0; + transition: background-color var(--speed) var(--ease); } +.switch::after { content: ""; position: absolute; top: 2.5px; left: 2.5px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, .3); transition: transform var(--speed) var(--ease); } +.switch:checked { background: var(--accent-solid); } +.switch:checked::after { transform: translateX(15px); } +.switch:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +.studio-sum { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; } +.studio-sum-item { all: unset; box-sizing: border-box; display: flex; align-items: center; gap: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); cursor: pointer; background: var(--surface-2); } +.studio-sum-item:hover { background: var(--hover); } +.studio-sum-item:focus-visible { outline: 2px solid var(--focus); } +.dep-sum { display: flex; flex-wrap: wrap; gap: 8px 20px; } +.plain-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } +.plain-list li { display: flex; gap: 10px; align-items: flex-start; font-size: var(--t-body); color: var(--ink-2); } +.plain-list svg { width: 15px; height: 15px; color: var(--ok-solid); flex: none; margin-top: 2px; } +.danger-card { border-color: color-mix(in srgb, var(--bad-solid) 35%, var(--line)); } +.btn.btn-danger:not(.btn-ghost) { color: var(--bad-ink); background: var(--bad-bg); border-color: color-mix(in srgb, var(--bad-solid) 40%, transparent); } +@media (max-width: 1100px) { .set-layout { grid-template-columns: 1fr; } .set-nav { position: static; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); } .studio-edit, .acct-edit { grid-template-columns: 1fr; } } +.cell-app .s .so-inline { display: inline-flex; align-items: center; gap: 4px; margin-left: 8px; font-family: var(--font); font-size: var(--t-micro); font-weight: 650; color: var(--muted); } +.cell-app .s .so-inline svg { width: 12px; height: 12px; } +.toolbar .search-input { width: 240px; } diff --git a/apps/desktop/src/ui/icons.tsx b/apps/desktop/src/ui/icons.tsx index dd5a607..ca560fb 100644 --- a/apps/desktop/src/ui/icons.tsx +++ b/apps/desktop/src/ui/icons.tsx @@ -47,6 +47,20 @@ const P = { keyboard: 'M3.5 6.5h17A1 1 0 0 1 21.5 7.5v9a1 1 0 0 1-1 1h-17a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1zM6.5 10h.1M10 10h.1M13.5 10h.1M17 10h.1M7.5 14h9', database: 'M12 8c4.4 0 8-1.3 8-3s-3.6-3-8-3-8 1.3-8 3 3.6 3 8 3zM4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3', wand: 'M14.5 6.5l3 3M4 20 17.5 6.5l-3-3L1 17zM19 2.5v3M20.5 4h-3M21 10v2M22 11h-2', + building: 'M4.5 20.5V5A1.5 1.5 0 0 1 6 3.5h7A1.5 1.5 0 0 1 14.5 5v15.5M14.5 9.5H18a1.5 1.5 0 0 1 1.5 1.5v9.5M3 20.5h18M8 7.5h3M8 11h3M8 14.5h3', + eye: 'M2.5 12c1-1.5 4.5-6 9.5-6s8.5 4.5 9.5 6c-1 1.5-4.5 6-9.5 6s-8.5-4.5-9.5-6zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', + eyeOff: 'M3 3l18 18M10.6 6.1c.5-.1.9-.1 1.4-.1 5 0 8.5 4.5 9.5 6-.5.8-1.6 2.3-3.2 3.6M6.4 7.9C4.7 9.2 3.5 10.9 2.5 12c1 1.5 4.5 6 9.5 6 1.5 0 2.9-.4 4.1-1M9.9 9.9a3 3 0 0 0 4.2 4.2', + link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1', + unlink: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1M4 4l16 16', + bell: 'M6 16.5V11a6 6 0 1 1 12 0v5.5l1.5 2h-15zM10 20.5a2 2 0 0 0 4 0', + filter: 'M4 5.5h16l-6 7.5v5.5l-4 1.5v-7z', + play: 'M8 5.5v13l10.5-6.5z', + send: 'M4 11.5 20 4l-6 16-3-6.5zM11 13.5 20 4', + edit: 'M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4', + upload: 'M12 20V9M7.5 13.5 12 9l4.5 4.5M4.5 4.5h15', + sliders: 'M4 6.5h9M17 6.5h3M4 12h3M11 12h9M4 17.5h11M19 17.5h1M15 4.5v4M9 10v4M17 15.5v4', + rotate: 'M4 12a8 8 0 1 0 2.4-5.7L4 8.5M4 4v4.5h4.5', + cloud: 'M7 18.5h10.5a4 4 0 0 0 .6-8 6 6 0 0 0-11.6 1.6A3.3 3.3 0 0 0 7 18.5z', } as const; export type IconName = keyof typeof P; diff --git a/apps/desktop/src/ui/kit.tsx b/apps/desktop/src/ui/kit.tsx index 64555ec..f7746d3 100644 --- a/apps/desktop/src/ui/kit.tsx +++ b/apps/desktop/src/ui/kit.tsx @@ -137,9 +137,9 @@ export function Seg({ value, options, onChange, label }: { val ); } -export function Card({ title, icon, sub, actions, children, foot, className = '', pad = true }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; foot?: ReactNode; className?: string; pad?: boolean }) { +export function Card({ title, icon, sub, actions, children, foot, className = '', pad = true, id }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; foot?: ReactNode; className?: string; pad?: boolean; id?: string }) { return ( -
+
{title !== undefined && (

{icon && }{title}

{sub &&
{sub}
}
@@ -158,3 +158,15 @@ export function Kbd({ keys }: { keys: string[] }) { /** Platform modifier label (⌘ on macOS, Ctrl elsewhere). */ export const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'; + +/** A studio's logo, or its monogram on the studio colour. `null` studio: "No studio" (dashed). */ +export function StudioMark({ studio, size = 'md' }: { studio: { name: string; color: string; logo?: string | null } | null; size?: 'sm' | 'md' | 'lg' }) { + if (!studio) return