From f47c00bed0b335a255e393a73e4349bf96a9d79e Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 04:19:47 +0800 Subject: [PATCH 1/4] D3 writes: owner actions (Play rollout share / halt / resume / complete, iOS phased release, send one approved reply) answer the command's confirmation only with a verified host token; reviews reply edits a draft; native dialog names owner actions; token binding tests for every write the window offers --- apps/desktop/src-tauri/src/commands.rs | 37 +++-- apps/desktop/src-tauri/src/policy.rs | 6 +- apps/desktop/src-tauri/tests/d3_writes.rs | 60 ++++++++ cli/lib/ctx.ts | 11 +- cli/lib/desktop-protocol.ts | 4 +- cli/lib/project-files.ts | 12 ++ cli/lib/runner.ts | 3 +- cli/reviews.ts | 27 +++- cli/serve.ts | 44 +++++- tests/desktop-d3.test.ts | 169 ++++++++++++++++++++++ tests/serve.test.ts | 10 +- 11 files changed, 359 insertions(+), 24 deletions(-) create mode 100644 apps/desktop/src-tauri/tests/d3_writes.rs create mode 100644 tests/desktop-d3.test.ts diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index f685852..c53baa7 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -138,7 +138,7 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_ let mut p = policy::sanitize_js_call(&method, kind, ¶ms.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 { + confirm_dialog_with(window, title, text, "Apply".into()).await +} + +async fn confirm_dialog_with(window: &WebviewWindow, title: String, text: String, ok: String) -> Res { 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 }); diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index d1a0e37..a603df8 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -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, 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)) diff --git a/apps/desktop/src-tauri/tests/d3_writes.rs b/apps/desktop/src-tauri/tests/d3_writes.rs new file mode 100644 index 0000000..b522221 --- /dev/null +++ b/apps/desktop/src-tauri/tests/d3_writes.rs @@ -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()); +} diff --git a/cli/lib/ctx.ts b/cli/lib/ctx.ts index d85a96b..8e82fad 100644 --- a/cli/lib/ctx.ts +++ b/cli/lib/ctx.ts @@ -23,11 +23,16 @@ export function byAppleLocale(langs: Language[]): Map { /** * 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 { - 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] `); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 2a92422..b8af96f 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -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). */ diff --git a/cli/lib/project-files.ts b/cli/lib/project-files.ts index eb6276e..f54573f 100644 --- a/cli/lib/project-files.ts +++ b/cli/lib/project-files.ts @@ -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(//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: ` set in a draft file text; the body unchanged. */ export function setApproved(text: string, approved: boolean): string { const { data, body } = parseFrontMatter(text); diff --git a/cli/lib/runner.ts b/cli/lib/runner.ts index 98f1ab0..28232e4 100644 --- a/cli/lib/runner.ts +++ b/cli/lib/runner.ts @@ -39,7 +39,8 @@ export function pickCallEnv(env: Record | undefined): Record = {}, machine = false): Record { const base: Record = {}; - 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' } : {}) }; diff --git a/cli/reviews.ts b/cli/reviews.ts index 832bbb5..84d4b7d 100644 --- a/cli/reviews.ts +++ b/cli/reviews.ts @@ -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 [--undo] [--dry] sets approved: true (false) in one draft (local file) +// storebound reviews reply --text "..." [--dry] writes the reply of one draft (local file; approval reset) +// storebound reviews send --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 { } 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 { 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 --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'); } diff --git a/cli/serve.ts b/cli/serve.ts index 2bef392..c443c57 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -58,10 +58,42 @@ 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)] }, +]; +/** Flags no owner action may ever produce. */ +export const OWNER_FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--submit-review', '--remove', '--invite', '--production', 'submit', 'publish', 'distribute', 'testers']; + /** Desktop-only methods whose `project` is a folder without a config yet. */ const NEW_PROJECT = new Set(['project_init']); @@ -69,7 +101,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 +136,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 +328,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'); diff --git a/tests/desktop-d3.test.ts b/tests/desktop-d3.test.ts new file mode 100644 index 0000000..46b03d3 --- /dev/null +++ b/tests/desktop-d3.test.ts @@ -0,0 +1,169 @@ +// 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; +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' }], +]; + +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']); + 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' }, + ]; + 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']); + }); + 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', '', + '', '', '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 ')).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); + }); +}); diff --git a/tests/serve.test.ts b/tests/serve.test.ts index 6a2b31b..31f94cd 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -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; @@ -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 From ba58895d3afe40078134737a6d666cd703d65458 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 11 Oct 2026 04:25:53 +0800 Subject: [PATCH 2/4] Desktop D3 writes in the window: push listing text, upload graphics, screenshots and previews, render jobs, catalog sync and price export, Play rollout share / halt / resume / complete and iOS phased release controls, TestFlight What to Test, internal groups and testers, reply editor with approve and send; every one a dry run, a native dialog, then the real run --- apps/desktop/scripts/screens.ts | 27 ++++++ apps/desktop/src/dev/fixtures.ts | 15 ++-- apps/desktop/src/i18n/en.ts | 94 +++++++++++++++++++- apps/desktop/src/i18n/tr.ts | 94 +++++++++++++++++++- apps/desktop/src/screens/tabs/Catalog.tsx | 40 ++++++++- apps/desktop/src/screens/tabs/Listings.tsx | 58 +++++++++++- apps/desktop/src/screens/tabs/Releases.tsx | 64 +++++++++++-- apps/desktop/src/screens/tabs/Reviews.tsx | 71 ++++++++------- apps/desktop/src/screens/tabs/TestFlight.tsx | 87 +++++++++++++++--- apps/desktop/src/store.tsx | 32 +++++++ apps/desktop/src/styles.css | 18 ++++ apps/desktop/src/ui/WriteButton.tsx | 16 ++++ cli/serve.ts | 6 +- tests/desktop-d3.test.ts | 8 +- tests/store-apps.test.ts | 12 +-- 15 files changed, 573 insertions(+), 69 deletions(-) create mode 100644 apps/desktop/src/ui/WriteButton.tsx diff --git a/apps/desktop/scripts/screens.ts b/apps/desktop/scripts/screens.ts index 078d188..2226825 100644 --- a/apps/desktop/scripts/screens.ts +++ b/apps/desktop/scripts/screens.ts @@ -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}`); diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 1af6778..8dfde39 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -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 = { - [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): Promise } 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; - 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 }; } diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 4da4161..f0fc17a 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -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; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 2837eee..688a0d9 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -229,7 +229,7 @@ export const tr: Record = { '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 = { '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.', + + }; diff --git a/apps/desktop/src/screens/tabs/Catalog.tsx b/apps/desktop/src/screens/tabs/Catalog.tsx index 06cd007..a9fb1ca 100644 --- a/apps/desktop/src/screens/tabs/Catalog.tsx +++ b/apps/desktop/src/screens/tabs/Catalog.tsx @@ -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 = { 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 ( + +
+ {android && ( +
+
Google Play
+ {t('act.playProducts')} + {t('act.playSubs')} +
+ )} + {ios && ( +
+
App Store
+ {t('act.appleIap')} + {t('act.appleSubs')} +
+ )} +
+
{t('act.prices')}
+ {t('act.pricesExport')} + {t('act.pricesImport')} storebound prices import +
+
+

{t('act.catalogNote')}

+
+ ); +} + export function CatalogTab({ project }: { project: Project }) { const d = useData(); const e = d.statusOf(project); @@ -43,6 +78,7 @@ export function CatalogTab({ project }: { project: Project }) { {diff.error && {t('common.readFailedKeep', { error: diff.error })}} + { diff.refresh(); }} /> {read ? t('action.refresh') : t('cat.compare')}}>
diff --git a/apps/desktop/src/screens/tabs/Listings.tsx b/apps/desktop/src/screens/tabs/Listings.tsx index ff43a3b..c5fde1c 100644 --- a/apps/desktop/src/screens/tabs/Listings.tsx +++ b/apps/desktop/src/screens/tabs/Listings.tsx @@ -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 = { @@ -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 ( + +
+ {android && ( +
+
Google Play
+ {t('act.playListing')} + {t('act.playImages')} +
+ )} + {ios && ( +
+
App Store
+
+ + setVersion(ev.target.value.trim())} placeholder="2.4.0" /> +
+ {t('act.appleListing', { version: version || '…' })} + {t('act.appleShots')} + {t('act.applePreviews')} +
+ )} +
+
{t('act.render')}
+ + {t('act.renderShots')} + {t('act.renderVideo')} + {t('act.icons')} + {t('act.gallery')} +
+
+

{t('act.note')}

+
+ ); +} + export function ListingsTab({ project }: { project: Project }) { const r = useRead(project.id, 'project.listings', { network: false }); if (!r.data) { @@ -76,6 +129,7 @@ export function ListingsTab({ project }: { project: Project }) { l.screenshots !== null) ? shots : '–'} sub={L.locales.some(l => l.screenshots !== null) ? t('lst.screenshotsSub') : t('lst.noRenders')} />
{L.problems.map((p, i) => {p})} + {!noFiles && l.lang)} />} {noFiles ? ( {t('lst.noFilesText')} diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index 8a75b19..c238c1e 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -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 ( +
+ {t('roll.playNow', { pct: pct ?? 0 })} + {r.phase === 'rollout' && next.length > 0 && <> + + {t('roll.toShare', { pct: share })} + } + {r.phase === 'rollout' && {t('roll.halt')}} + {r.phase === 'halted' && {t('roll.resume')}} + {t('roll.complete')} +
+ ); + } + if (r.store === 'ios' && r.phased && (r.phased.state === 'ACTIVE' || r.phased.state === 'PAUSED')) { + return ( +
+ {t('roll.iosNow', { day: r.phased.day ?? 0 })} + {r.phased.state === 'ACTIVE' && {t('roll.pause')}} + {r.phased.state === 'PAUSED' && {t('roll.resume')}} + {t('roll.everyone')} +
+ ); + } + if (r.store === 'ios' && !r.phased && ['draft', 'review', 'approved'].includes(r.phase) && /^\d+(\.\d+){0,2}$/.test(v)) { + return ( +
+ {t('roll.phasedOn')} +
+ ); + } + 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 ( {train.version}{title}} @@ -57,6 +106,11 @@ function Train({ title, train, tf, tone }: { title: string; train: ReleaseTrain;
{t('tl.store')}{STAGES.map(s => {t(STAGE_KEY[s])})}
{lanes.map(l => )} + {lanes.some(l => l.release) && app.project && ( +
+ {lanes.map(l => l.release && )} +
+ )}
); } @@ -83,8 +137,8 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { return ( <> {errs.map(([s, msg]) => {t('releases.storeUnreadable', { store: storeName(s as 'ios'), error: msg })})} - {l.release.next && } - {l.release.current && } + {l.release.next && } + {l.release.current && } {!l.release.next && !l.release.current && {t('releases.noVersionsText')}} diff --git a/apps/desktop/src/screens/tabs/Reviews.tsx b/apps/desktop/src/screens/tabs/Reviews.tsx index d3c2ba1..0f04b37 100644 --- a/apps/desktop/src/screens/tabs/Reviews.tsx +++ b/apps/desktop/src/screens/tabs/Reviews.tsx @@ -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; 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 ( {r.title || t('reviews.noTitle')}} sub={{r.store === 'apple' ? 'App Store' : 'Google Play'}{r.where ? ` · ${r.where}` : ''} · {date(r.date)}{r.appVersion ? ` · ${t('reviews.version', { v: r.appVersion })}` : ''}}> @@ -32,25 +43,34 @@ function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft | {t('reviews.draft')} {draft && (draft.sent ? {t('reviews.sentOn', { date: date(draft.sent) })} : draft.approved ? {t('reviews.approved')} : {t('reviews.notApproved')})} - {!draft ?

{t('reviews.noDraft')}

: ( + {!draft ?

{t('reviews.noDraft')}

: draft.sent ? ( +
{draft.reply}
+ ) : ( <> - {draft.reply ?
{draft.reply}
:

{t('reviews.emptyDraft', { file: base(draft.file) })}

} -
{t('reviews.chars', { n: num([...draft.reply].length), limit: r.store === 'play' ? 350 : 5970 })}{base(draft.file)}
- {draft.issues.length > 0 && ( +