Compare commits

...

4 commits

27 changed files with 1131 additions and 92 deletions

View file

@ -85,6 +85,33 @@ for (const theme of themes) {
await page.locator('.fchip').first().click();
await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill('');
}
if (!only.length || only.includes('tf-edit')) {
// TestFlight: What to Test editor of the newest build
await page.goto(`${base}/?start=app:testflight&theme=${theme}&lang=${lang}`);
await settle(page);
await page.getByRole('button', { name: /What to Test|Neyi test etmeli/ }).first().click();
await page.getByRole('textbox').first().fill('New combo meter and the calmer night palette. Please try level 31 at a 20x combo.');
await page.waitForTimeout(200);
await page.evaluate(() => document.getElementById('content')?.scrollBy({ top: 330 }));
await page.waitForTimeout(200);
await shot('tf-edit');
}
if (!only.length || only.includes('reply-edit')) {
// Reviews: the reply editor of the approved draft, edited (not saved yet)
await page.goto(`${base}/?start=app:reviews&theme=${theme}&lang=${lang}`);
await settle(page);
await page.locator('textarea.reply-edit').fill('Sorry about the lost streak! The fix for the crash at high combos is in 2.4.0, in review now. Thank you for the level number.');
await page.waitForTimeout(200);
await shot('reply-edit');
}
if (!only.length || only.includes('write-toast')) {
// a write running: halt the Play rollout (owner action), caught with its progress toast
await page.goto(`${base}/?start=app:releases&theme=${theme}&lang=${lang}`);
await settle(page);
await page.getByRole('button', { name: /^Halt$|^Durdur$/ }).first().click();
await page.waitForTimeout(450);
await shot('write-toast');
}
if (!only.length || only.includes('import')) {
// Import apps running, with its progress toast
await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`);

View file

@ -138,7 +138,7 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
let mut p = policy::sanitize_js_call(&method, kind, &params.unwrap_or(Value::Null)).map_err(Fail::host)?;
let args = p.get("args").cloned().unwrap_or_else(|| json!({}));
let mut cache_project = None;
if matches!(kind, Some(Kind::Read | Kind::Write)) {
if matches!(kind, Some(Kind::Read | Kind::Write | Kind::Owner)) {
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
@ -242,8 +242,26 @@ pub fn dialog_summary(title: &str, description: &str, project: &str, network: bo
s
}
/// Summary of an owner action: users see it right away, so the dialog says so in plain words.
pub fn owner_summary(title: &str, description: &str, project: &str) -> String {
format!("{title} · {project}\n\n{description}\n\nThis is your decision: it changes what users get on the store right away. storebound does it only because you press the button below.")
}
/// Dialog title and the confirm button of a write: owner actions name the action on the button.
pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) {
if kind == Kind::Owner {
(format!("Owner action: {title}"), format!("Yes: {title}"))
} else {
(format!("Apply: {title}"), "Apply".to_string())
}
}
/// Native Apply / Cancel dialog; true on Apply.
async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) -> Res<bool> {
confirm_dialog_with(window, title, text, "Apply".into()).await
}
async fn confirm_dialog_with(window: &WebviewWindow, title: String, text: String, ok: String) -> Res<bool> {
let w = window.clone();
tauri::async_runtime::spawn_blocking(move || {
w.app_handle()
@ -251,7 +269,7 @@ async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) ->
.message(text)
.title(title)
.kind(MessageDialogKind::Warning)
.buttons(MessageDialogButtons::OkCancelCustom("Apply".into(), "Cancel".into()))
.buttons(MessageDialogButtons::OkCancelCustom(ok, "Cancel".into()))
.parent(&w)
.blocking_show()
})
@ -266,9 +284,11 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
guard(&window)?;
let job = job_of(job)?;
let r = state.sidecar.get(&app).await?;
if r.kind(&method) != Some(Kind::Write) || method == "project.init" {
let kind = r.kind(&method);
if !matches!(kind, Some(Kind::Write | Kind::Owner)) || method == "project.init" {
return Err(Fail::host(format!("{method} is not a write method of an app folder")));
}
let kind = kind.unwrap_or(Kind::Write);
let d = r.descriptor(&method).cloned().ok_or_else(|| Fail::host("unknown method"))?;
let args = match args.unwrap_or(json!({})) {
Value::Object(o) => Value::Object(o),
@ -283,14 +303,11 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
if dry["ok"] != Value::Bool(true) {
return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry }));
}
let text = format!(
"{}\n\nDry run ({}):\n{}",
dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive),
dry["command"].as_str().unwrap_or_default(),
dialog_excerpt(dry["output"].as_str().unwrap_or_default())
);
let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) };
let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default()));
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
if !confirm_dialog(&window, format!("Apply: {}", d.title), tilde(&text, home.as_deref())).await? {
let (title, ok) = dialog_labels(kind, &d.title);
if !confirm_dialog_with(&window, title, tilde(&text, home.as_deref()), ok).await? {
return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry }));
}
let bound = json!({ "project": proj.path, "args": args });

View file

@ -53,6 +53,9 @@ pub enum Kind {
Session,
/// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key.
Account,
/// Owner actions (rollout share, phased release, sending one approved reply): like writes, a dry run from the
/// window; the real run only through `write_with_confirm`, whose dialog says that users see it at once.
Owner,
}
impl Kind {
@ -64,6 +67,7 @@ impl Kind {
"portfolio" => Kind::Portfolio,
"session" => Kind::Session,
"account" => Kind::Account,
"owner" => Kind::Owner,
_ => return None,
})
}
@ -96,7 +100,7 @@ pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Res
}
}
let mut out = obj.clone();
if kind == Kind::Write {
if matches!(kind, Kind::Write | Kind::Owner) {
out.insert("dryRun".into(), Value::Bool(true));
}
Ok(Value::Object(out))

View file

@ -0,0 +1,60 @@
//! Desktop D3 writes: owner actions are dry runs from the window like every write; only `write_with_confirm` runs them,
//! after a dialog that names the action on its button and says users see it at once. Tokens are bound to exactly the
//! method and the { project, args } sent (the same vector as the TypeScript side checks).
use serde_json::json;
use storebound_desktop::commands::{dialog_labels, dialog_summary, owner_summary};
use storebound_desktop::confirm::{canonical, mac, mint};
use storebound_desktop::policy::{sanitize_js_call, Kind};
#[test]
fn owner_actions_are_dry_runs_from_the_window() {
let p = sanitize_js_call("owner.play_rollout", Some(Kind::Owner), &json!({ "args": { "action": "complete" } })).unwrap();
assert_eq!(p["dryRun"], json!(true));
for bad in [json!({ "dryRun": false }), json!({ "confirmToken": "sbt1.x" }), json!({ "credentials": {} }), json!({ "project": "/x" })] {
assert!(sanitize_js_call("owner.reply_send", Some(Kind::Owner), &bad).is_err(), "{bad}");
}
assert_eq!(Kind::parse("owner"), Some(Kind::Owner));
let w = sanitize_js_call("reviews.reply", Some(Kind::Write), &json!({ "args": { "file": "play-1.md", "text": "Thanks" } })).unwrap();
assert_eq!(w["dryRun"], json!(true));
}
#[test]
fn owner_dialogs_name_the_action() {
let (title, ok) = dialog_labels(Kind::Owner, "Change the Play staged rollout");
assert_eq!(title, "Owner action: Change the Play staged rollout");
assert_eq!(ok, "Yes: Change the Play staged rollout");
assert_eq!(dialog_labels(Kind::Write, "Push Play listing text"), ("Apply: Push Play listing text".to_string(), "Apply".to_string()));
let s = owner_summary("Send one approved reply", "Sends one approved, unsent reply draft.", "Prism Puddle");
assert!(s.contains("Prism Puddle") && s.contains("right away") && s.contains("your decision"));
assert!(dialog_summary("Push", "d", "A", true, false).contains("not public until you submit"));
}
#[test]
fn tokens_bind_method_project_and_args_of_each_write() {
let secret = [9u8; 32];
let writes = [
("play.listing", json!({})),
("apple.listing", json!({ "version": "2.4.0" })),
("apple.screenshots", json!({})),
("apple.testflight_distribute", json!({ "build": "52", "groups": "Studio team" })),
("reviews.reply", json!({ "file": "play-r-p1.md", "text": "Thanks!" })),
("owner.play_rollout", json!({ "action": "percent", "percent": 50 })),
("owner.ios_phased", json!({ "action": "resume", "version": "2.3.0" })),
("owner.reply_send", json!({ "file": "play-r-p1.md" })),
];
for (method, args) in writes {
let bound = json!({ "project": "/apps/prism", "args": args });
let t = mint(&secret, method, &bound, 1_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap();
let sig = t.rsplit('.').next().unwrap().to_string();
assert_eq!(sig, mac(&secret, method, &bound, 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
// any change of method, project or args changes the signature
assert_ne!(sig, mac(&secret, "play.images", &bound, 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap(), "{method}");
assert_ne!(sig, mac(&secret, method, &json!({ "project": "/apps/other", "args": bound["args"] }), 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
let mut more = bound.clone();
more["args"]["x"] = json!(1);
assert_ne!(sig, mac(&secret, method, &more, 61_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
}
// a rollout share is a safe integer (percent), so it can be bound; fractions as numbers cannot
assert!(canonical(&json!({ "percent": 50 })).is_ok());
assert!(canonical(&json!({ "fraction": 0.5 })).is_err());
}

View file

@ -103,8 +103,8 @@ if (import.meta.env.VITE_FIXTURES === 'empty') overrides = { pairs: [], unpairs:
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<string, AccountCheck> = {
[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' },
[P1]: { store: 'android', status: 'ok', principal: 'play-bot@example.com', apps: 8, message: 'The service account can see 8 apps.', fix: null, docs: null },
[P2]: { store: 'android', status: 'permission', principal: 'sample-labs-bot@example.com', apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: PLAY_INVITE('sample-labs-bot@example.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 },
@ -496,12 +496,13 @@ async function answer(cmd: string, a: Record<string, unknown>): Promise<unknown>
}
case 'job_cancel': cancelled.add(a.job as string); return true;
case 'write_with_confirm': {
await sleep(500);
const method = a.method as string, args = (a.args ?? {}) as Record<string, unknown>;
if (method === 'reviews.approve') {
const d = DRAFTS[a.projectId as string]?.drafts.find(x => x.file.endsWith(`/${String(args.file)}`));
if (d) d.approved = !args.undo;
}
await progressLines(job, [`[${method}] dry run`, `[${method}] confirmed in the dialog`, `[${method}] applying`]);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
const d = DRAFTS[a.projectId as string]?.drafts.find(x => x.file.endsWith(`/${String(args.file)}`));
if (method === 'reviews.approve' && d) d.approved = !args.undo;
if (method === 'reviews.reply' && d) { d.reply = String(args.text); d.approved = false; d.issues = []; }
if (method === 'owner.reply_send' && d) d.sent = iso(0);
const res: ToolResult = { method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')}`, output: `[${method}] done (fixture)` };
return { confirmed: true, stage: 'done', dryRun: { ...res, dryRun: true }, result: res };
}

View file

@ -227,7 +227,7 @@ export const en = {
'releases.noVersionsText': 'When the first build is uploaded it shows here.',
'releases.history': 'Versions on the stores',
'releases.historySub': 'Read {when}',
'releases.consoleNote': 'storebound never submits for review, releases or completes a rollout. Do those in the store console.',
'releases.consoleNote': 'storebound never submits for review and never releases an approved version: do those in the store console. Rollout and phased release changes are your decision, each confirmed in a system dialog.',
'cat.products': 'One-time products',
'cat.productsSub': 'In the config',
@ -774,4 +774,96 @@ export const en = {
'portfolio.groupCount_one': '1 app',
'portfolio.groupAccounts': '{count} accounts',
'portfolio.groupAccounts_one': '1 account',
'write.dryRunning': 'Dry run first: nothing changes yet',
'write.notApplied': 'Not applied',
'write.notAppliedDetail': 'You chose Cancel in the dialog: nothing changed.',
'act.storeTitle': 'Push to the stores',
'act.storeSub': 'Listing text, screenshots and previews from this folder, and the local renders',
'act.playListing': 'Listing text',
'act.playListingDone': 'Play listing updated',
'act.playImages': 'Graphics and screenshots',
'act.version': 'Version',
'act.appleListing': 'Version {version} and its text',
'act.appleListingDone': 'App Store version and text updated',
'act.appleShots': 'Screenshots',
'act.applePreviews': 'App previews',
'act.uploaded': 'Uploaded',
'act.slowHint': 'Can take minutes: progress shows in the toast, Cancel stops it',
'act.render': 'Render (local)',
'act.renderLang': 'Language to render',
'act.allLangs': 'All languages',
'act.renderShots': 'Render screenshots',
'act.renderVideo': 'Cut app previews',
'act.icons': 'Generate icons',
'act.gallery': 'Review gallery',
'act.galleryDone': 'Gallery written next to the renders',
'act.rendered': 'Done',
'act.localHint': 'Local files only; needs ffmpeg and Chrome (Dependencies)',
'act.note': 'Each action runs a dry run and shows it in a system dialog before anything changes. Nothing here submits for review or publishes: that stays in the consoles.',
'act.catalogTitle': 'Sync the catalog',
'act.catalogSub': 'Create and update products and subscriptions with their regional prices from the config',
'act.playProducts': 'One-time products',
'act.playSubs': 'Subscriptions',
'act.appleIap': 'In-app purchases',
'act.appleSubs': 'Subscriptions',
'act.synced': 'Catalog updated',
'act.prices': 'Prices',
'act.pricesExport': 'Export prices (CSV)',
'act.pricesExported': 'Prices exported into the folder',
'act.pricesImport': 'Changing live prices from a sheet stays a terminal step:',
'act.catalogNote': 'Never submits: new items wait in the consoles until you send them with a version.',
'roll.playNow': 'Rollout {pct} %',
'roll.share': 'New user share',
'roll.toShare': 'Raise to {pct} %',
'roll.halt': 'Halt',
'roll.haltHint': 'Stops new installs of the update; not a rollback',
'roll.halted': 'Rollout halted',
'roll.resume': 'Resume',
'roll.complete': 'Everyone (100 %)',
'roll.completeHint': 'Completes the staged rollout: every user gets the update',
'roll.done': 'Rollout updated',
'roll.iosNow': 'Phased release, day {day} of 7',
'roll.pause': 'Pause',
'roll.pauseHint': 'Holds the automatic updates (up to 30 days); not a rollback',
'roll.paused': 'Phased release paused',
'roll.everyone': 'Release to everyone',
'roll.everyoneHint': 'Ends the phased release: every user with automatic updates gets it now',
'roll.phasedOn': 'Turn on phased release',
'roll.phasedOnHint': 'When this version goes live, it reaches users with automatic updates over 7 days',
'roll.phasedOnDone': 'Phased release is on',
'tf.what': 'What to Test',
'tf.groupsBtn': 'Internal groups',
'tf.whatToTest': 'What to Test for build {build}',
'tf.whatPlaceholder': 'What changed and what to look at (every App Store locale gets this text)',
'tf.whatSave': 'Set this text',
'tf.whatFromFile': 'From the listing file',
'tf.whatFromFileHint': 'Each locale\'s whatToTest (or What\'s New) from the App Store listing file',
'tf.whatSaved': 'What to Test updated',
'tf.toInternal': 'Give build {build} to internal groups',
'tf.noInternal': 'No internal group: create one in App Store Connect or with apple.testflight.groups.',
'tf.distribute': 'Give to these groups',
'tf.distributed': 'Build added to the groups',
'tf.externalNote': 'External groups and Beta App Review stay in App Store Connect.',
'tf.testersTitle': 'Testers',
'tf.testersSub': 'From the testers CSV in this folder (.storebound/testers.csv, never committed)',
'tf.testersGroup': 'Group',
'tf.testersAll': 'Every group in the CSV',
'tf.testersAdd': 'Add new testers',
'tf.testersHint': 'Apple emails each new tester an invitation once the group has a build',
'tf.testersDone': 'Testers added',
'tf.testersNote': 'Emails stay masked in every line and dialog. Removing testers stays a terminal step.',
'reviews.replyEditor': 'Reply',
'reviews.replyPlaceholder': 'Plain text, in the reviewer\'s language. No incentives, no personal data.',
'reviews.unsaved': 'Not saved',
'reviews.save': 'Save draft',
'reviews.saved': 'Draft saved (approve it again)',
'reviews.send': 'Send reply',
'reviews.sendHint': 'Public: the reviewer is notified. A system dialog shows the reply first.',
'reviews.sent': 'Reply sent',
'reviews.incentive': 'Offers something for a rating or asks for stars: not allowed',
'reviews.tooLong': 'Longer than the store allows ({limit} characters)',
'reviews.sendNoteD3': 'Replies are public. Save, approve, then Send: each step shows a system dialog first.',
} as const;

View file

@ -229,7 +229,7 @@ export const tr: Record<keyof typeof en, string> = {
'releases.noVersionsText': 'İlk derleme yüklendiğinde burada görünür.',
'releases.history': 'Mağazalardaki sürümler',
'releases.historySub': '{when} okundu',
'releases.consoleNote': 'storebound hiçbir zaman incelemeye göndermez, yayınlamaz veya dağıtımı tamamlamaz. Bunları mağaza konsolunda yapın.',
'releases.consoleNote': 'storebound hiçbir zaman incelemeye göndermez ve onaylanmış bir sürümü yayınlamaz: bunları mağaza konsolunda yapın. Dağıtım ve aşamalı yayın değişiklikleri sizin kararınızdır, her biri bir sistem penceresinde onaylanır.',
'cat.products': 'Tek seferlik ürünler',
'cat.productsSub': 'Ayar dosyasında',
@ -776,4 +776,96 @@ export const tr: Record<keyof typeof en, string> = {
'portfolio.groupCount_one': '1 uygulama',
'portfolio.groupAccounts': '{count} hesap',
'portfolio.groupAccounts_one': '1 hesap',
'write.dryRunning': 'Önce deneme: henüz hiçbir şey değişmiyor',
'write.notApplied': 'Uygulanmadı',
'write.notAppliedDetail': 'Pencerede İptal\'i seçtiniz: hiçbir şey değişmedi.',
'act.storeTitle': 'Mağazalara gönder',
'act.storeSub': 'Bu klasördeki mağaza metni, ekran görüntüleri ve önizlemeler, ve yerel çıktılar',
'act.playListing': 'Mağaza metni',
'act.playListingDone': 'Play mağaza metni güncellendi',
'act.playImages': 'Grafikler ve ekran görüntüleri',
'act.version': 'Sürüm',
'act.appleListing': '{version} sürümü ve metni',
'act.appleListingDone': 'App Store sürümü ve metni güncellendi',
'act.appleShots': 'Ekran görüntüleri',
'act.applePreviews': 'Uygulama önizlemeleri',
'act.uploaded': 'Yüklendi',
'act.slowHint': 'Dakikalar sürebilir: ilerleme bildirimde görünür, İptal durdurur',
'act.render': 'Üret (yerel)',
'act.renderLang': 'Üretilecek dil',
'act.allLangs': 'Tüm diller',
'act.renderShots': 'Ekran görüntülerini üret',
'act.renderVideo': 'Önizlemeleri kes',
'act.icons': 'Simgeleri üret',
'act.gallery': 'İnceleme galerisi',
'act.galleryDone': 'Galeri çıktıların yanına yazıldı',
'act.rendered': 'Bitti',
'act.localHint': 'Yalnızca yerel dosyalar; ffmpeg ve Chrome gerekir (Bağımlılıklar)',
'act.note': 'Her işlem önce bir deneme çalıştırır ve bir şey değişmeden önce sistem penceresinde gösterir. Buradaki hiçbir şey incelemeye göndermez ya da yayımlamaz: o konsollarda kalır.',
'act.catalogTitle': 'Kataloğu eşitle',
'act.catalogSub': 'Ürünleri ve abonelikleri bölgesel fiyatlarıyla yapılandırmadan oluştur ve güncelle',
'act.playProducts': 'Tek seferlik ürünler',
'act.playSubs': 'Abonelikler',
'act.appleIap': 'Uygulama içi satın almalar',
'act.appleSubs': 'Abonelikler',
'act.synced': 'Katalog güncellendi',
'act.prices': 'Fiyatlar',
'act.pricesExport': 'Fiyatları dışa aktar (CSV)',
'act.pricesExported': 'Fiyatlar klasöre aktarıldı',
'act.pricesImport': 'Canlı fiyatları bir tablodan değiştirmek terminal adımı olarak kalır:',
'act.catalogNote': 'Asla göndermez: yeni ürünler siz bir sürümle gönderene kadar konsollarda bekler.',
'roll.playNow': 'Dağıtım %{pct}',
'roll.share': 'Yeni kullanıcı payı',
'roll.toShare': '%{pct} yap',
'roll.halt': 'Durdur',
'roll.haltHint': 'Güncellemenin yeni kurulumlarını durdurur; geri alma değildir',
'roll.halted': 'Dağıtım durduruldu',
'roll.resume': 'Sürdür',
'roll.complete': 'Herkese (%100)',
'roll.completeHint': 'Kademeli dağıtımı tamamlar: her kullanıcı güncellemeyi alır',
'roll.done': 'Dağıtım güncellendi',
'roll.iosNow': 'Aşamalı yayın, 7 günün {day}. günü',
'roll.pause': 'Duraklat',
'roll.pauseHint': 'Otomatik güncellemeleri bekletir (en çok 30 gün); geri alma değildir',
'roll.paused': 'Aşamalı yayın duraklatıldı',
'roll.everyone': 'Herkese yayınla',
'roll.everyoneHint': 'Aşamalı yayını bitirir: otomatik güncellemesi açık her kullanıcı şimdi alır',
'roll.phasedOn': 'Aşamalı yayını aç',
'roll.phasedOnHint': 'Bu sürüm yayına girince otomatik güncellemesi açık kullanıcılara 7 günde ulaşır',
'roll.phasedOnDone': 'Aşamalı yayın açık',
'tf.what': 'Neyi test etmeli',
'tf.groupsBtn': 'İç gruplar',
'tf.whatToTest': '{build} derlemesi için Neyi test etmeli',
'tf.whatPlaceholder': 'Ne değişti, nelere bakılmalı (her App Store dili bu metni alır)',
'tf.whatSave': 'Bu metni ayarla',
'tf.whatFromFile': 'Mağaza dosyasından',
'tf.whatFromFileHint': 'App Store mağaza dosyasındaki her dilin whatToTest (ya da Yenilikler) metni',
'tf.whatSaved': 'Neyi test etmeli güncellendi',
'tf.toInternal': '{build} derlemesini iç gruplara ver',
'tf.noInternal': 'İç grup yok: App Store Connect\'te ya da apple.testflight.groups ile oluşturun.',
'tf.distribute': 'Bu gruplara ver',
'tf.distributed': 'Derleme gruplara eklendi',
'tf.externalNote': 'Dış gruplar ve Beta App Review App Store Connect\'te kalır.',
'tf.testersTitle': 'Test kullanıcıları',
'tf.testersSub': 'Bu klasördeki test kullanıcısı CSV\'sinden (.storebound/testers.csv, asla commit edilmez)',
'tf.testersGroup': 'Grup',
'tf.testersAll': 'CSV\'deki her grup',
'tf.testersAdd': 'Yeni test kullanıcılarını ekle',
'tf.testersHint': 'Grubun bir derlemesi olunca Apple her yeni kullanıcıya davet e-postası gönderir',
'tf.testersDone': 'Test kullanıcıları eklendi',
'tf.testersNote': 'E-postalar her satırda ve pencerede maskeli kalır. Kullanıcı çıkarmak terminal adımı olarak kalır.',
'reviews.replyEditor': 'Yanıt',
'reviews.replyPlaceholder': 'Düz metin, yorumcunun dilinde. Teşvik yok, kişisel veri yok.',
'reviews.unsaved': 'Kaydedilmedi',
'reviews.save': 'Taslağı kaydet',
'reviews.saved': 'Taslak kaydedildi (yeniden onaylayın)',
'reviews.send': 'Yanıtı gönder',
'reviews.sendHint': 'Herkese açık: yorumcu bilgilendirilir. Önce bir sistem penceresi yanıtı gösterir.',
'reviews.sent': 'Yanıt gönderildi',
'reviews.incentive': 'Puan karşılığı bir şey öneriyor ya da yıldız istiyor: izin verilmez',
'reviews.tooLong': 'Mağazanın izin verdiğinden uzun ({limit} karakter)',
'reviews.sendNoteD3': 'Yanıtlar herkese açıktır. Kaydet, onayla, sonra Gönder: her adım önce bir sistem penceresi gösterir.',
};

View file

@ -247,7 +247,7 @@ export function Portfolio() {
actions={<div className="legend-row"><span><span className="pips"><b className="on" /></span>{t('legend.done')}</span><span>{t('legend.stages')}</span></div>}>
{rows.length ? (
<div className="table-wrap">
<table className="table">
<table className="table pf">
<thead><tr>
<th>{t('col.app')}</th><th>App Store</th><th>Google Play</th><th>{t('col.next')}</th><th>{t('col.crash')}</th><th>{t('col.catalog')}</th><th className="right">{t('col.config')}</th>
</tr></thead>

View file

@ -4,8 +4,9 @@ import type { Project } from '../../api';
import { type Key, t } from '../../i18n';
import { ago, num } from '../../lib/format';
import { type CatalogDiff, type CellState, parityMatrix } from '../../lib/model';
import { useData, useRead } from '../../store';
import { Icon, type IconName } from '../../ui/icons';
import { useData, useRead, useWrite } from '../../store';
import { Icon, type IconName, StoreGlyph } from '../../ui/icons';
import { WriteButton } from '../../ui/WriteButton';
import { Card, Chip, Empty, Kpi, Notice, Skeleton } from '../../ui/kit';
const CELL: Record<CellState, [IconName, Key]> = { ok: ['check', 'cat.ok'], warn: ['alert', 'cat.warn'], error: ['x', 'cat.error'], na: ['dot', 'cat.na'], unknown: ['info', 'cat.unknown'] };
@ -20,6 +21,40 @@ function Cell({ c }: { c: { state: CellState; notes: string[] } }) {
);
}
/** Create / update the catalog on both stores from the config (prices included), and export the price sheet. */
function CatalogActions({ project, products, subs, refresh }: { project: Project; products: number; subs: number; refresh: () => void }) {
const d = useData();
const w = useWrite(project.id);
const e = d.statusOf(project);
const ios = !!e?.app?.platforms.ios, android = !!e?.app?.platforms.android;
return (
<Card title={t('act.catalogTitle')} icon="upload" sub={t('act.catalogSub')}>
<div className="act-grid">
{android && (
<div className="act-col">
<div className="act-head"><StoreGlyph store="android" />Google Play</div>
<WriteButton run={w} icon="tag" disabled={!products} w={{ method: 'play.products', args: {}, title: t('act.playProducts'), done: t('act.synced'), after: refresh }}>{t('act.playProducts')}</WriteButton>
<WriteButton run={w} icon="refresh" disabled={!subs} w={{ method: 'play.subscriptions', args: {}, title: t('act.playSubs'), done: t('act.synced'), after: refresh }}>{t('act.playSubs')}</WriteButton>
</div>
)}
{ios && (
<div className="act-col">
<div className="act-head"><StoreGlyph store="ios" />App Store</div>
<WriteButton run={w} icon="tag" disabled={!products} w={{ method: 'apple.iap', args: {}, title: t('act.appleIap'), done: t('act.synced'), after: refresh }}>{t('act.appleIap')}</WriteButton>
<WriteButton run={w} icon="refresh" disabled={!subs} w={{ method: 'apple.subscriptions', args: {}, title: t('act.appleSubs'), done: t('act.synced'), after: refresh }}>{t('act.appleSubs')}</WriteButton>
</div>
)}
<div className="act-col">
<div className="act-head"><Icon name="database" />{t('act.prices')}</div>
<WriteButton run={w} icon="download" w={{ method: 'prices.export', args: {}, title: t('act.pricesExport'), done: t('act.pricesExported') }}>{t('act.pricesExport')}</WriteButton>
<span className="small muted">{t('act.pricesImport')} <code className="selectable">storebound prices import</code></span>
</div>
</div>
<p className="small muted act-note"><Icon name="shield" />{t('act.catalogNote')}</p>
</Card>
);
}
export function CatalogTab({ project }: { project: Project }) {
const d = useData();
const e = d.statusOf(project);
@ -43,6 +78,7 @@ export function CatalogTab({ project }: { project: Project }) {
<Kpi icon="globe" label={t('cat.gaps')} value={read ? gaps.length : '–'} sub={read ? t('cat.gapsSub') : t('kpi.notRead')} />
</div>
{diff.error && <Notice tone="warn">{t('common.readFailedKeep', { error: diff.error })}</Notice>}
<CatalogActions project={project} products={s?.products ?? 0} subs={s?.subscriptions ?? 0} refresh={() => { diff.refresh(); }} />
<Card title={t('cat.matrix')} icon="layers" sub={read ? (diff.fromCache ? t('common.cachedFrom', { when: ago(diff.at) }) : t('common.readWhen', { when: ago(diff.at) })) : t('cat.configOnly')} pad={false}
actions={<button className="btn btn-sm" onClick={diff.refresh} disabled={diff.loading}><Icon name="refresh" className={diff.loading ? 'spin' : undefined} />{read ? t('action.refresh') : t('cat.compare')}</button>}>
<div className="table-wrap">

View file

@ -1,10 +1,12 @@
// Listings: per language and store, which listing fields are written and within the store limits (from the listing
// files in the app folder), and how many screenshots are rendered per language.
import { useState } from 'react';
import type { ListingField, ListingLocale, ListingsResult, Project } from '../../api';
import { type Key, t } from '../../i18n';
import { ago, num } from '../../lib/format';
import { useRead } from '../../store';
import { Icon } from '../../ui/icons';
import { useData, useRead, useWrite } from '../../store';
import { Icon, StoreGlyph } from '../../ui/icons';
import { WriteButton } from '../../ui/WriteButton';
import { Card, Chip, Empty, Kpi, Notice, Skeleton } from '../../ui/kit';
const FIELD_KEY: Record<string, Key> = {
@ -56,6 +58,57 @@ function StoreGrid({ store, locales }: { store: 'play' | 'apple'; locales: Listi
);
}
/** Push the listing text, upload the art, and render it (each a dry run, a native dialog, then the real run). */
function StoreActions({ project, langs }: { project: Project; langs: string[] }) {
const d = useData();
const w = useWrite(project.id);
const l = d.liveOf(project);
const e = d.statusOf(project);
const suggested = l?.release.next?.ios?.version ?? l?.release.next?.version ?? '';
const [version, setVersion] = useState(suggested);
const [lang, setLang] = useState('');
const ios = !!e?.app?.platforms.ios, android = !!e?.app?.platforms.android;
const okVersion = /^\d+(\.\d+){0,2}$/.test(version);
const only = lang ? { lang } : {};
return (
<Card title={t('act.storeTitle')} icon="upload" sub={t('act.storeSub')}>
<div className="act-grid">
{android && (
<div className="act-col">
<div className="act-head"><StoreGlyph store="android" />Google Play</div>
<WriteButton run={w} icon="text" w={{ method: 'play.listing', args: {}, title: t('act.playListing'), done: t('act.playListingDone') }}>{t('act.playListing')}</WriteButton>
<WriteButton run={w} icon="image" w={{ method: 'play.images', args: {}, title: t('act.playImages'), done: t('act.uploaded') }} hint={t('act.slowHint')}>{t('act.playImages')}</WriteButton>
</div>
)}
{ios && (
<div className="act-col">
<div className="act-head"><StoreGlyph store="ios" />App Store</div>
<div className="row" style={{ gap: 8 }}>
<label className="small muted" htmlFor="act-version">{t('act.version')}</label>
<input id="act-version" className="input input-sm mono" style={{ width: 90 }} value={version} onChange={ev => setVersion(ev.target.value.trim())} placeholder="2.4.0" />
</div>
<WriteButton run={w} icon="text" disabled={!okVersion} w={{ method: 'apple.listing', args: { version }, title: t('act.appleListing', { version }), done: t('act.appleListingDone') }}>{t('act.appleListing', { version: version || '…' })}</WriteButton>
<WriteButton run={w} icon="image" w={{ method: 'apple.screenshots', args: {}, title: t('act.appleShots'), done: t('act.uploaded') }} hint={t('act.slowHint')}>{t('act.appleShots')}</WriteButton>
<WriteButton run={w} icon="play" w={{ method: 'apple.previews', args: {}, title: t('act.applePreviews'), done: t('act.uploaded') }} hint={t('act.slowHint')}>{t('act.applePreviews')}</WriteButton>
</div>
)}
<div className="act-col">
<div className="act-head"><Icon name="wand" />{t('act.render')}</div>
<select className="input input-sm" value={lang} onChange={ev => setLang(ev.target.value)} aria-label={t('act.renderLang')}>
<option value="">{t('act.allLangs')}</option>
{langs.map(x => <option key={x} value={x}>{x}</option>)}
</select>
<WriteButton run={w} icon="image" w={{ method: 'shots.render', args: only, title: t('act.renderShots'), done: t('act.rendered') }} hint={t('act.localHint')}>{t('act.renderShots')}</WriteButton>
<WriteButton run={w} icon="play" w={{ method: 'shots.video', args: only, title: t('act.renderVideo'), done: t('act.rendered') }} hint={t('act.localHint')}>{t('act.renderVideo')}</WriteButton>
<WriteButton run={w} icon="sparkle" w={{ method: 'icons', args: {}, title: t('act.icons'), done: t('act.rendered') }} hint={t('act.localHint')}>{t('act.icons')}</WriteButton>
<WriteButton run={w} icon="layers" w={{ method: 'shots.gallery', args: only, title: t('act.gallery'), done: t('act.galleryDone') }} hint={t('act.localHint')}>{t('act.gallery')}</WriteButton>
</div>
</div>
<p className="small muted act-note"><Icon name="shield" />{t('act.note')}</p>
</Card>
);
}
export function ListingsTab({ project }: { project: Project }) {
const r = useRead<ListingsResult>(project.id, 'project.listings', { network: false });
if (!r.data) {
@ -76,6 +129,7 @@ export function ListingsTab({ project }: { project: Project }) {
<Kpi icon="image" label={t('lst.screenshots')} value={L.locales.some(l => l.screenshots !== null) ? shots : '–'} sub={L.locales.some(l => l.screenshots !== null) ? t('lst.screenshotsSub') : t('lst.noRenders')} />
</div>
{L.problems.map((p, i) => <Notice key={i} tone="warn">{p}</Notice>)}
{!noFiles && <StoreActions project={project} langs={L.locales.map(l => l.lang)} />}
{noFiles ? (
<Card pad={false}>
<Empty illo="text" title={t('lst.noFilesTitle')}>{t('lst.noFilesText')}</Empty>

View file

@ -1,11 +1,13 @@
// 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 ReleaseTrain } from '../../api';
import { useState } from 'react';
import { api, type ReleaseTrain, type StoreRelease } from '../../api';
import type { UnifiedApp } from '../../lib/identity';
import { WriteButton } from '../../ui/WriteButton';
import { type Key, t } from '../../i18n';
import { ago, date, share } from '../../lib/format';
import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model';
import { useData, useRead } from '../../store';
import { useData, useRead, useWrite } from '../../store';
import { Icon, StoreGlyph } from '../../ui/icons';
import { Bar, Card, Chip, Empty, Notice, PhaseChip, storeName } from '../../ui/kit';
import { ascUrl, PLAY_CONSOLE } from '../AppView';
@ -48,7 +50,54 @@ function LaneRow({ lane, version }: { lane: Lane; version: string }) {
);
}
function Train({ title, train, tf, tone }: { title: string; train: ReleaseTrain; tf: TestFlightStatus | null; tone: 'accent' | 'ok' }) {
const SHARES = [1, 2, 5, 10, 20, 50];
/** Rollout controls of one store release: Play staged rollout share / halt / resume / complete, iOS phased release
* pause / resume / everyone, or turning the phased release on for an upcoming iOS version. Owner actions: each one is
* a dry run first, then a system dialog that names it. */
function RolloutControls({ app, r }: { app: UnifiedApp; r: StoreRelease }) {
const w = useWrite(app.project?.id ?? null);
const pct = r.fraction !== null ? Math.round(r.fraction * 100) : null;
const [share, setShare] = useState(() => String(SHARES.find(s => pct === null || s > pct) ?? 50));
if (!app.project) return null;
const v = r.version ?? '';
if (r.store === 'android' && (r.phase === 'rollout' || r.phase === 'halted')) {
const track = r.track && ['production', 'beta', 'alpha', 'internal'].includes(r.track) ? r.track : 'production';
const next = SHARES.filter(s => pct === null || s > pct);
return (
<div className="roll-ctl">
<span className="small muted">{t('roll.playNow', { pct: pct ?? 0 })}</span>
{r.phase === 'rollout' && next.length > 0 && <>
<select className="input input-sm" value={share} onChange={e => setShare(e.target.value)} aria-label={t('roll.share')}>{next.map(s => <option key={s} value={s}>{s} %</option>)}</select>
<WriteButton run={w} icon="arrowRight" w={{ method: 'owner.play_rollout', args: { action: 'percent', percent: Number(share), track }, title: t('roll.toShare', { pct: share }), done: t('roll.done') }}>{t('roll.toShare', { pct: share })}</WriteButton>
</>}
{r.phase === 'rollout' && <WriteButton run={w} icon="pause" w={{ method: 'owner.play_rollout', args: { action: 'halt', track }, title: t('roll.halt'), done: t('roll.halted') }} hint={t('roll.haltHint')}>{t('roll.halt')}</WriteButton>}
{r.phase === 'halted' && <WriteButton run={w} icon="play" w={{ method: 'owner.play_rollout', args: { action: 'resume', track }, title: t('roll.resume'), done: t('roll.done') }}>{t('roll.resume')}</WriteButton>}
<WriteButton run={w} icon="users" w={{ method: 'owner.play_rollout', args: { action: 'complete', track }, title: t('roll.complete'), done: t('roll.done') }} hint={t('roll.completeHint')}>{t('roll.complete')}</WriteButton>
</div>
);
}
if (r.store === 'ios' && r.phased && (r.phased.state === 'ACTIVE' || r.phased.state === 'PAUSED')) {
return (
<div className="roll-ctl">
<span className="small muted">{t('roll.iosNow', { day: r.phased.day ?? 0 })}</span>
{r.phased.state === 'ACTIVE' && <WriteButton run={w} icon="pause" w={{ method: 'owner.ios_phased', args: { action: 'pause', version: v }, title: t('roll.pause'), done: t('roll.paused') }} hint={t('roll.pauseHint')}>{t('roll.pause')}</WriteButton>}
{r.phased.state === 'PAUSED' && <WriteButton run={w} icon="play" w={{ method: 'owner.ios_phased', args: { action: 'resume', version: v }, title: t('roll.resume'), done: t('roll.done') }}>{t('roll.resume')}</WriteButton>}
<WriteButton run={w} icon="users" w={{ method: 'owner.ios_phased', args: { action: 'complete', version: v }, title: t('roll.everyone'), done: t('roll.done') }} hint={t('roll.everyoneHint')}>{t('roll.everyone')}</WriteButton>
</div>
);
}
if (r.store === 'ios' && !r.phased && ['draft', 'review', 'approved'].includes(r.phase) && /^\d+(\.\d+){0,2}$/.test(v)) {
return (
<div className="roll-ctl">
<WriteButton run={w} icon="layers" w={{ method: 'owner.ios_phased', args: { action: 'on', version: v }, title: t('roll.phasedOn'), done: t('roll.phasedOnDone') }} hint={t('roll.phasedOnHint')}>{t('roll.phasedOn')}</WriteButton>
</div>
);
}
return null;
}
function Train({ title, train, tf, tone, app }: { title: string; train: ReleaseTrain; tf: TestFlightStatus | null; tone: 'accent' | 'ok'; app: UnifiedApp }) {
const lanes = trainLanes(train, tf);
return (
<Card pad={false} title={<span className="train-head"><span className="ver">{train.version}</span><Chip tone={tone}>{title}</Chip></span>}
@ -57,6 +106,11 @@ function Train({ title, train, tf, tone }: { title: string; train: ReleaseTrain;
<div className="tl-head"><span>{t('tl.store')}</span>{STAGES.map(s => <span key={s}>{t(STAGE_KEY[s])}</span>)}</div>
{lanes.map(l => <LaneRow key={l.store} lane={l} version={train.version} />)}
</div>
{lanes.some(l => l.release) && app.project && (
<div className="card-foot roll-foot">
{lanes.map(l => l.release && <RolloutControls key={l.store} app={app} r={l.release} />)}
</div>
)}
</Card>
);
}
@ -83,8 +137,8 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) {
return (
<>
{errs.map(([s, msg]) => <Notice key={s} tone="warn">{t('releases.storeUnreadable', { store: storeName(s as 'ios'), error: msg })}</Notice>)}
{l.release.next && <Train title={t('tl.next')} train={l.release.next} tf={tf.data} tone="accent" />}
{l.release.current && <Train title={t('tl.live')} train={l.release.current} tf={tf.data} tone="ok" />}
{l.release.next && <Train title={t('tl.next')} train={l.release.next} tf={tf.data} tone="accent" app={app} />}
{l.release.current && <Train title={t('tl.live')} train={l.release.current} tf={tf.data} tone="ok" app={app} />}
{!l.release.next && !l.release.current && <Card pad={false}><Empty compact illo="unknown" title={t('releases.noVersions')}>{t('releases.noVersionsText')}</Empty></Card>}
<Card title={t('releases.history')} icon="layers" sub={t('releases.historySub', { when: ago(d.live?.at ?? d.portfolio?.at) })} pad={false}>

View file

@ -1,20 +1,31 @@
// Reviews: the inbox of both stores with the star distribution and filters, and per review its local reply draft
// (.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 ReplyDraft } from '../../api';
import { useEffect, useMemo, useState } from 'react';
import type { DraftsResult, 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';
import { useData, useRead } from '../../store';
import { useRead, useWrite } from '../../store';
import { WriteButton } from '../../ui/WriteButton';
import { Icon, StoreGlyph } from '../../ui/icons';
import { Bar, Card, Chip, Empty, Notice, Seg, Skeleton, Stars } from '../../ui/kit';
const base = (f: string) => f.split(/[\\/]/).pop() ?? f;
function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft | undefined; onApprove: (d: ReplyDraft, undo: boolean) => void; busy: boolean }) {
/** Same checks as `reviews send` (cli/lib/reviews.ts checkReply), shown while typing; the CLI checks again. */
const INCENTIVE = [/\b(free|bonus|extra|gift|reward)\b[^.!?\n]{0,40}\b(coins?|gems?|credits?|lives|items?)\b/i, /\b(change|update|raise|edit)\s+(your\s+)?(rating|review|stars?)\b/i, /\b(5|five)[ -]?stars?\b/i, /\b(rate|review)\s+us\b/i];
function Detail({ r, draft, w, onChanged }: { r: Review; draft: ReplyDraft | undefined; w: ReturnType<typeof useWrite>; onChanged: () => void }) {
const errors = draft?.issues.filter(i => i.level === 'error') ?? [];
const [text, setText] = useState(draft?.reply ?? '');
useEffect(() => { setText(draft?.reply ?? ''); }, [draft?.file, draft?.reply]);
const limit = r.store === 'play' ? 350 : 5970;
const len = [...text.trim()].length;
const dirty = !!draft && text.trim() !== draft.reply.trim();
const live = text && INCENTIVE.some(x => x.test(text)) ? t('reviews.incentive') : len > limit ? t('reviews.tooLong', { limit }) : null;
const file = draft ? base(draft.file) : '';
return (
<Card className="rv-detail" title={<span className="row" style={{ gap: 10 }}><Stars n={r.rating} />{r.title || t('reviews.noTitle')}</span>}
sub={<span className="row" style={{ gap: 6 }}><StoreGlyph store={r.store === 'apple' ? 'ios' : 'android'} className="ic13" />{r.store === 'apple' ? 'App Store' : 'Google Play'}{r.where ? ` · ${r.where}` : ''} · {date(r.date)}{r.appVersion ? ` · ${t('reviews.version', { v: r.appVersion })}` : ''}</span>}>
@ -32,25 +43,34 @@ function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft |
<span className="label">{t('reviews.draft')}</span>
{draft && (draft.sent ? <Chip tone="ok">{t('reviews.sentOn', { date: date(draft.sent) })}</Chip> : draft.approved ? <Chip tone="ok" icon="check">{t('reviews.approved')}</Chip> : <Chip tone="neutral">{t('reviews.notApproved')}</Chip>)}
</div>
{!draft ? <p className="muted small">{t('reviews.noDraft')}</p> : (
{!draft ? <p className="muted small">{t('reviews.noDraft')}</p> : draft.sent ? (
<div className="reply-box selectable">{draft.reply}</div>
) : (
<>
{draft.reply ? <div className="reply-box selectable">{draft.reply}</div> : <p className="muted small">{t('reviews.emptyDraft', { file: base(draft.file) })}</p>}
<div className="row small muted" style={{ gap: 10 }}><span className="num">{t('reviews.chars', { n: num([...draft.reply].length), limit: r.store === 'play' ? 350 : 5970 })}</span><span className="mono-id">{base(draft.file)}</span></div>
{draft.issues.length > 0 && (
<textarea className="input reply-edit" rows={5} value={text} onChange={e => setText(e.target.value)} aria-label={t('reviews.replyEditor')} placeholder={t('reviews.replyPlaceholder')} />
<div className="row small muted" style={{ gap: 10 }}>
<span className={`num${len > limit ? ' tbad' : ''}`}>{t('reviews.chars', { n: num(len), limit })}</span><span className="mono-id">{file}</span>
{dirty && <Chip tone="warn" dot={false}>{t('reviews.unsaved')}</Chip>}
</div>
{live && <ul className="issues"><li className="e"><Icon name="alertCircle" />{live}</li></ul>}
{!dirty && draft.issues.length > 0 && (
<ul className="issues">
{draft.issues.map((i, n) => <li key={n} className={i.level === 'error' ? 'e' : 'w'}><Icon name={i.level === 'error' ? 'alertCircle' : 'alert'} />{i.msg}</li>)}
</ul>
)}
{!draft.sent && (
<div className="actions">
{draft.approved
? <button className="btn" onClick={() => onApprove(draft, true)} disabled={busy}>{t('reviews.unapprove')}</button>
: <button className="btn btn-primary" onClick={() => onApprove(draft, false)} disabled={busy || !draft.reply || errors.length > 0} title={errors.length ? t('reviews.fixFirst') : t('reviews.approveHint')}><Icon name="check" />{t('reviews.approve')}</button>}
</div>
)}
<div className="actions">
<WriteButton run={w} icon="check" primary={dirty} disabled={!dirty || !text.trim() || text.trim().startsWith('-') || len > 6000}
w={{ method: 'reviews.reply', args: { file, text: text.trim() }, title: t('reviews.save'), done: t('reviews.saved'), after: onChanged }}>{t('reviews.save')}</WriteButton>
{draft.approved
? <WriteButton run={w} icon="x" disabled={dirty} w={{ method: 'reviews.approve', args: { file, undo: true }, title: t('reviews.unapprove'), done: t('reviews.unapproved'), after: onChanged }}>{t('reviews.unapprove')}</WriteButton>
: <WriteButton run={w} icon="check" disabled={dirty || !draft.reply || errors.length > 0} hint={errors.length ? t('reviews.fixFirst') : t('reviews.approveHint')}
w={{ method: 'reviews.approve', args: { file }, title: t('reviews.approve'), done: t('reviews.approvedToast'), after: onChanged }}>{t('reviews.approve')}</WriteButton>}
<WriteButton run={w} icon="send" primary={draft.approved && !dirty} disabled={!draft.approved || dirty || errors.length > 0} hint={t('reviews.sendHint')}
w={{ method: 'owner.reply_send', args: { file }, title: t('reviews.send'), done: t('reviews.sent'), after: onChanged }}>{t('reviews.send')}</WriteButton>
</div>
</>
)}
<p className="small muted">{t('reviews.sendNote')} <code className="selectable">storebound reviews send</code></p>
<p className="small muted">{t('reviews.sendNoteD3')}</p>
</div>
</div>
</Card>
@ -58,13 +78,12 @@ function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft |
}
export function ReviewsTab({ app }: { app: UnifiedApp }) {
const d = useData();
const project = app.project;
const list = useRead<Review[]>(app.target, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews'), appName: app.name });
const drafts = useRead<DraftsResult>(app.target, 'reviews.drafts', { network: false, skip: !project });
const [f, setF] = useState<ReviewFilter>({ store: 'all', stars: [], unanswered: false, query: '' });
const [sel, setSel] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const w = useWrite(project?.id ?? null);
const all = list.data ?? [];
const stats = useMemo(() => starStats(f.store === 'all' ? all : all.filter(r => r.store === f.store)), [all, f.store]);
@ -72,17 +91,7 @@ export function ReviewsTab({ app }: { app: UnifiedApp }) {
const byFile = useMemo(() => new Map((drafts.data?.drafts ?? []).map(x => [base(x.file), x] as const)), [drafts.data]);
const cur = shown.find(r => `${r.store}:${r.id}` === sel) ?? shown.find(r => !r.reply && byFile.has(draftName(r))) ?? shown[0];
const write = async (method: string, args: Record<string, unknown>, title: string) => {
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) });
else if (o.confirmed) d.toast({ kind: 'bad', title: t('write.failed'), detail: o.result?.output.split('\n').filter(Boolean).at(-1) });
} catch (e) { d.toast({ kind: 'bad', title: t('write.failed'), detail: errorText(e) }); } finally { setBusy(false); }
};
const changed = () => { drafts.refresh(); };
if (!list.data) {
if (list.loading && !list.error) return <Card><Skeleton lines={5} block /></Card>;
@ -100,7 +109,7 @@ export function ReviewsTab({ app }: { app: UnifiedApp }) {
<div className="row between">
<span className="stamp"><Icon name="clock" />{list.fromCache ? t('common.cachedFrom', { when: ago(list.at) }) : t('common.readWhen', { when: ago(list.at) })}</span>
<div className="actions">
<button className="btn btn-sm" onClick={() => write('reviews.draft', { days: 30 }, t('reviews.draftsMade'))} disabled={busy} title={t('reviews.makeDraftsHint')}><Icon name="text" />{t('reviews.makeDrafts')}</button>
{project && <WriteButton run={w} icon="text" hint={t('reviews.makeDraftsHint')} w={{ method: 'reviews.draft', args: { days: 30 }, title: t('reviews.makeDrafts'), done: t('reviews.draftsMade'), after: changed }}>{t('reviews.makeDrafts')}</WriteButton>}
<button className="btn btn-sm" onClick={list.refresh} disabled={list.loading}><Icon name="refresh" />{t('action.refresh')}</button>
</div>
</div>
@ -147,7 +156,7 @@ export function ReviewsTab({ app }: { app: UnifiedApp }) {
</div>
) : <Empty compact illo="reviews" title={t('reviews.noMatch')} />}
</Card>
{cur ? <Detail r={cur} draft={byFile.get(draftName(cur))} busy={busy} onApprove={(dr, undo) => write('reviews.approve', { file: base(dr.file), ...(undo ? { undo: true } : {}) }, undo ? t('reviews.unapproved') : t('reviews.approvedToast'))} />
{cur ? <Detail r={cur} draft={byFile.get(draftName(cur))} w={w} onChanged={changed} />
: <Card className="rv-detail"><Empty compact illo="reviews" title={t('reviews.pick')} /></Card>}
</div>
</>

View file

@ -1,10 +1,12 @@
// TestFlight: beta groups (internal / external, testers, builds, public link) and the recent builds with their
// processing and beta review states.
import { Fragment, useState } from 'react';
import type { UnifiedApp } from '../../lib/identity';
import { WriteButton } from '../../ui/WriteButton';
import { t } from '../../i18n';
import { ago, date, num } from '../../lib/format';
import type { TestFlightStatus, Tone } from '../../lib/model';
import { useData, useRead } from '../../store';
import type { TestFlightStatus, TfBuild, TfGroup, Tone } from '../../lib/model';
import { useData, useRead, useWrite } from '../../store';
import { Icon } from '../../ui/icons';
import { Card, Chip, Empty, Notice, Skeleton } from '../../ui/kit';
@ -23,10 +25,63 @@ function State({ s }: { s: string | null }) {
return s ? <Chip tone={b.tone}>{b.text}</Chip> : <span className="muted small">–</span>;
}
/** One build's "What to Test" and its internal groups: confirm-gated writes (dry run, dialog, apply). */
function BuildEditor({ b, groups, w, mode, onDone }: { b: TfBuild; groups: TfGroup[]; w: ReturnType<typeof useWrite>; mode: 'what' | 'groups'; onDone: () => void }) {
const [text, setText] = useState('');
const internal = groups.filter(g => g.internal);
const [picked, setPicked] = useState<string[]>(internal.map(g => g.name));
const base = { build: b.build ?? '', ...(b.version ? { version: b.version } : {}) };
if (mode === 'what') {
return (
<div className="build-edit">
<label className="small strong" htmlFor={`wtt-${b.build}`}>{t('tf.whatToTest', { build: b.build ?? '' })}</label>
<textarea id={`wtt-${b.build}`} className="input" rows={3} maxLength={4000} value={text} onChange={e => setText(e.target.value)} placeholder={t('tf.whatPlaceholder')} />
<div className="actions">
<WriteButton run={w} icon="check" primary disabled={!text.trim() || text.trim().startsWith('-')} w={{ method: 'apple.testflight_what_to_test', args: { ...base, text: text.trim() }, title: t('tf.whatSave'), done: t('tf.whatSaved'), after: onDone }}>{t('tf.whatSave')}</WriteButton>
<WriteButton run={w} icon="text" w={{ method: 'apple.testflight_what_to_test', args: base, title: t('tf.whatFromFile'), done: t('tf.whatSaved'), after: onDone }} hint={t('tf.whatFromFileHint')}>{t('tf.whatFromFile')}</WriteButton>
</div>
</div>
);
}
return (
<div className="build-edit">
<span className="small strong">{t('tf.toInternal', { build: b.build ?? '' })}</span>
{internal.length ? (
<div className="row" style={{ gap: 14, flexWrap: 'wrap' }}>
{internal.map(g => <label key={g.id} className="check"><input type="checkbox" checked={picked.includes(g.name)} onChange={e => setPicked(p => (e.target.checked ? [...p, g.name] : p.filter(x => x !== g.name)))} />{g.name}</label>)}
</div>
) : <span className="small muted">{t('tf.noInternal')}</span>}
<div className="actions">
<WriteButton run={w} icon="users" primary disabled={!picked.length} w={{ method: 'apple.testflight_distribute', args: { ...base, groups: picked.join(',') }, title: t('tf.distribute'), done: t('tf.distributed'), after: onDone }}>{t('tf.distribute')}</WriteButton>
<span className="small muted">{t('tf.externalNote')}</span>
</div>
</div>
);
}
function Testers({ groups, w }: { groups: TfGroup[]; w: ReturnType<typeof useWrite> }) {
const [group, setGroup] = useState('');
return (
<Card title={t('tf.testersTitle')} icon="users" sub={t('tf.testersSub')}>
<div className="row" style={{ gap: 10, flexWrap: 'wrap' }}>
<select className="input input-sm" value={group} onChange={e => setGroup(e.target.value)} aria-label={t('tf.testersGroup')}>
<option value="">{t('tf.testersAll')}</option>
{groups.map(g => <option key={g.id} value={g.name}>{g.name}</option>)}
</select>
<WriteButton run={w} icon="users" w={{ method: 'owner.testflight_testers', args: group ? { groups: group } : {}, title: t('tf.testersAdd'), done: t('tf.testersDone') }} hint={t('tf.testersHint')}>{t('tf.testersAdd')}</WriteButton>
</div>
<p className="small muted act-note"><Icon name="shield" />{t('tf.testersNote')}</p>
</Card>
);
}
export function TestFlightTab({ app }: { app: UnifiedApp }) {
const d = useData();
const e = d.statusFor(app);
const r = useRead<TestFlightStatus>(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight' });
const w = useWrite(app.project?.id ?? null);
const [open, setOpen] = useState<{ build: string; mode: 'what' | 'groups' } | null>(null);
const writable = !!app.project;
if ((e && !e.app?.platforms.ios) || (!e && !app.project && !app.ios)) return <Card pad={false}><Empty illo="plane" title={t('tf.noIos')}>{t('tf.noIosText')}</Empty></Card>;
if (!r.data) {
if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>;
@ -62,19 +117,31 @@ export function TestFlightTab({ app }: { app: UnifiedApp }) {
<Card title={t('tf.buildsTitle')} icon="cube" sub={t('tf.buildsSub')} pad={false}>
{s.builds.length ? (
<table className="table">
<thead><tr><th>{t('col.version')}</th><th>{t('col.build')}</th><th>{t('tf.processing')}</th><th>{t('tf.internalTesting')}</th><th>{t('tf.externalTesting')}</th><th className="right">{t('tf.uploaded')}</th></tr></thead>
<thead><tr><th>{t('col.version')}</th><th>{t('col.build')}</th><th>{t('tf.processing')}</th><th>{t('tf.internalTesting')}</th><th>{t('tf.externalTesting')}</th><th>{t('tf.uploaded')}</th>{writable && <th className="right"><span className="sr">{t('col.actions')}</span></th>}</tr></thead>
<tbody>
{s.builds.map((b, i) => (
<tr key={i}>
<td className="strong num">{b.version ?? '–'}</td><td className="num">{b.build ?? '–'}</td>
<td><State s={b.processing} /></td><td><State s={b.internal} /></td><td><State s={b.external} /></td>
<td className="right muted">{date(b.uploaded)}</td>
</tr>
))}
{s.builds.map((b, i) => {
const usable = !!b.build && b.processing === 'VALID' && !/EXPIRED/.test(`${b.internal ?? ''}`);
const here = open?.build === b.build ? open.mode : null;
return (
<Fragment key={i}>
<tr>
<td className="strong num">{b.version ?? '–'}</td><td className="num">{b.build ?? '–'}</td>
<td><State s={b.processing} /></td><td><State s={b.internal} /></td><td><State s={b.external} /></td>
<td className="muted">{date(b.uploaded)}</td>
{writable && <td className="right nowrap">{usable && <div className="actions" style={{ justifyContent: 'flex-end' }}>
<button className="btn btn-sm btn-ghost" aria-expanded={here === 'what'} onClick={() => setOpen(here === 'what' ? null : { build: b.build!, mode: 'what' })}><Icon name="text" />{t('tf.what')}</button>
<button className="btn btn-sm btn-ghost" aria-expanded={here === 'groups'} onClick={() => setOpen(here === 'groups' ? null : { build: b.build!, mode: 'groups' })}><Icon name="users" />{t('tf.groupsBtn')}</button>
</div>}</td>}
</tr>
{here && <tr className="edit-row"><td colSpan={7}><BuildEditor b={b} groups={s.groups} w={w} mode={here} onDone={() => { setOpen(null); r.refresh(); }} /></td></tr>}
</Fragment>
);
})}
</tbody>
</table>
) : <Empty compact illo="plane" title={t('tf.noBuilds')} />}
</Card>
{writable && s.groups.length > 0 && <Testers groups={s.groups} w={w} />}
</>
);
}

View file

@ -304,6 +304,38 @@ export interface ReadState<T> {
refresh: () => Promise<void>;
}
export interface WriteRun { method: string; args: Record<string, unknown>; title: string; done: string; after?: () => void }
/**
* Writes of one app folder: dry run, the native dialog that shows it (Apply / Cancel, or the owner action's own
* button), then the real run with a host-minted token. One toast follows it from the dry run to the result, with the
* command's progress lines; Cancel stops it. `busy` is the key of the running write.
*/
export function useWrite(projectId: string | null) {
const d = useData();
const [busy, setBusy] = useState<string | null>(null);
const run = useCallback(async (w: WriteRun) => {
if (!projectId) return null;
const key = `${w.method}:${JSON.stringify(w.args)}`;
const job = newJob(w.method);
setBusy(key);
const tid = d.toast({ id: job, kind: 'job', title: w.title, detail: t('write.dryRunning'), progress: null, job });
try {
const o = await api.writeWithConfirm(w.method, projectId, w.args, job);
if (o.stage === 'dry-run') d.updateToast(tid, { kind: 'bad', title: t('write.dryFailed'), detail: lastLine(o.dryRun.output) || undefined, progress: undefined, job: undefined });
else if (o.stage === 'dialog') d.updateToast(tid, { kind: 'info', title: t('write.notApplied'), detail: t('write.notAppliedDetail'), progress: undefined, job: undefined });
else if (o.result?.ok) { d.updateToast(tid, { kind: 'ok', title: w.done, detail: lastLine(o.result.output) || undefined, progress: undefined, job: undefined }); w.after?.(); }
else d.updateToast(tid, { kind: 'bad', title: t('write.failed'), detail: lastLine(o.result?.output ?? '') || undefined, progress: undefined, job: undefined });
return o;
} catch (e) {
const msg = errorText(e);
d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('write.failed'), detail: msg, progress: undefined, job: undefined });
return null;
} finally { setBusy(null); }
}, [projectId, d]);
return { busy, run, isBusy: (method: string, args: Record<string, unknown> = {}) => busy === `${method}:${JSON.stringify(args)}` };
}
/** 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 ?? '';

View file

@ -748,3 +748,26 @@ h2[tabindex="-1"]:focus, h2[tabindex="-1"]:focus-visible { outline: none; }
.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; }
/* ---- D3 writes: action cards, rollout controls, TestFlight build editors, reply editor ---- */
.act-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; }
.act-col { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 12px 14px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface-2); }
.act-col .btn { width: 100%; justify-content: flex-start; }
.act-col select.input-sm { width: 100%; max-width: none; }
.act-head { display: flex; align-items: center; gap: 8px; font-weight: 650; font-size: var(--t-meta); color: var(--ink-2); margin-bottom: 2px; }
.act-head svg { width: 15px; height: 15px; }
.act-note { display: flex; align-items: flex-start; gap: 8px; margin-top: 12px; }
.act-note svg { width: 14px; height: 14px; flex: none; margin-top: 2px; color: var(--muted); }
.roll-foot { display: grid; gap: 8px; }
.roll-ctl { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.roll-ctl > .small:first-child { min-width: 150px; }
.table tbody tr.edit-row td { background: var(--surface-2); }
.table tbody tr.edit-row:hover td { background: var(--surface-2); }
.build-edit { display: grid; gap: 10px; padding: 4px 0; max-width: 760px; }
textarea.input { height: auto; padding: 8px 10px; line-height: 1.45; resize: vertical; font-family: var(--font); }
.reply-edit { min-height: 110px; }
.table.pf th, .table.pf td { padding-left: 9px; padding-right: 9px; }
.table.pf th:first-child, .table.pf td:first-child { padding-left: 18px; }
.table.pf th:last-child, .table.pf td:last-child { padding-right: 18px; }
.table.pf .cell-app .s { max-width: 200px; }
.table.pf .mini-health .spark { width: 56px; }

View file

@ -0,0 +1,16 @@
// A button that runs one confirm-gated write (dry run -> native dialog -> apply) and spins while it runs.
import type { ReactNode } from 'react';
import type { useWrite, WriteRun } from '../store';
import { Icon, type IconName } from './icons';
export function WriteButton({ w, run, icon, children, primary, danger, disabled, hint, small = true }: {
w: WriteRun; run: ReturnType<typeof useWrite>; icon: IconName; children: ReactNode; primary?: boolean; danger?: boolean; disabled?: boolean; hint?: string; small?: boolean;
}) {
const mine = run.isBusy(w.method, w.args);
return (
<button className={`btn${small ? ' btn-sm' : ''}${primary ? ' btn-primary' : ''}${danger ? ' btn-danger' : ''}`} disabled={disabled || !!run.busy} title={hint} aria-busy={mine || undefined}
onClick={() => { run.run(w); }}>
<Icon name={mine ? 'refresh' : icon} className={mine ? 'spin' : undefined} />{children}
</button>
);
}

View file

@ -23,11 +23,16 @@ export function byAppleLocale(langs: Language[]): Map<string, Language> {
/**
* Asks on the terminal unless --yes. Store actions that are public or irreversible go through this.
* Under `storebound serve` (the desktop sidecar) nothing can answer and nothing may skip the question, not even --yes:
* those actions stay terminal-only, so the answer is always no.
* Under `storebound serve` (the desktop sidecar) nothing can answer and nothing may skip the question, not even --yes,
* so the answer is no. The one exception: a desktop owner action (serve.ts OWNER_TOOLS: rollout changes, the phased
* release, sending one approved reply) whose confirm token the sidecar verified after the owner pressed the button of
* a native dialog showing the dry run; serve sets STOREBOUND_OWNER_CONFIRMED for that one child only.
*/
export async function confirm(ctx: Ctx, question: string): Promise<boolean> {
if (process.env.STOREBOUND_SERVE === '1') { console.error(`confirm-required: ${question}\n terminal only: run it in a terminal`); return false; }
if (process.env.STOREBOUND_SERVE === '1') {
if (process.env.STOREBOUND_OWNER_CONFIRMED === '1') { console.error(`confirmed by the owner in the desktop dialog: ${question}`); return true; }
console.error(`confirm-required: ${question}\n terminal only: run it in a terminal`); return false;
}
if (ctx.args.has('yes')) return true;
if (!process.stdin.isTTY) { console.log(`${question}\n not a terminal: re-run with --yes to confirm`); return false; }
process.stdout.write(`${question} [y/N] `);

View file

@ -29,7 +29,9 @@ export interface MethodDescriptor {
method: string;
title: string;
description: string;
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account';
/** owner: a desktop-only write the owner decides (rollout, phased release, sending one reply); always a dry run
* unless the host's confirm token comes with it, and then the command's own confirmation is answered by that token. */
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account' | 'owner';
/** Talks to a store API or the internet. */
network: boolean;
/** Replaces existing data on a store (screenshots, whole forms). */

View file

@ -172,6 +172,18 @@ export function readReplyDrafts(dir: string): DraftsResult {
return out;
}
/** The "## Reply" section of a draft set to `reply` (everything after the heading is replaced); `approved` goes back
* to false, since an edited reply needs a fresh approval. Sent drafts are not edited. */
export function setReplyText(text: string, reply: string): string {
const { data, body } = parseFrontMatter(text);
if (data.store !== 'apple' && data.store !== 'play') throw new Error('not a review reply draft (front matter "store" missing)');
if (typeof data.sent === 'string' && data.sent) throw new Error('this reply was sent already: edit it in the store console');
const clean = reply.replace(/\r\n?/g, '\n').replace(/<!--[\s\S]*?-->/g, '').trim();
const at = body.search(/^## Reply\s*$/m);
const head = at < 0 ? `${body.trimEnd()}\n\n` : body.slice(0, at);
return stringifyFrontMatter({ ...data, approved: false }, `${head}## Reply\n\n${clean}\n`);
}
/** Front matter `approved: <bool>` set in a draft file text; the body unchanged. */
export function setApproved(text: string, approved: boolean): string {
const { data, body } = parseFrontMatter(text);

View file

@ -39,7 +39,8 @@ export function pickCallEnv(env: Record<string, unknown> | undefined): Record<st
/** Environment of a child: the parent's minus anything secret to the session, plus the per-call values. */
export function childEnv(extra: Record<string, string> = {}, machine = false): Record<string, string> {
const base: Record<string, string> = {};
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION')) base[k] = v;
// never inherited: the session secret, and the owner's confirmation (serve passes it per call, after a verified token)
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION') && k !== 'STOREBOUND_OWNER_CONFIRMED') base[k] = v;
// app-managed tools (desktop data folder) come first on PATH
if (base.STOREBOUND_TOOL_PATH) base.PATH = toolPath(base);
return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) };

View file

@ -4,6 +4,8 @@
// storebound reviews send [--dir .storebound/replies] [--dry] [--yes]
// storebound reviews drafts [--json] the local drafts with the checks `send` applies (offline)
// storebound reviews approve <draft file> [--undo] [--dry] sets approved: true (false) in one draft (local file)
// storebound reviews reply <draft file> --text "..." [--dry] writes the reply of one draft (local file; approval reset)
// storebound reviews send --file <draft file> ... sends that one approved draft only
// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter
// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never
// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets
@ -21,7 +23,7 @@ import {
type Review, sendPlan,
} from './lib/reviews';
import { textTable } from './lib/table';
import { readReplyDrafts, setApproved } from './lib/project-files';
import { readReplyDrafts, setApproved, setReplyText } from './lib/project-files';
import { playClient } from './play/client';
const TAG = 'reviews';
@ -117,7 +119,11 @@ export async function run(ctx: Ctx): Promise<void> {
}
if (sub === 'send') {
const { drafts, texts } = readDrafts(dir);
const { drafts: all, texts } = readDrafts(dir);
const only = a.get('file');
if (only !== undefined && !/^(apple|play)-[A-Za-z0-9._-]{1,120}\.md$/.test(only)) throw new Error('--file: a draft file name in .storebound/replies');
const drafts = only === undefined ? all : all.filter(d => d.file.split(/[\\/]/).pop() === only);
if (only !== undefined && !drafts.length) throw new Error(`no draft ${only} in ${dir}`);
const plan = sendPlan(drafts);
for (const s of plan.skip) log(TAG, `skip ${s.file.split('/').pop()}: ${s.why}`);
for (const d of plan.send) for (const i of checkReply(d.reply, d.store)) warn(TAG, `${d.file.split('/').pop()}: ${i.msg}`);
@ -171,5 +177,20 @@ export async function run(ctx: Ctx): Promise<void> {
done(TAG, `${approved ? 'approved' : 'approval removed'}: ${p} (send with storebound reviews send)`);
return;
}
throw new Error('usage: storebound reviews list | draft | drafts | approve | send');
if (sub === 'reply') {
// writes the reply text of one draft (local file only); an edited reply needs a fresh approval
const file = a.get('file') ?? a._[1];
const text = a.get('text');
if (!file || text === undefined) throw new Error('usage: storebound reviews reply <draft file> --text "..." [--dry]');
const p = resolve(dir, file);
if (relative(dir, p).startsWith('..') || !p.endsWith('.md') || !existsSync(p)) throw new Error(`no draft ${file} in ${dir}`);
const d = parseDraft(p, readFileSync(p, 'utf8'));
const next = setReplyText(readFileSync(p, 'utf8'), text);
for (const i of checkReply(parseDraft(p, next).reply, d.store)) (i.level === 'error' ? warn : log)(TAG, `${file}: ${i.msg}`);
if (a.has('dry')) { done(TAG, `would write the reply (${[...text.trim()].length} characters) into ${p}${d.approved ? ' and reset its approval' : ''} (dry run)`); return; }
writeFileSync(p, next);
done(TAG, `reply saved in ${p}${d.approved ? ' (approval reset: approve it again)' : ''}`);
return;
}
throw new Error('usage: storebound reviews list | draft | drafts | approve | reply | send');
}

View file

@ -58,10 +58,46 @@ export const DESKTOP_ONLY: ToolDef[] = [
description: 'Sets approved: true (or false with undo) in one local reply draft after its checks pass. Nothing is sent: replies go out with `storebound reviews send` in a terminal.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' }, undo: { type: 'boolean', default: false } },
required: ['file'], args: i => [String(i.file), ...(i.undo === true ? ['--undo'] : [])] },
{ name: 'reviews_reply', title: 'Write a reply draft', command: ['reviews', 'reply'], write: true, network: false, idempotent: true,
description: 'Writes the reply text of one local reply draft (.storebound/replies); an edited reply loses its approval. Nothing is sent.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' },
text: { type: 'string', pattern: '^[\\s\\S]{1,6000}$', description: 'The reply (plain text, the reviewer\'s language)' } },
required: ['file', 'text'], args: i => [String(i.file), '--text', String(i.text)] },
{ name: 'project_init', title: 'Start an app folder', command: ['init'], write: true, network: false, idempotent: true,
description: 'Copies the storebound templates (config, listing, screenshot copy, declarations, privacy policy) for a profile into an empty app folder; existing files are kept.',
props: { profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], default: 'app' } }, args: i => ['--profile', String(i.profile ?? 'app')] },
];
/**
* Owner actions (desktop only, kind "owner"): changes the owner decides because users see them at once. Each is a dry
* run unless the host's confirm token comes with it, minted after the owner pressed the button of a native dialog that
* showed that dry run; only then the command's own confirmation is answered (STOREBOUND_OWNER_CONFIRMED for that one
* child). Never: submitting for review, releasing an approved version (--manual-release), cancelling a submission,
* external TestFlight or Beta App Review, removing testers. Those stay in the consoles or the terminal.
*/
export const OWNER_TOOLS: ToolDef[] = [
{ name: 'owner_play_rollout', title: 'Change the Play staged rollout', command: ['play', 'rollout'], write: true, network: true,
description: 'Google Play staged rollout of a track: set the user share (percent), halt it (not a rollback), resume it, or complete it (100 %).',
props: { action: { type: 'string', enum: ['percent', 'halt', 'resume', 'complete'] }, percent: { type: 'integer', minimum: 1, maximum: 99, description: 'User share in percent (action percent, or resume at a new share)' },
track: { type: 'string', enum: ['production', 'beta', 'alpha', 'internal'], default: 'production' } },
required: ['action'],
args: i => [...(i.action === 'halt' ? ['--halt'] : i.action === 'resume' ? ['--resume'] : i.action === 'complete' ? ['--complete'] : []),
...(i.percent !== undefined && (i.action === 'percent' || i.action === 'resume') ? ['--fraction', String(Number(i.percent) / 100)] : []), '--track', String(i.track ?? 'production')] },
{ name: 'owner_ios_phased', title: 'Change the App Store phased release', command: ['apple', 'release'], write: true, network: true,
description: 'The 7-day phased release of an App Store version: turn it on, pause it (not a rollback), resume it, or release to everyone now (complete).',
props: { action: { type: 'string', enum: ['on', 'pause', 'resume', 'complete'] }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } },
required: ['action'], args: i => ['--phased', String(i.action), ...(i.version ? ['--version', String(i.version)] : [])] },
{ name: 'owner_reply_send', title: 'Send one approved reply', command: ['reviews', 'send'], write: true, network: true,
description: 'Sends one approved, unsent reply draft (.storebound/replies) to its store: public, the reviewer is notified. The draft checks (length, no incentives) apply.',
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' } },
required: ['file'], args: i => ['--file', String(i.file)] },
{ name: 'owner_testflight_testers', title: 'Add TestFlight testers', command: ['apple', 'testflight', 'testers'], write: true, network: true,
description: 'Adds the testers of the project\'s testers CSV (.storebound/testers.csv, gitignored) to their TestFlight groups; Apple emails them an invitation once the group has a build. Emails stay masked in every line. Removing testers stays a terminal command.',
props: { groups: { type: 'string', pattern: '^[^,;]{1,60}(,[^,;]{1,60}){0,19}$', description: 'Comma-separated group names (default: every group in the CSV)' } },
args: i => (i.groups ? ['--group', String(i.groups)] : []) },
];
/** Flags no owner action may ever produce. */
export const OWNER_FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--submit-review', '--remove', '--invite', '--production', '--csv', 'submit', 'publish', 'distribute'];
/** Desktop-only methods whose `project` is a folder without a config yet. */
const NEW_PROJECT = new Set(['project_init']);
@ -69,7 +105,8 @@ const NEW_PROJECT = new Set(['project_init']);
export const methodName = (tool: string): string => tool.replace('_', '.');
export const DESKTOP_TOOLS: ToolDef[] = [...TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)), ...DESKTOP_ONLY];
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const));
const OWNER = new Set(OWNER_TOOLS.map(t => t.name));
const byMethod = new Map([...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => [methodName(t.name), t] as const));
function argsSchema(t: ToolDef): MethodDescriptor['args'] {
const s = inputSchema(t) as MethodDescriptor['args'];
@ -103,8 +140,8 @@ const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/;
const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;
export function describeMethods(): MethodDescriptor[] {
return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({
method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const,
return [...SYSTEM, ...[...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => ({
method: methodName(t.name), title: t.title, description: t.description, kind: OWNER.has(t.name) ? 'owner' as const : t.write ? 'write' as const : 'read' as const,
network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t),
}))];
}
@ -295,6 +332,11 @@ export class Session {
const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) });
const json = !t.write && JSON_TOOLS.has(t.name);
const argv = json ? [...built.argv, '--json'] : built.argv;
if (OWNER.has(t.name)) {
if (argv.some(a => OWNER_FORBIDDEN_ARGS.includes(a))) throw new RpcError(ERR.invalidParams, `${method}: not an owner action from here`);
// the verified token is the owner's answer to the command's own question; nothing else can set it
if (!dryRun) env.STOREBOUND_OWNER_CONFIRMED = '1';
}
const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) }));
const res = await r.result;
if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');

View file

@ -25,8 +25,15 @@ Types of the protocol: `cli/lib/desktop-protocol.ts`; pure portfolio logic: `cli
the sidecar's stdin. Write methods are dry runs unless the call carries a confirm token: HMAC-SHA256 over the
method, the canonical `{ project, args }` and a 60 s expiry, single use. The host mints one only after the owner
pressed Apply in a native dialog that shows the summary and the dry run (`write_with_confirm`).
- No method submits for review, releases, publishes, resumes or completes a rollout. Under `serve`, the CLI's own
terminal confirmations always answer no.
- No method submits for review, releases an approved version, publishes, cancels a submission, sends a build to
external testers or removes testers. Under `serve`, the CLI's own terminal confirmations answer no, with one
exception: the **owner actions** (`owner.play_rollout` share / halt / resume / complete, `owner.ios_phased`
on / pause / resume / complete, `owner.reply_send` one approved draft, `owner.testflight_testers` adds the testers
of `.storebound/testers.csv`). They are desktop-only (never MCP tools), dry runs from the window like every write,
and their real run needs the host token. Only then serve sets `STOREBOUND_OWNER_CONFIRMED` for that one child,
which answers the command's question. The native dialog names the action on its button ("Yes: Change the Play
staged rollout"). `tests/desktop-d3.test.ts` and `src-tauri/tests/d3_writes.rs` pin the token binding of every
write the window offers.
- The webview gets no plugin API. It may call the app commands (each re-checks the window label and the page origin
in Rust) and listen to two events. Strict CSP, no remote content. `src-tauri/tests/security.rs` pins all of it.
- Store keys (Play service account JSON, App Store Connect key id, issuer id and .p8) are picked in native dialogs,
@ -61,6 +68,84 @@ Types of the protocol: `cli/lib/desktop-protocol.ts`; pure portfolio logic: `cli
(CI) checks keys, empty messages and placeholders. **Theme**: text tokens keep 7:1 contrast in both themes
(`tests/theme.test.ts`), motion at most 200 ms and off with reduced motion.
## Studios, accounts and store-only apps (D3)
### Accounts and studios
- A **studio** is a name, a colour and an optional logo. It groups any number of store accounts:
- a Play service account, which can be invited to several Play developer accounts and then sees all their apps;
- an App Store Connect team key, one per team.
- Keys stay in the keychain. The state file keeps labels and studio ids only.
- `storebound apps check` gives each account's health, with the fix in words:
- ok;
- no-apps;
- permission (Play: "invite <service account> in Play Console > Users and permissions with ...");
- revoked;
- api-disabled.
- `storebound apps list` reads the apps an account can see:
- App Store Connect: `GET /v1/apps`, the newest version, and an icon from the newest build's `iconAssetToken`,
fetched by the CLI and returned as a data URL;
- Play: the Reporting API `apps:search`.
- Serve exposes both as `apps.list` and `account.check` (kind `account`, one account's key per call, run in an
empty temp folder). The host caches app lists under `acct:<id>`.
### One card per app
`src/lib/identity.ts` builds one card per app, pure and tested:
1. A folder takes the store apps its config names. Order: an explicit link, then the App Store app id, then the
bundle id or package name. The folder's mapped accounts win.
2. The remaining store apps pair iOS + Android, in this order:
- manual pairs;
- the same id;
- a close id (`.ios` / `.android` suffixes, case, punctuation);
- the same name.
Unpairs block automatic pairs.
3. What is left is a single-store app.
Overrides (pairs, unpairs, links, studio moves, the ignore list of apps, folders and whole accounts) live in the
host state file (`overrides_set`, every key checked in `workspace.rs`).
### Store-only apps
- A store-only app has no folder. It is read through a **store target**:
`store:ios:<account>:<app id>:<bundle>;android:<account>:<package>`.
- The host checks the target and the account kinds, and passes `virtual: { name, apple, play }`. The sidecar writes
a minimal `storebound.config.json` (store ids, placeholder links) into its temp folder.
- Only `apple.status`, `play.status`, `health`, `reviews.list`, `apple.testflight_status` and `apple.ppo_status` work
this way, and `portfolio.status` takes store-only entries.
- "Link a folder" or "Start an app folder here" turn it into a full app.
### Settings
- Studios and accounts.
- Pairing and the ignore list.
- Store reads: on launch, every 15 min to 12 h (off by default), apps at a time 1-8, icons.
- Offline cache: size, keep 7 / 30 / 90 / 365 days or always, clear.
- Language, theme and motion.
- Notifications, after a read, never on the first one: review / release state changes, new 1-2 star reviews, crash
or ANR over the Play threshold.
- Dependencies and the CLI sidecar.
- Privacy, with a button that reveals the data folder.
- Shortcuts.
- Update channel (placeholder until the updater ships).
- Reset: native confirmation, then the keychain entries and every saved state are removed.
### Writes in the window
Each write is a dry run, then the native dialog, then the real run, with one progress toast and Cancel:
- **Listings tab:** Play listing text, App Store version and text, Play graphics, App Store screenshots and
previews; local render jobs (screenshots, previews, icons, gallery).
- **Catalog tab:** Play products and subscriptions, App Store IAPs and subscriptions, price export. Price import
stays a terminal step.
- **Releases tab:** rollout and phased release owner actions.
- **TestFlight tab:** What to Test, internal groups, testers.
- **Reviews tab:** reply editor (`reviews.reply`), approve, send (owner action).
R&D on a fastlane importer and a RevenueCat adapter: `docs/research/fastlane-revenuecat.md`.
## Dependencies screen
storebound needs no local tool for store work. Screenshots, app previews, icons and captures use:

View file

@ -0,0 +1,110 @@
# R&D: a fastlane importer and a RevenueCat adapter
Two questions for after desktop D3. Facts come from the official docs linked in each section; the
recommendations are ours.
## 1. `storebound import fastlane`
**What fastlane keeps on disk**
- **deliver (App Store)**, under `fastlane/metadata/`
([docs.fastlane.tools/actions/deliver](https://docs.fastlane.tools/actions/deliver/)):
- One folder per language: `name.txt`, `subtitle.txt`, `description.txt`, `keywords.txt`, `promotional_text.txt`,
`release_notes.txt`, `support_url.txt`, `marketing_url.txt`, `privacy_url.txt`.
- Non-localized files at the root: `copyright.txt`, `primary_category.txt`, `secondary_category.txt` and the
sub-category files.
- `review_information/`: `first_name.txt`, `last_name.txt`, `phone_number.txt`, `email_address.txt`,
`demo_user.txt`, `demo_password.txt`, `notes.txt`.
- A `default/` folder that fills any language without its own files.
- Screenshots and app previews in one folder per language. The device comes from the image size or the file name.
- **supply (Google Play)**, under `fastlane/metadata/android/<locale>/`
([docs.fastlane.tools/actions/supply](https://docs.fastlane.tools/actions/supply/)):
- `title.txt`, `short_description.txt`, `full_description.txt`, `video.txt`.
- `changelogs/<versionCode>.txt` and `changelogs/default.txt`.
- `images/`: `icon`, `featureGraphic`, `promoGraphic`, `tvBanner`, plus `phoneScreenshots/`, `sevenInchScreenshots/`
and `tenInchScreenshots/`.
- **Appfile / Deliverfile / Fastfile** are Ruby:
- `app_identifier`, `apple_id`, `team_id` / `itc_team_id`, `json_key_file`, `package_name`.
- Deliverfile options such as `languages`, `submit_for_review`, `automatic_release`, `phased_release`,
`price_tier`, `app_rating_config_path`.
**What an importer would do.** It would only read, it would never run Ruby, and it would write with `--dry` first.
1. **Store ids.** Parse the simple `key("value")` / `key "value"` lines of `Appfile` and `Deliverfile` with a strict
regex. That gives `apple.bundleId`, `play.packageName` and the languages. Ruby logic (conditionals, `ENV[...]`,
lanes) is reported as "set by hand", never guessed.
2. **Languages.** Join the deliver locales and the supply locales into storebound `languages[]` (`apple`, `play` codes).
3. **Listing text.**
- Write `store/appstore.md` and `store/listing.md` from the `.txt` files, mapping `default/` into every language
that lacks a file.
- The newest `changelogs/<versionCode>.txt` becomes `whatsNew`.
- Check lengths against the store limits (`storebound check`).
4. **Art.** Copy or link the screenshot folders into the renders layout (per language and size), or list them as
`shots.frames` when they look like raw captures. The supply icon and feature graphic go to the configured paths.
5. **Secrets and personal data.**
- `json_key_file` and `review_information/*` (contact, demo user and password) go to
`.storebound/credentials.json`, which is gitignored, and never to the config (AGENTS.md rules 4 and 9).
- The importer prints that it moved them, masked.
6. **Not imported, with a note:**
- Submission and release flags (`submit_for_review`, `automatic_release`). storebound never submits.
- `price_tier`. Prices live in the products / CSV flow.
- The age rating config (answered with the owner in `store-declarations`).
- Fastfile lanes.
**Worth it? Yes.** fastlane is the most common existing setup, and its metadata folder maps almost one to one onto
storebound's listing files. A read-only importer gives a migration path that keeps the store text, the screenshots
and the credentials layout in a few seconds, and a dry run shows exactly what lands where.
**Effort:** about 2 to 3 days with tests on fixture folders: an Appfile / Deliverfile line parser, the two metadata
walkers, a dry-run report, and the `.storebound/` hand-off. Ship it as `storebound import fastlane [--dir fastlane]
[--dry]`, then as an "Import from fastlane" choice in the desktop first-run guide.
## 2. A RevenueCat adapter
**What the API offers.** RevenueCat REST API v2 lives at `https://api.revenuecat.com/v2`. It uses Bearer v2 secret
keys with per-endpoint permissions, set in the project settings ([revenuecat.com/docs/api-v2](https://www.revenuecat.com/docs/api-v2)).
It covers:
- Apps.
- Products: `/projects/{project_id}/products`.
- Entitlements, with `.../entitlements/{entitlement_id}/actions/attach_products`.
- Offerings and Packages.
So the RevenueCat catalog can be created and kept in sync by API.
**What storebound already replaces.** The store-side catalog: one product and subscription list in the config,
created and priced on both stores (`play products / subscriptions`, `apple iap / subscriptions`, the regional price
CSV), with cross-store parity (`catalog diff`). Teams that use RevenueCat only as a way to "set up the products"
don't need it for that.
**What storebound cannot replace.**
- Runtime receipt and purchase-token validation.
- Entitlement state per user, server notifications (App Store Server Notifications, Play RTDN).
- Renewals, grace periods, refunds, customer history, paywall experiments and charts.
- The client SDKs.
All of that runs on a server, against live users. It is outside a release tool, and storebound should not try.
**What an optional adapter could do:** `storebound revenuecat sync [--dry]`.
- Key: `REVENUECAT_API_KEY` (v2 secret) and project id, from the environment or `.storebound/` only.
- Source of truth: the storebound catalog. For every config product or subscription id and each store:
1. Create the RevenueCat product (store identifier, app id, type).
2. Create the entitlements named in a new optional config field (`products[].entitlements: ['pro']`) and attach
the products.
3. Optionally create one default offering whose packages map to the subscriptions (`$rc_monthly` / `$rc_annual`
by period).
- Idempotent: match by store identifier. A dry-run diff comes first, as with every storebound write. Nothing is
deleted.
- Read-only parity: show "missing in RevenueCat" in `catalog diff` and in the desktop Catalog tab.
**Recommendation.** Build the fastlane importer first: it is the migration path and the bigger win.
Make RevenueCat a small, optional adapter later, scoped to catalog sync (products, entitlements, a default offering)
plus parity in `catalog diff`. Market it as "keep RevenueCat in step with the stores", not as a replacement:
- storebound owns the store-side catalog and the release.
- RevenueCat (or the app's own server) owns runtime entitlements.
Do not add webhooks, customers or any runtime data, so storebound stays a local tool with no server and no user data.

171
tests/desktop-d3.test.ts Normal file
View file

@ -0,0 +1,171 @@
// Desktop D3 write actions: every write the window offers is a dry run unless the host's confirm token for exactly
// that method, project and arguments comes with it (single use, short-lived); owner actions (rollout share, phased
// release, sending one approved reply) additionally answer the command's own confirmation, and only with such a token.
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { mint } from '../cli/lib/confirm-token';
import { confirm } from '../cli/lib/ctx';
import { ERR } from '../cli/lib/desktop-protocol';
import { parseDraft } from '../cli/lib/reviews';
import { setReplyText } from '../cli/lib/project-files';
import { childEnv, type RunOptions, type Running } from '../cli/lib/runner';
import { TOOLS } from '../cli/mcp-tools';
import { describeMethods, methodName, OWNER_FORBIDDEN_ARGS, OWNER_TOOLS, Session } from '../cli/serve';
import { toArgv } from '../cli/mcp-tools';
type J = Record<string, unknown>;
const DEMO = join(import.meta.dir, '..', 'examples', 'demo-game');
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => (i + 7).toString(16).padStart(2, '0')).join('');
const SECRET = Buffer.from(SECRET_HEX, 'hex');
async function session(now = () => Date.now()) {
const calls: { argv: string[]; o: RunOptions }[] = [];
const run = (argv: string[], o: RunOptions): Running => { calls.push({ argv, o }); return { result: Promise.resolve({ code: 0, out: 'done', cancelled: false }), cancel: () => {} }; };
const s = new Session(() => {}, run, now);
let id = 0;
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))! as J;
await call('session.hello', { secret: SECRET_HEX });
return { calls, call };
}
const err = (r: J) => r.error as { code: number; data?: J };
/** The writes the D3 screens offer, with arguments as the window sends them. */
const D3_WRITES: [string, J][] = [
['play.listing', {}], ['apple.listing', { version: '2.4.0' }], ['play.images', { only: 'en-US' }], ['apple.screenshots', {}], ['apple.previews', {}],
['play.products', {}], ['apple.iap', {}], ['play.subscriptions', {}], ['apple.subscriptions', {}],
['apple.testflight_distribute', { build: '52', groups: 'Studio team' }], ['apple.testflight_what_to_test', { build: '52', text: 'New combo meter' }],
['reviews.reply', { file: 'play-r-p1.md', text: 'Thanks! The fix is in 2.4.0.' }], ['reviews.approve', { file: 'play-r-p1.md' }],
['shots.render', {}], ['shots.video', {}], ['shots.gallery', {}], ['icons', {}],
['owner.play_rollout', { action: 'percent', percent: 50 }], ['owner.play_rollout', { action: 'halt' }], ['owner.ios_phased', { action: 'pause', version: '2.3.0' }],
['owner.ios_phased', { action: 'resume' }], ['owner.reply_send', { file: 'play-r-p1.md' }], ['owner.testflight_testers', { groups: 'Friends and family' }],
];
describe('D3 writes: token binding for every method the window offers', () => {
for (const [method, args] of D3_WRITES) {
test(`${method} ${JSON.stringify(args)}`, async () => {
let now = 1_000_000;
const s = await session(() => now);
const p = { project: DEMO, args };
// dry run by default, and without a token
const dry = await s.call(method, p);
expect(err(dry)).toBeUndefined();
expect(s.calls.at(-1)!.argv).toContain('--dry');
expect(s.calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
expect(err(await s.call(method, { ...p, dryRun: false })).code).toBe(ERR.confirmRequired);
// a token for other arguments, another method or another project is refused
const other = method === 'play.listing' ? 'play.images' : 'play.listing';
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, other, p, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, method, { project: '/elsewhere', args }, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(SECRET, method, { project: DEMO, args: { ...args, x: 1 } }, { now }) })).code).toBe(ERR.confirmInvalid);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: mint(Buffer.alloc(32, 1), method, p, { now }) })).code).toBe(ERR.confirmInvalid);
// the right token runs it for real, once
const n = s.calls.length;
const token = mint(SECRET, method, p, { now });
const real = await s.call(method, { ...p, dryRun: false, confirmToken: token, credentials: { PLAY_SERVICE_ACCOUNT: '{}' } });
expect(err(real)).toBeUndefined();
expect((real.result as J).dryRun).toBe(false);
const c = s.calls.at(-1)!;
expect(s.calls.length).toBe(n + 1);
expect(c.argv).not.toContain('--dry');
expect(c.o.env?.PLAY_SERVICE_ACCOUNT).toBe('{}');
expect(c.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe(method.startsWith('owner.') ? '1' : undefined);
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: token })).data).toEqual({ reason: 'replayed' });
// and expires
const late = mint(SECRET, method, p, { now, ttlMs: 1000 });
now += 1000;
expect(err(await s.call(method, { ...p, dryRun: false, confirmToken: late })).data).toEqual({ reason: 'expired' });
});
}
});
describe('owner actions', () => {
test('exactly these, desktop only, kind owner, never a submit / release request / cancel / external TestFlight flag', () => {
expect(OWNER_TOOLS.map(t => methodName(t.name)).sort()).toEqual(['owner.ios_phased', 'owner.play_rollout', 'owner.reply_send', 'owner.testflight_testers']);
for (const t of OWNER_TOOLS) expect(TOOLS.some(x => x.name === t.name)).toBe(false);
const ds = describeMethods().filter(m => m.method.startsWith('owner.'));
for (const d of ds) expect(d.kind).toBe('owner');
const samples: J[] = [
{ action: 'percent', percent: 5 }, { action: 'halt' }, { action: 'resume', percent: 10 }, { action: 'complete', track: 'beta' },
{ action: 'on' }, { action: 'pause', version: '1.2.3' }, { action: 'resume' }, { action: 'complete' }, { file: 'apple-123.md' }, {}, { groups: 'Studio team,Friends' },
];
for (const t of OWNER_TOOLS) for (const s of samples) {
let argv: string[];
try { argv = toArgv(t, s).argv; } catch { continue; }
for (const a of argv) expect(OWNER_FORBIDDEN_ARGS).not.toContain(a);
}
});
test('argv: rollout share in percent -> fraction, halt / resume / complete, track; phased actions; one reply', () => {
const t = (name: string) => OWNER_TOOLS.find(x => x.name === name)!;
expect(toArgv(t('owner_play_rollout'), { action: 'percent', percent: 20, dry_run: false }).argv).toEqual(['play', 'rollout', '--fraction', '0.2', '--track', 'production']);
expect(toArgv(t('owner_play_rollout'), { action: 'halt' }).argv).toEqual(['play', 'rollout', '--halt', '--track', 'production', '--dry']);
expect(toArgv(t('owner_play_rollout'), { action: 'resume', percent: 50, dry_run: false }).argv).toEqual(['play', 'rollout', '--resume', '--fraction', '0.5', '--track', 'production']);
expect(toArgv(t('owner_play_rollout'), { action: 'complete', percent: 50, track: 'beta', dry_run: false }).argv).toEqual(['play', 'rollout', '--complete', '--track', 'beta']);
expect(toArgv(t('owner_ios_phased'), { action: 'resume', version: '2.3.0', dry_run: false }).argv).toEqual(['apple', 'release', '--phased', 'resume', '--version', '2.3.0']);
expect(toArgv(t('owner_reply_send'), { file: 'play-r1.md', dry_run: false }).argv).toEqual(['reviews', 'send', '--file', 'play-r1.md']);
expect(toArgv(t('owner_testflight_testers'), { groups: 'Studio team', dry_run: false }).argv).toEqual(['apple', 'testflight', 'testers', '--group', 'Studio team']);
expect(toArgv(t('owner_testflight_testers'), {}).argv).toEqual(['apple', 'testflight', 'testers', '--dry']);
});
test('bad arguments never reach a command', async () => {
const s = await session();
for (const [m, args] of [['owner.play_rollout', { action: 'manual' }], ['owner.play_rollout', { action: 'percent', percent: 100 }], ['owner.play_rollout', { action: 'percent', percent: 0.5 }],
['owner.ios_phased', { action: 'release' }], ['owner.ios_phased', { action: 'on', version: '--manual-release' }], ['owner.reply_send', { file: '../../etc/passwd' }],
['owner.reply_send', {}], ['reviews.reply', { file: 'play-1.md', text: '--yes' }], ['reviews.reply', { file: 'play-1.md', text: 'x'.repeat(6001) }]] as [string, J][])
expect(err(await s.call(m, { project: DEMO, args })).code).toBe(ERR.invalidParams);
expect(s.calls.length).toBe(0);
});
});
describe('the owner flag', () => {
const saved = { ...process.env };
afterEach(() => { for (const k of ['STOREBOUND_SERVE', 'STOREBOUND_OWNER_CONFIRMED']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
const ctx = { loaded: {} as never, args: { has: (n: string) => n === 'yes', get: () => undefined, str: (_: string, d: string) => d, num: (_: string, d: number) => d, list: () => [], _: [] } };
test('under serve: no by default, even with --yes; yes only with the owner flag', async () => {
process.env.STOREBOUND_SERVE = '1';
delete process.env.STOREBOUND_OWNER_CONFIRMED;
expect(await confirm(ctx, 'Resume?')).toBe(false);
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect(await confirm(ctx, 'Resume?')).toBe(true);
});
test('a child never inherits it; it comes only per call', () => {
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect(childEnv({}, true).STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
expect(childEnv({ STOREBOUND_OWNER_CONFIRMED: '1' }, true).STOREBOUND_OWNER_CONFIRMED).toBe('1');
});
});
describe('reply drafts: write the reply', () => {
const draft = ['---', 'store: play', 'review_id: r-p1', 'rating: 2', 'approved: true', 'sent: null', '---', '# ★★☆☆☆ Crashes', '', '> Game closes at a 20x combo.', '', '## Reply', '',
'<!-- Write the reply below. -->', '', 'Old text', ''].join('\n');
test('replaces the reply, keeps the review, resets the approval', () => {
const next = setReplyText(draft, ' Sorry! Fixed in 2.4.0.\r\nThanks for the level number. ');
const d = parseDraft('/x/play-r-p1.md', next);
expect(d.reply).toBe('Sorry! Fixed in 2.4.0.\nThanks for the level number.');
expect(d.approved).toBe(false);
expect(next).toContain('> Game closes at a 20x combo.');
expect(next).not.toContain('Old text');
expect(parseDraft('/x', setReplyText(next, 'Again <!-- hidden -->')).reply).toBe('Again');
});
test('sent drafts and other files are not edited', () => {
expect(() => setReplyText(draft.replace('sent: null', 'sent: 2026-10-01T00:00:00Z'), 'x')).toThrow();
expect(() => setReplyText('# not a draft', 'x')).toThrow();
});
test('CLI: reviews reply writes one draft, dry run first', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sb-reply-'));
const cfg = readFileSync(join(DEMO, 'storebound.config.ts'), 'utf8');
writeFileSync(join(dir, 'storebound.config.ts'), cfg);
const replies = join(dir, '.storebound', 'replies');
await Bun.$`mkdir -p ${replies}`.quiet();
writeFileSync(join(replies, 'play-r-p1.md'), draft);
const cli = join(import.meta.dir, '..', 'cli', 'index.ts');
const dry = await Bun.$`bun ${cli} reviews reply play-r-p1.md --text ${'New reply'} --dry`.cwd(dir).quiet().nothrow();
expect(dry.exitCode).toBe(0);
expect(readFileSync(join(replies, 'play-r-p1.md'), 'utf8')).toBe(draft);
const real = await Bun.$`bun ${cli} reviews reply play-r-p1.md --text ${'New reply'}`.cwd(dir).quiet().nothrow();
expect(real.exitCode).toBe(0);
expect(parseDraft('x', readFileSync(join(replies, 'play-r-p1.md'), 'utf8'))).toMatchObject({ reply: 'New reply', approved: false });
const outside = await Bun.$`bun ${cli} reviews reply ../../x.md --text y`.cwd(dir).quiet().nothrow();
expect(outside.exitCode).not.toBe(0);
});
});

View file

@ -6,7 +6,7 @@ import { canonical, mac, MAX_TTL_MS, mint, parseSecret, TokenGuard } from '../cl
import { ERR } from '../cli/lib/desktop-protocol';
import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner';
import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools';
import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve';
import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, OWNER_TOOLS, Session } from '../cli/serve';
import { buildOne, hostTarget, leaks } from '../tools/build-sidecars';
type J = Record<string, unknown>;
@ -86,7 +86,13 @@ describe('confirm tokens', () => {
describe('serve --stdio: methods', () => {
test('nothing submits, releases or publishes', () => {
const names = describeMethods().map(m => m.method);
for (const n of names) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS);
// the owner actions (rollout share, phased release, sending one approved reply: tests/desktop-d3.test.ts) are the
// only methods with those words, all under "owner.", and none submits, publishes, cancels, deletes or invites
const owner = describeMethods().filter(m => m.kind === 'owner').map(m => m.method);
expect(owner.sort()).toEqual(OWNER_TOOLS.map(t => methodName(t.name)).sort());
for (const n of owner) expect(n.startsWith('owner.')).toBe(true);
for (const n of names.filter(x => !owner.includes(x))) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS);
for (const n of names) expect(n).not.toMatch(/submit|publish|cancel|delete|remove|invite|manual/i);
for (const n of ['apple.submit', 'apple.release', 'play.release', 'play.release_testing', 'apple.phased_release', 'play.rollout', 'reviews.send', 'apple.ppo_start', 'prices.import'])
expect(names).not.toContain(n);
// every desktop tool still goes through the MCP rules: no forbidden flag can come out of any of them

View file

@ -104,7 +104,7 @@ describe('account health', () => {
expect(appleCheck({ error: new Error('fetch failed') }).status).toBe('error');
});
test('Play: ok, not invited (0 apps), API off, revoked key, missing permission; the hint names the service account', () => {
const who = 'storebound@example-project.iam.gserviceaccount.com';
const who = 'play-bot@example.com';
expect(playCheck(who, { apps: 2 })).toMatchObject({ status: 'ok', apps: 2, principal: who });
const none = playCheck(who, { apps: 0 });
expect(none.status).toBe('permission');
@ -140,7 +140,7 @@ describe('storebound apps (CLI functions, mocked HTTP)', () => {
test('apple: list with icons, check', async () => {
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
process.env.ASC_KEY_ID = 'ABCDE12345';
process.env.ASC_ISSUER_ID = '00000000-0000-4000-8000-000000000000';
process.env.ASC_ISSUER_ID = '00000000-0000-0000-0000-000000000000';
process.env.ASC_P8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
const get = ascGet([]);
const seen = mockFetch(url => {
@ -167,7 +167,7 @@ describe('storebound apps (CLI functions, mocked HTTP)', () => {
});
test('play: token exchange, apps:search, check; no apps = not invited', async () => {
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example-project.iam.gserviceaccount.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
let apps: unknown[] = PLAY_SEARCH_2.apps;
const seen = mockFetch(url => {
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'ya29.test', expires_in: 3600 });
@ -177,7 +177,7 @@ describe('storebound apps (CLI functions, mocked HTTP)', () => {
const r = await listApps('play', root, false);
expect(r.apps.map(a => a.id)).toEqual(['com.example.ledger']);
expect(seen.some(s => s.startsWith('POST https://oauth2.googleapis.com/token'))).toBe(true);
expect(await checkAccount('play', root)).toMatchObject({ status: 'ok', principal: 'sb@example-project.iam.gserviceaccount.com' });
expect(await checkAccount('play', root)).toMatchObject({ status: 'ok', principal: 'sb@example.com' });
apps = [];
expect((await checkAccount('play', root)).status).toBe('permission');
});
@ -194,8 +194,8 @@ async function session(reply: (argv: string[], o: RunOptions) => { code?: number
await call('session.hello', { secret: SECRET_HEX });
return { calls, call };
}
const PLAY = { PLAY_SERVICE_ACCOUNT: '{"client_email":"x@example.com","private_key":"-----BEGIN PRIVATE KEY-----"}' };
const APPLE = { ASC_KEY_ID: 'ABCDE12345', ASC_ISSUER_ID: '00000000-0000-4000-8000-000000000000', ASC_P8: '-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----' };
const PLAY = { PLAY_SERVICE_ACCOUNT: JSON.stringify({ client_email: 'x@example.com', private_key: '-----BEGIN PRIVATE KEY-----' }) };
const APPLE = { ASC_KEY_ID: 'ABCDE12345', ASC_ISSUER_ID: '00000000-0000-0000-0000-000000000000', ASC_P8: '-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----' };
describe('serve: account methods', () => {
test('described as kind "account", network reads', () => {