From aa72204a06c965fc41a46c446c1324ce7af5be2c Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 10:12:12 +0800 Subject: [PATCH 001/429] site: the highlighted download card keeps its own text colour for the details line (grey on the accent fill was unreadable); style.css cache key --- site/index.html | 2 +- site/style.css | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/site/index.html b/site/index.html index 44630f8..6e9bd4c 100644 --- a/site/index.html +++ b/site/index.html @@ -25,7 +25,7 @@ - + diff --git a/site/style.css b/site/style.css index bcf73bd..2ead5a8 100644 --- a/site/style.css +++ b/site/style.css @@ -714,6 +714,8 @@ h2 { font-size: clamp(28px, 4.2vw, 40px); font-weight: 720; letter-spacing: -.03 .dl-os .btn small { font-weight: 500; font-size: 12.5px; color: var(--muted); } .dl-os .btn.is-off { opacity: .6; cursor: default; pointer-events: none; } .dl-os .btn.is-here { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; } +/* the highlighted (your system) card is btn-primary: its details must keep the button's own text colour (muted grey on the accent fill was unreadable) */ +.dl-os .btn-primary small { color: inherit; opacity: .88; } .dl-notice { margin-top: 16px; padding: 14px 16px; border-radius: 12px; border: 1px solid var(--ui-ink); background: var(--ui-bg); color: var(--ui-ink); font-size: 14.5px; } .dl-notice ol { margin: 8px 0 0; padding-left: 20px; } .dl-verify { margin-top: 18px; } From be9ff8b78800a81d9069af8c9128cde128aba5e2 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 20:46:48 +0800 Subject: [PATCH 002/429] Play 'Live' only when the public store page proves it: play status checks https://play.google.com/store/apps/details?id= (no auth, 4 s timeout, cached 5 min; publicPage in the JSON), a completed production release with a 404 page is 'Sent to Google (in review or not yet published)', 200 is live for the first release or when the page shows the versionName, otherwise 'Released to production (Google may still be reviewing)', offline is unknown; new phases sent / released in the desktop Releases tab, Portfolio, release status | plan; versions matched across the stores without trailing .0 parts (App Store 1.0 and Play 1.0.0 are one row and one train, each side shows its own string); tests/play-public-version-match.test.ts, desktop boot check release-state cases (page 404 and 200) (pitfall 56) --- CHANGELOG.md | 12 +++ apps/desktop/src/dev/submit-fixtures.ts | 20 ++++ apps/desktop/src/i18n/en.ts | 4 + apps/desktop/src/i18n/tr.ts | 4 + apps/desktop/src/lib/notify.ts | 5 +- apps/desktop/src/screens/tabs/Releases.tsx | 9 +- apps/desktop/src/ui/kit.tsx | 3 +- cli/lib/desktop-protocol.ts | 7 +- cli/lib/play-public.ts | 63 +++++++++++ cli/lib/portfolio.ts | 74 +++++++++++-- cli/lib/train.ts | 29 +++-- cli/play/status.ts | 8 +- cli/release.ts | 4 +- skills/store-pitfalls/SKILL.md | 11 ++ tests/play-public-version-match.test.ts | 119 +++++++++++++++++++++ tests/portfolio.test.ts | 3 +- tests/release-train.test.ts | 1 + tools/desktop-boot-check.ts | 90 +++++++++++++++- 18 files changed, 436 insertions(+), 30 deletions(-) create mode 100644 cli/lib/play-public.ts create mode 100644 tests/play-public-version-match.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1000918..c2079f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## Unreleased + +- **Play "Live" only when the store page proves it.** The Play Developer API has no review state: a production release + reads `completed` while Google still reviews it. `play status` now checks the public store page (no auth, fast + timeout, cached 5 minutes) and adds `publicPage` to its JSON: page 404 = "Sent to Google (in review or not yet + published)", 200 = live for the first release, an update is "Released to production (Google may still be + reviewing)" unless the page shows its versionName, offline = unknown. New release phases `sent` and `released` in + the desktop Releases tab, Portfolio, `release status | plan` and the CLI JSON. Pitfall 56. +- **One row per release across the stores.** Versions are matched without trailing .0 parts (App Store "1.0" and Play + "1.0.0" are one row and one timeline); each side still shows the store's own string. + + ## 0.8.1 · 2026-10-13 `apple build` exports each build into its own folder and fails loudly on any export error; `apple upload` refuses a diff --git a/apps/desktop/src/dev/submit-fixtures.ts b/apps/desktop/src/dev/submit-fixtures.ts index 40891c0..cc7cf1f 100644 --- a/apps/desktop/src/dev/submit-fixtures.ts +++ b/apps/desktop/src/dev/submit-fixtures.ts @@ -103,3 +103,23 @@ export const PLAY_STATUS = { ], listings: [], products: [], }; + +// A first release in the shapes the stores really answered (pitfall: App Store "1.0" in review while Google Play's +// production release of "1.0.0" reads "completed" but the app is not public yet). `play status --json` adds the public +// store page check (publicPage): 404 = not public yet, 200 = published. +export const APPLE_STATUS_FIRST_REVIEW = { + app: { id: '1000000002', attributes: { name: 'Prism Puddle', bundleId: 'com.example.prismpuddle' } }, + versions: [version('ver-10', '1.0', 'WAITING_FOR_REVIEW', 'b-3')], + builds: [build('b-3', '3', 'VALID', '2026-10-10T09:00:00Z', 'pre-10')], attachedBuilds: [], buildVersions: { 'b-3': '1.0' }, + iaps: [], phased: {}, subs: [{ id: 'rs-10', attributes: { state: 'WAITING_FOR_REVIEW', submittedDate: '2026-10-10T10:00:00Z' } }], unresolved: [], emptyDrafts: [], +}; +const playFirst = (state: 'public' | 'notPublic') => ({ + ...PLAY_STATUS, + tracks: [ + { track: 'production', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed', userFraction: 1 }] }, + { track: 'internal', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed' }] }, + ], + publicPage: { state, http: state === 'public' ? 200 : 404, versionName: null, checkedAt: '2026-10-13T08:00:00Z', url: 'https://play.google.com/store/apps/details?id=com.example.prismpuddle&hl=en' }, +}); +export const PLAY_STATUS_FIRST_404 = playFirst('notPublic'); +export const PLAY_STATUS_FIRST_200 = playFirst('public'); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 5dd63ef..15451be 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -100,6 +100,9 @@ export const en = { 'phase.paused': 'Paused', 'phase.approved': 'Approved', 'phase.review': 'In review', + 'phase.sent': 'Sent to Google (in review or not yet published)', + 'phase.released': 'Released to production (Google may still be reviewing)', + 'phase.releasedUnknown': 'Released to production (live state unknown: the store page could not be read)', 'phase.rejected': 'Rejected', 'phase.testing': 'Testing', 'phase.draft': 'Draft', @@ -211,6 +214,7 @@ export const en = { 'tl.next': 'Next', 'tl.live': 'Live', + 'tl.released': 'Released', 'tl.store': 'Store', 'tl.created': 'Created {date}', 'tl.notOnStore': 'Not on this store', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 27c519d..f02df46 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -102,6 +102,9 @@ export const tr: Record = { 'phase.paused': 'Duraklatıldı', 'phase.approved': 'Onaylandı', 'phase.review': 'İncelemede', + 'phase.sent': 'Google’a gönderildi (incelemede ya da henüz yayınlanmadı)', + 'phase.released': 'Üretime çıktı (Google hâlâ inceliyor olabilir)', + 'phase.releasedUnknown': 'Üretime çıktı (yayın durumu bilinmiyor: mağaza sayfası okunamadı)', 'phase.rejected': 'Reddedildi', 'phase.testing': 'Testte', 'phase.draft': 'Taslak', @@ -213,6 +216,7 @@ export const tr: Record = { 'tl.next': 'Sonraki', 'tl.live': 'Yayında', + 'tl.released': 'Üretimde', 'tl.store': 'Mağaza', 'tl.created': 'Oluşturma: {date}', 'tl.notOnStore': 'Bu mağazada yok', diff --git a/apps/desktop/src/lib/notify.ts b/apps/desktop/src/lib/notify.ts index 3be6d31..247f8ba 100644 --- a/apps/desktop/src/lib/notify.ts +++ b/apps/desktop/src/lib/notify.ts @@ -1,6 +1,7 @@ // What deserves a desktop notification after a read (Settings > Notifications). Pure: compares the previous read with // the new one and never fires on a first read (nothing to compare with = no flood). import type { PortfolioResult } from '../api'; +import { sameVersion } from '../../../../cli/lib/portfolio'; import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from './model'; export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string } @@ -8,14 +9,14 @@ export interface ReleaseChange { project: string; name: string; store: 'ios' | ' /** Phase changes of the same version on the same store that the owner waits for: review in / out, approved, rejected, live, halted. */ export function releaseChanges(prev: PortfolioResult | null | undefined, next: PortfolioResult): ReleaseChange[] { if (!prev) return []; - const WATCH = new Set(['review', 'approved', 'rejected', 'live', 'halted']); + const WATCH = new Set(['review', 'sent', 'released', 'approved', 'rejected', 'live', 'halted']); const out: ReleaseChange[] = []; for (const a of next.apps) { const before = prev.apps.find(p => p.project === a.project); if (!before || before.release.source !== 'live' || a.release.source !== 'live') continue; for (const r of a.release.all ?? []) { if (!r.version) continue; - const old = (before.release.all ?? []).find(x => x.store === r.store && x.version === r.version); + const old = (before.release.all ?? []).find(x => x.store === r.store && (x.version === r.version || sameVersion(x.version, r.version))); if (!old || old.phase === r.phase) continue; if (WATCH.has(r.phase) || WATCH.has(old.phase)) out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase }); } diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index d05f5c5..caab9e7 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -22,6 +22,7 @@ function stageCaption(l: Lane, i: number): string { const r = l.release; if (i === 1) return r.store === 'ios' ? 'TestFlight' : (r.track ?? t('stage.testing')); if (i === 2) return t(`phase.${r.phase}` as Key); + if (i === 3 && r.phase === 'released') return t(r.publicPage === 'unknown' ? 'phase.releasedUnknown' : 'phase.released'); return ''; } @@ -33,7 +34,7 @@ function LaneRow({ lane, version }: { lane: Lane; version: string }) {
{storeName(lane.store)}
-
{r ? `${version}${r.build ? ` (${r.build})` : ''}` : t('tl.notOnStore')}
+
{r ? `${r.version ?? version}${r.build ? ` (${r.build})` : ''}` : t('tl.notOnStore')}
{lane.at < 0 ?
{t('tl.noVersion', { version, store: storeName(lane.store) })}
: STAGES.map((s, i) => { @@ -102,8 +103,10 @@ function RolloutControls({ app, r }: { app: UnifiedApp; r: StoreRelease }) { function Train({ title, train, tf, tone, app }: { title: string; train: ReleaseTrain; tf: TestFlightStatus | null; tone: 'accent' | 'ok'; app: UnifiedApp }) { const lanes = trainLanes(train, tf); + // "Live" only when a store has it live or rolling out; a Play release Google may still review is "Released" + const label = tone === 'ok' && !lanes.some(l => l.release && ['live', 'rollout', 'halted'].includes(l.release.phase)) ? t('tl.released') : title; return ( - {train.version}{title}} + {train.version}{label}} sub={[train.ios?.date ? t('tl.created', { date: date(train.ios.date) }) : null].filter(Boolean).join(' · ') || undefined}>
{t('tl.store')}{STAGES.map(s => {t(STAGE_KEY[s])})}
@@ -165,7 +168,7 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { {history.map(h => ( - {h.version} + {[...new Set([h.version, h.ios?.version, h.android?.version].filter(Boolean))].join(' / ')} {h.ios ? : –} {h.ios?.build ?? '–'} {h.android ? : –} diff --git a/apps/desktop/src/ui/kit.tsx b/apps/desktop/src/ui/kit.tsx index 2b0989e..0e3283d 100644 --- a/apps/desktop/src/ui/kit.tsx +++ b/apps/desktop/src/ui/kit.tsx @@ -14,7 +14,7 @@ export function Chip({ tone = 'neutral', children, dot = true, title, icon }: { return {icon ? : dot && tone !== 'outline' && }{children}; } -const PHASE_TONE: Record = { live: 'ok', rollout: 'accent', halted: 'bad', approved: 'ok', review: 'warn', rejected: 'bad', testing: 'info', draft: 'neutral', other: 'neutral' }; +const PHASE_TONE: Record = { live: 'ok', rollout: 'accent', halted: 'bad', released: 'info', approved: 'ok', review: 'warn', sent: 'warn', rejected: 'bad', testing: 'info', draft: 'neutral', other: 'neutral' }; /** Chip of a store release: "Live", "Rollout 20%", "In review" ... (iOS phased release: "Phased 50%", "Paused"). */ export function phaseLabel(r: StoreRelease | null | undefined): { text: string; tone: Tone } { @@ -22,6 +22,7 @@ export function phaseLabel(r: StoreRelease | null | undefined): { text: string; const pct = r.fraction !== null && r.fraction !== undefined && r.fraction < 1 ? ` ${share(r.fraction)}` : ''; if (r.phase === 'rollout') return { text: (r.store === 'ios' ? t('phase.phased') : t('phase.rollout')) + pct, tone: 'accent' }; if (r.phase === 'halted') return { text: (r.store === 'ios' ? t('phase.paused') : t('phase.halted')) + pct, tone: 'bad' }; + if (r.phase === 'released' && r.publicPage === 'unknown') return { text: t('phase.releasedUnknown'), tone: 'neutral' }; if (r.phase === 'testing' && r.track) return { text: `${t('phase.testing')} · ${r.track}`, tone: 'info' }; return { text: t(`phase.${r.phase}`), tone: PHASE_TONE[r.phase] }; } diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 57491ea..9818a1f 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -115,7 +115,10 @@ export interface AppIdentity { } /** Where a version is on one store. */ -export type ReleasePhase = 'live' | 'rollout' | 'halted' | 'approved' | 'review' | 'rejected' | 'testing' | 'draft' | 'other'; +/** `sent`: a Google Play production release that is completed in the API while the public store page is 404 (sent to + * Google, in review or not yet published). `released`: completed in production and the app is public, but this + * version is not proven live (an update Google may still be reviewing, or the public page could not be read). */ +export type ReleasePhase = 'live' | 'rollout' | 'halted' | 'released' | 'approved' | 'review' | 'sent' | 'rejected' | 'testing' | 'draft' | 'other'; export interface StoreRelease { store: 'ios' | 'android'; @@ -131,6 +134,8 @@ export interface StoreRelease { track: string | null; /** iOS phased release: day 1-7 and its state (ACTIVE, PAUSED, COMPLETE); null without one. */ phased?: { state: string; day: number | null } | null; + /** Google Play production: the public store page (public = 200, notPublic = 404, unknown = not read). */ + publicPage?: 'public' | 'notPublic' | 'unknown'; /** When the store record was made (iOS version createdDate), if the store says. */ date?: string | null; } diff --git a/cli/lib/play-public.ts b/cli/lib/play-public.ts new file mode 100644 index 0000000..36f0440 --- /dev/null +++ b/cli/lib/play-public.ts @@ -0,0 +1,63 @@ +// Is the app public on Google Play? The Play Developer API has no review state: a production release reads +// "completed" from the moment it is sent, while Google may still be reviewing it (a first release is not public +// until then). The public store page answers it: 200 = published, 404 = not public yet. No auth, a fast timeout, +// cached for a few minutes (in memory and in the temp folder, so short CLI runs share it), "unknown" when offline. +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +export type PublicState = 'public' | 'notPublic' | 'unknown'; +export interface PlayPublicPage { + state: PublicState; + /** HTTP status of the store page (null when it could not be read). */ + http: number | null; + /** The versionName the page shows, when it shows one (usually it does not). */ + versionName: string | null; + checkedAt: string; + url: string; + error?: string; +} + +export const playPageUrl = (pkg: string): string => `https://play.google.com/store/apps/details?id=${encodeURIComponent(pkg)}&hl=en`; + +const TTL_MS = 5 * 60_000; +const mem = new Map(); +const cacheFile = (pkg: string): string => join(tmpdir(), 'storebound-play-public', `${pkg.replace(/[^\w.-]/g, '_')}.json`); +const fresh = (p: PlayPublicPage | undefined | null): p is PlayPublicPage => !!p && p.state !== 'unknown' && Date.now() - Date.parse(p.checkedAt) < TTL_MS; + +/** The versionName in the page's structured data, when it has one ("softwareVersion"). */ +export function pageVersion(html: string): string | null { + const m = html.match(/"softwareVersion"\s*:\s*"([^"]{1,40})"/); + return m && /\d/.test(m[1]!) ? m[1]! : null; +} + +/** Reads the public page (cached 5 minutes; STOREBOUND_PLAY_PUBLIC=public|notPublic|unknown overrides it for tests). */ +export async function playPublicPage(pkg: string, o: { timeoutMs?: number; noCache?: boolean } = {}): Promise { + const url = playPageUrl(pkg); + const forced = process.env.STOREBOUND_PLAY_PUBLIC; + if (forced === 'public' || forced === 'notPublic' || forced === 'unknown') + return { state: forced, http: forced === 'public' ? 200 : forced === 'notPublic' ? 404 : null, versionName: process.env.STOREBOUND_PLAY_PUBLIC_VERSION ?? null, checkedAt: new Date().toISOString(), url }; + if (!o.noCache) { + const m = mem.get(pkg); + if (fresh(m)) return m; + try { const f = JSON.parse(readFileSync(cacheFile(pkg), 'utf8')) as PlayPublicPage; if (fresh(f) && f.url === url) { mem.set(pkg, f); return f; } } catch { /* no cache */ } + } + let out: PlayPublicPage; + try { + const r = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(o.timeoutMs ?? 4000), headers: { 'User-Agent': 'Mozilla/5.0 storebound', 'Accept-Language': 'en' } }); + const http = r.status; + if (http === 200) out = { state: 'public', http, versionName: pageVersion(await r.text()), checkedAt: new Date().toISOString(), url }; + else if (http === 404) out = { state: 'notPublic', http, versionName: null, checkedAt: new Date().toISOString(), url }; + else out = { state: 'unknown', http, versionName: null, checkedAt: new Date().toISOString(), url, error: `HTTP ${http}` }; + } catch (e) { + out = { state: 'unknown', http: null, versionName: null, checkedAt: new Date().toISOString(), url, error: (e as Error).message || 'offline' }; + } + if (out.state !== 'unknown') { + mem.set(pkg, out); + try { mkdirSync(join(tmpdir(), 'storebound-play-public'), { recursive: true }); writeFileSync(cacheFile(pkg), JSON.stringify(out)); } catch { /* cache is optional */ } + } + return out; +} + +/** Forget the cached answers (tests). */ +export function clearPlayPublicCache(): void { mem.clear(); } diff --git a/cli/lib/portfolio.ts b/cli/lib/portfolio.ts index 9e53f0c..5995344 100644 --- a/cli/lib/portfolio.ts +++ b/cli/lib/portfolio.ts @@ -23,6 +23,25 @@ export function cmpVersion(a: string, b: string): number { return 0; } +/** Matching key of a version: numeric parts without trailing zero parts, so 1 == 1.0 == 1.0.0 ("1"), 2.10 != 2.1. + * A version with non-numeric parts keeps its own spelling. The stores' strings are shown as they are; this only joins. */ +export function versionKey(v: string): string { + const parts = v.trim().split('.'); + if (!parts.every(p => /^\d+$/.test(p))) return v.trim(); + const n = parts.map(p => String(parseInt(p, 10))); + while (n.length > 1 && n.at(-1) === '0') n.pop(); + return n.join('.'); +} + +/** The same release on both stores (App Store "1.0" and Play "1.0.0"). */ +export const sameVersion = (a: string | null | undefined, b: string | null | undefined): boolean => !!a && !!b && versionKey(a) === versionKey(b); + +/** The spelling a joined row shows: the longest of the stores' strings (1.0.0 over 1.0), the first one on a tie. */ +export function displayVersion(vs: (string | null | undefined)[]): string { + const xs = vs.filter((x): x is string => !!x); + return xs.reduce((a, b) => (b.split('.').length > a.split('.').length ? b : a), xs[0] ?? ''); +} + /** App Store version states (appStoreState / appVersionState) -> phase. */ export function applePhase(state: string): ReleasePhase { if (/^(READY_FOR_SALE|READY_FOR_DISTRIBUTION)$/.test(state)) return 'live'; @@ -85,22 +104,56 @@ export function testflightReleases(builds: J[], buildVersions: Record "2.3.0"). */ export const versionOfName = (name: unknown): string | null => (typeof name === 'string' ? name.match(/\d+(?:\.\d+){0,3}/)?.[0] ?? null : null); +/** + * Play tracks (`play status --json`) -> releases. The Developer API has no review state: a completed production release + * is only "live" when the public store page proves it (`publicPage` in the status JSON): 404 = sent to Google (in + * review or not yet published); 200 = live for the first release or when the page shows this versionName, otherwise + * "released" (an update Google may still be reviewing); page not read = "released" with publicPage unknown. + */ export function playReleases(data: unknown): StoreRelease[] { const out: StoreRelease[] = []; - for (const t of ((data as J)?.tracks ?? []) as J[]) { - for (const r of (t?.releases ?? []) as J[]) { - const codes = ((r.versionCodes ?? []) as unknown[]).map(Number).filter(Number.isFinite); + const page = (data as J)?.publicPage as { state?: string; versionName?: string | null } | undefined; + const pageState = page?.state === 'public' || page?.state === 'notPublic' ? page.state : 'unknown'; + const raw = (data as J)?.tracks; + const tracks: J[] = Array.isArray(raw) ? raw : []; + const codesOf = (r: J): number[] => (Array.isArray(r?.versionCodes) ? (r.versionCodes as unknown[]) : []).map(Number).filter(Number.isFinite); + const rels = (t: J): J[] => (Array.isArray(t?.releases) ? t.releases : []); + const allCodes = tracks.flatMap(t => rels(t).flatMap(codesOf)); + for (const t of tracks) { + for (const r of rels(t)) { + const codes = codesOf(r); const production = t.track === 'production'; const status = String(r.status ?? 'unknown'); - const phase: ReleasePhase = !production ? (status === 'draft' ? 'draft' : 'testing') - : status === 'completed' ? 'live' : status === 'inProgress' ? 'rollout' : status === 'halted' ? 'halted' : status === 'draft' ? 'draft' : 'other'; - out.push({ store: 'android', version: versionOfName(r.name), build: codes.length ? String(Math.max(...codes)) : null, state: status, phase, fraction: typeof r.userFraction === 'number' ? r.userFraction : null, track: String(t.track) }); + const version = versionOfName(r.name); + const rel: StoreRelease = { store: 'android', version, build: codes.length ? String(Math.max(...codes)) : null, state: status, phase: 'other', fraction: typeof r.userFraction === 'number' ? r.userFraction : null, track: String(t.track) }; + rel.phase = !production ? (status === 'draft' ? 'draft' : 'testing') + : status === 'inProgress' ? 'rollout' : status === 'halted' ? 'halted' : status === 'draft' ? 'draft' : 'other'; + if (production && status === 'completed') { + const low = codes.length ? Math.min(...codes) : Infinity; + const first = !allCodes.some(c => c < low); // nothing older on any track: the app's first release + rel.phase = pageState === 'notPublic' ? 'sent' + : pageState === 'public' && (first || sameVersion(page?.versionName, version)) ? 'live' + : 'released'; + rel.publicPage = pageState; + } + out.push(rel); } } return out; } -const PHASE_RANK: Record = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 }; +/** Plain words for a Play production release's phase (CLI text; the desktop has the same words in i18n). */ +export function playReleaseLabel(r: StoreRelease): string { + if (r.phase === 'sent') return 'Sent to Google (in review or not yet published)'; + if (r.phase === 'released') return r.publicPage === 'unknown' ? 'Released to production (public store page not readable: live state unknown)' : 'Released to production (Google may still be reviewing)'; + if (r.phase === 'live') return 'Live'; + return r.state; +} + +export const PHASE_RANK: Record = { live: 0, rollout: 1, halted: 2, released: 3, approved: 4, review: 5, sent: 6, rejected: 7, testing: 8, draft: 9, other: 10 }; + +/** Phases where the version reaches (or may reach) users. */ +export const REACHING: ReadonlySet = new Set(['live', 'rollout', 'halted', 'released']); const pick = (rs: StoreRelease[]): StoreRelease | null => [...rs].sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase])[0] ?? null; /** @@ -110,8 +163,11 @@ const pick = (rs: StoreRelease[]): StoreRelease | null => [...rs].sort((a, b) => */ export function releaseTrains(ios: StoreRelease[], android: StoreRelease[]): { current: ReleaseTrain | null; next: ReleaseTrain | null } { const all = [...ios, ...android].filter((r): r is StoreRelease & { version: string } => !!r.version); - const train = (v: string): ReleaseTrain => ({ version: v, ios: pick(all.filter(r => r.store === 'ios' && r.version === v)), android: pick(all.filter(r => r.store === 'android' && r.version === v)) }); - const live = all.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').map(r => r.version).sort(cmpVersion).at(-1) ?? null; + const train = (v: string): ReleaseTrain => { + const i = pick(all.filter(r => r.store === 'ios' && sameVersion(r.version, v))), a = pick(all.filter(r => r.store === 'android' && sameVersion(r.version, v))); + return { version: displayVersion([a?.version, i?.version, v]), ios: i, android: a }; + }; + const live = all.filter(r => REACHING.has(r.phase)).map(r => r.version).sort(cmpVersion).at(-1) ?? null; const above = all.filter(r => !live || cmpVersion(r.version, live) > 0).map(r => r.version).sort(cmpVersion).at(-1) ?? null; return { current: live ? train(live) : null, next: above ? train(above) : null }; } diff --git a/cli/lib/train.ts b/cli/lib/train.ts index 549e671..0cb0f3b 100644 --- a/cli/lib/train.ts +++ b/cli/lib/train.ts @@ -4,10 +4,10 @@ // stage for the same store state. Pure; the store reads are `apple status --json` / `play status --json`, turned into // StoreRelease rows by cli/lib/portfolio.ts. import type { ReleaseTrain, StoreRelease } from './desktop-protocol'; -import { cmpVersion } from './portfolio'; +import { cmpVersion, displayVersion, PHASE_RANK, REACHING, sameVersion, versionKey } from './portfolio'; import type { Finding } from './validate-rules'; -export { cmpVersion }; +export { cmpVersion, displayVersion, sameVersion, versionKey }; export type Tone = 'ok' | 'warn' | 'bad' | 'info' | 'neutral' | 'accent'; @@ -36,6 +36,8 @@ export function laneOf(store: 'ios' | 'android', r: StoreRelease | null, testfli case 'testing': return { ...base, at: 1, tone: 'info', share: null }; case 'review': return { ...base, at: 2, tone: 'warn', share: null }; case 'approved': return { ...base, at: 2, tone: 'ok', share: null }; + case 'sent': return { ...base, at: 2, tone: 'warn', share: null }; + case 'released': return { ...base, at: 3, tone: r.publicPage === 'unknown' ? 'neutral' : 'info', share: null }; case 'rejected': return { ...base, at: 2, tone: 'bad', share: null }; case 'live': return { ...base, at: 4, tone: 'ok', share: 1 }; case 'rollout': return { ...base, at: 4, tone: 'accent', share: r.fraction ?? null }; @@ -49,23 +51,26 @@ export interface BetaBuilds { builds: { version: string | null; internal: string /** Both lanes of a train; iOS counts TestFlight as reached when a build of that version is in beta testing. */ export function trainLanes(t: ReleaseTrain, tf?: BetaBuilds | null): Lane[] { - const inBeta = !!tf?.builds.some(b => b.version === t.version && /IN_BETA_TESTING|BETA_APPROVED|READY_FOR_BETA_TESTING/.test(`${b.internal ?? ''} ${b.external ?? ''}`)); + const inBeta = !!tf?.builds.some(b => sameVersion(b.version, t.version) && /IN_BETA_TESTING|BETA_APPROVED|READY_FOR_BETA_TESTING/.test(`${b.internal ?? ''} ${b.external ?? ''}`)); return [laneOf('ios', t.ios, inBeta), laneOf('android', t.android)]; } /** Every distinct version of the store releases, newest first, with both stores' release (best phase per store). */ export function versionHistory(all: StoreRelease[]): ReleaseTrain[] { - const rank: Record = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 }; - const versions = [...new Set(all.map(r => r.version).filter((v): v is string => !!v))].sort(cmpVersion).reverse(); - const best = (store: 'ios' | 'android', v: string) => all.filter(r => r.store === store && r.version === v).sort((a, b) => (rank[a.phase] ?? 9) - (rank[b.phase] ?? 9))[0] ?? null; - return versions.map(v => ({ version: v, ios: best('ios', v), android: best('android', v) })); + const keys = new Map(); // one row per release: 1.0 (App Store) and 1.0.0 (Play) are the same + for (const v of all.map(r => r.version).filter((x): x is string => !!x)) { const k = versionKey(v); keys.set(k, [...(keys.get(k) ?? []), v]); } + const best = (store: 'ios' | 'android', k: string) => all.filter(r => r.store === store && !!r.version && versionKey(r.version) === k).sort((a, b) => (PHASE_RANK[a.phase] ?? 99) - (PHASE_RANK[b.phase] ?? 99))[0] ?? null; + return [...keys].map(([k, vs]) => { + const ios = best('ios', k), android = best('android', k); + return { version: displayVersion([android?.version, ios?.version, ...vs]), ios, android }; + }).sort((a, b) => cmpVersion(b.version, a.version)); } /** On one store: the highest version reaching users (live or rolling out) and the highest version above it. */ export function storeNow(all: StoreRelease[], store: 'ios' | 'android'): { now: StoreRelease | null; next: StoreRelease | null } { const rs = all.filter((r): r is StoreRelease & { version: string } => r.store === store && !!r.version); const desc = (a: { version: string }, b: { version: string }) => cmpVersion(b.version, a.version); - const now = rs.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').sort(desc)[0] ?? null; + const now = rs.filter(r => REACHING.has(r.phase)).sort(desc)[0] ?? null; const next = rs.filter(r => !now || cmpVersion(r.version, now.version) > 0).sort(desc)[0] ?? null; return { now, next }; } @@ -80,6 +85,8 @@ export function laneText(l: Lane): string { const stage = STAGES[l.at] ?? 'build'; const p = l.release.phase; if (p === 'live') return 'live'; // the whole track filled: everyone has it + if (p === 'sent') return 'review (sent to Google: in review or not yet published)'; + if (p === 'released') return l.release.publicPage === 'unknown' ? 'released to production (public page not readable: live unknown)' : 'released to production (Google may still be reviewing)'; const word = p === stage || (p === 'draft' && stage === 'build') || (p === 'other' && stage === 'build') ? stage : `${stage} (${p})`; if (p === 'rollout' || p === 'halted') return `${word} ${pctText(l.share)}`.trim(); return word; @@ -176,6 +183,12 @@ function storeSteps(store: 'ios' | 'android', v: string, r: StoreRelease | null, case 'rejected': steps.push({ kind: 'owner', text: `resubmit ${v} after the fix (owner)`, fix: store === 'ios' ? 'App Store Connect > App Review > reply / resubmit' : 'Play Console > Publishing overview' }); break; + case 'sent': + steps.push({ kind: 'wait', text: `${v} is sent to Google (production completed, the store page is not public yet): in review or not yet published`, fix: 'storebound play status (checks the public store page)' }); + break; + case 'released': + steps.push({ kind: 'wait', text: r!.publicPage === 'unknown' ? `${v} is released to production; the public store page could not be read, so live is unknown` : `${v} is released to production; Google may still be reviewing it (the app is public, this version is not proven live)`, fix: 'storebound play status' }); + break; case 'review': steps.push({ kind: 'wait', text: `${v} is in review (${r!.state}); nothing to do until the store answers`, fix: store === 'ios' ? 'storebound apple status --wait-review' : 'storebound play status' }); break; diff --git a/cli/play/status.ts b/cli/play/status.ts index 4b83646..cfba96d 100644 --- a/cli/play/status.ts +++ b/cli/play/status.ts @@ -4,6 +4,8 @@ import { playCategoryOf } from '../lib/config'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; import { printJson } from '../lib/log'; +import { playPublicPage } from '../lib/play-public'; +import { playReleases, playReleaseLabel } from '../lib/portfolio'; import { playClient } from './client'; import { listOneTimeProducts } from './products'; @@ -16,11 +18,11 @@ export async function run(ctx: Ctx): Promise { const tracks = (await play.call<{ tracks?: Track[] }>('GET', `${play.API}/edits/${id}/tracks`)).tracks ?? []; const listings = (await play.call<{ listings?: { language: string }[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? []; const details = await play.call>('GET', `${play.API}/edits/${id}/details`); - const products = await listOneTimeProducts(play); + const [products, publicPage] = await Promise.all([listOneTimeProducts(play), playPublicPage(play.packageName)]); // the App category is not in the API (edits.details has no category field): a console step const cat = playCategoryOf(config); const category = { config: cat?.category ?? null, source: cat?.source ?? null, api: false, plan: 'storebound console plan play-store-settings' }; - if (ctx.args.has('json')) { printJson({ details, category, tracks, listings, products }); return; } + if (ctx.args.has('json')) { printJson({ details, category, tracks, listings, products, publicPage }); return; } console.log(`${play.packageName}\n details: ${details.defaultLanguage} · ${details.contactEmail ?? '-'} · ${details.contactWebsite ?? '-'}`); console.log(` category: ${cat ? `${cat.category} (${cat.source})` : 'not in the config (play.category)'} · not readable by the API: Store settings is a console step (${category.plan})`); console.log(` listings (${listings.length}): ${listings.map(l => l.language).join(', ') || '-'}`); @@ -28,6 +30,8 @@ export async function run(ctx: Ctx): Promise { const rs = (t.releases ?? []).map(r => `${r.name ?? '?'} [${r.versionCodes?.join(',') ?? '-'}] ${r.status}${r.userFraction ? ' ' + r.userFraction * 100 + '%' : ''}`); console.log(` track ${t.track.padEnd(11)} ${rs.join(' | ') || '-'}`); } + console.log(` public store page: ${publicPage.state === 'public' ? 'published (200)' : publicPage.state === 'notPublic' ? 'not public yet (404)' : `unknown (${publicPage.error ?? 'not read'})`}`); + for (const r of playReleases({ tracks, publicPage }).filter(x => x.track === 'production' && x.state === 'completed')) console.log(` production ${r.version ?? '?'} (${r.build ?? '?'}): ${playReleaseLabel(r)}`); console.log(` products (${products.length}):`); for (const p of products) console.log(` ${p.productId.padEnd(40)} ${(p.purchaseOptions ?? []).map(o => `${o.purchaseOptionId}:${o.state ?? '?'}`).join(' ')}`); }); diff --git a/cli/release.ts b/cli/release.ts index 7b4da70..9644546 100644 --- a/cli/release.ts +++ b/cli/release.ts @@ -17,7 +17,7 @@ import type { AppStatus, ReleaseTrain } from './lib/desktop-protocol'; import { log, printJson, warn } from './lib/log'; import { runCommand, type RunResult } from './lib/runner'; import { textTable } from './lib/table'; -import { laneOf, laneText, type PlanStep, releasePlan, type ReleasePlan, trackText, versionHistory } from './lib/train'; +import { laneOf, laneText, type PlanStep, releasePlan, type ReleasePlan, sameVersion, trackText, versionHistory } from './lib/train'; import type { Finding } from './lib/validate-rules'; import { findWorkspace, loadWorkspace, resolveApps, selectApps } from './lib/workspace'; import { appDir, appEnv, workspaceApps } from './workspace'; @@ -73,7 +73,7 @@ export interface TrainRow { app: string; version: string; which: 'current' | 'ne export function trainsOf(s: AppStatus, all: boolean): { which: TrainRow['which']; train: ReleaseTrain }[] { if (all) { const cur = s.release.current?.version, next = s.release.next?.version; - return versionHistory(s.release.all ?? []).map(t => ({ which: t.version === cur ? 'current' as const : t.version === next ? 'next' as const : 'other' as const, train: t })); + return versionHistory(s.release.all ?? []).map(t => ({ which: sameVersion(t.version, cur) ? 'current' as const : sameVersion(t.version, next) ? 'next' as const : 'other' as const, train: t })); } return [...(s.release.current ? [{ which: 'current' as const, train: s.release.current }] : []), ...(s.release.next ? [{ which: 'next' as const, train: s.release.next }] : [])]; } diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 855cec8..fb256af 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -649,3 +649,14 @@ that fails without the fix (see CONTRIBUTING.md). at render time, `devices` in report.json), and warns when a screenshot's front device runs off a side or the top. - **Guard:** `featureLayout`, `rotatedBox` (`cli/shots/lib.ts`), `deviceIssues` (`cli/shots/report.ts`), `tests/feature-fit.test.ts` (geometry, both templates rendered at 1024 x 500, a bleeding fixture). + +## 56. "Live on Play" while Google was still reviewing, and 1.0 / 1.0.0 shown as two versions +- **Do:** never call a Google Play production release live from the Developer API alone: a release reads `completed` + (userFraction 1) from the moment it is sent, also while Google reviews the first release. `play status` checks the + public store page (no auth, 4 s timeout, cached 5 minutes): 404 = "Sent to Google (in review or not yet + published)"; 200 = live for the first release (or when the page shows the same versionName), otherwise "Released to + production (Google may still be reviewing)"; offline = unknown, shown as unknown. Match versions across the stores + by `versionKey` (trailing .0 parts dropped: 1 == 1.0 == 1.0.0); show each store's own string. +- **Guard:** `playPublicPage` (`cli/lib/play-public.ts`), `playReleases` / `versionKey` / `sameVersion` + (`cli/lib/portfolio.ts`), `versionHistory` (`cli/lib/train.ts`), `tests/play-public-version-match.test.ts`, the + desktop boot check's `release-state` cases (page 404 and 200). diff --git a/tests/play-public-version-match.test.ts b/tests/play-public-version-match.test.ts new file mode 100644 index 0000000..2942134 --- /dev/null +++ b/tests/play-public-version-match.test.ts @@ -0,0 +1,119 @@ +// A first release on both stores in the shapes they really answer: App Store "1.0" (build 3) waiting for review, Google +// Play production "1.0.0" (versionCode 3) completed with userFraction 1 while the app is not public yet (the store page +// answers 404). One row for 1.0 / 1.0.0, never "Live" on Play from the Developer API alone (pitfall 56). +import { afterEach, describe, expect, test } from 'bun:test'; +import { APPLE_STATUS_FIRST_REVIEW, PLAY_STATUS_FIRST_200, PLAY_STATUS_FIRST_404 } from '../apps/desktop/src/dev/submit-fixtures'; +import { trainsOf } from '../cli/release'; +import { clearPlayPublicCache, pageVersion, playPublicPage } from '../cli/lib/play-public'; +import { appleReleases, playReleaseLabel, playReleases, releaseTrains, sameVersion, versionKey } from '../cli/lib/portfolio'; +import { laneOf, laneText, releasePlan, storeNow, versionHistory } from '../cli/lib/train'; + +const realFetch = globalThis.fetch; +afterEach(() => { globalThis.fetch = realFetch; delete process.env.STOREBOUND_PLAY_PUBLIC; clearPlayPublicCache(); }); + +describe('version matching across the stores', () => { + test('trailing zero parts do not make a different version', () => { + expect(versionKey('1.0')).toBe('1'); + expect(versionKey('1.0.0')).toBe('1'); + expect(versionKey('1')).toBe('1'); + expect(versionKey('2.10.0')).toBe('2.10'); + expect(versionKey('01.2.0')).toBe('1.2'); + expect(versionKey('1.0-beta')).toBe('1.0-beta'); + expect(sameVersion('1.0', '1.0.0')).toBe(true); + expect(sameVersion('2.1', '2.10')).toBe(false); + expect(sameVersion('1.0.1', '1.0')).toBe(false); + expect(sameVersion(null, '1')).toBe(false); + }); + test('App Store 1.0 and Play 1.0.0 are one row and one train; each side keeps its own string', () => { + const ios = appleReleases(APPLE_STATUS_FIRST_REVIEW), android = playReleases(PLAY_STATUS_FIRST_404); + const all = [...ios, ...android]; + const h = versionHistory(all); + expect(h).toHaveLength(1); + expect(h[0]!.version).toBe('1.0.0'); + expect(h[0]!.ios).toMatchObject({ version: '1.0', build: '3', phase: 'review' }); + expect(h[0]!.android).toMatchObject({ version: '1.0.0', build: '3', phase: 'sent', track: 'production' }); + const t = releaseTrains(ios, android); + expect(t.current).toBeNull(); // nothing reaches users yet + expect(t.next).toMatchObject({ version: '1.0.0', ios: { version: '1.0', phase: 'review' }, android: { version: '1.0.0', phase: 'sent' } }); + // release status --versions: the one row is the next train + const s = { release: { source: 'live' as const, ...t, all }, storeErrors: {}, summary: null } as never; + expect(trainsOf(s, true).map(x => [x.which, x.train.version])).toEqual([['next', '1.0.0']]); + // release plan 1.0 finds the Play 1.0.0 release too + const p = releasePlan({ version: '1.0', platforms: { ios: true, android: true }, check: { problems: [], warnings: [] }, validate: [], releases: all }); + expect(p.ios?.release?.version).toBe('1.0'); + expect(p.android?.release?.version).toBe('1.0.0'); + expect(p.done).toBe(false); + expect(p.android!.steps.map(x => x.text).join(' ')).toContain('sent to Google'); + }); +}); + +describe('Google Play "Live" needs the public store page', () => { + test('completed production + page 404 = sent to Google, never live', () => { + const [prod] = playReleases(PLAY_STATUS_FIRST_404); + expect(prod).toMatchObject({ phase: 'sent', state: 'completed', publicPage: 'notPublic', fraction: 1 }); + expect(playReleaseLabel(prod!)).toBe('Sent to Google (in review or not yet published)'); + const lane = laneOf('android', prod!); + expect(lane.at).toBe(2); // the review stage, not live / rollout + expect(lane.share).toBeNull(); + expect(laneText(lane)).not.toMatch(/^live/); + expect(storeNow(playReleases(PLAY_STATUS_FIRST_404), 'android').now).toBeNull(); + }); + test('first release + page 200 = live', () => { + const [prod] = playReleases(PLAY_STATUS_FIRST_200); + expect(prod).toMatchObject({ phase: 'live', publicPage: 'public' }); + expect(laneText(laneOf('android', prod!))).toBe('live'); + const t = releaseTrains(appleReleases(APPLE_STATUS_FIRST_REVIEW), playReleases(PLAY_STATUS_FIRST_200)); + expect(t.current).toMatchObject({ version: '1.0.0', android: { phase: 'live' }, ios: { phase: 'review' } }); + }); + test('an update after the first release: page 200 is not proof for the new versionCode unless the page shows it', () => { + const update = { publicPage: { state: 'public', versionName: null }, tracks: [ + { track: 'production', releases: [{ name: '1.1.0', versionCodes: ['5'], status: 'completed' }] }, + { track: 'internal', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed' }] }, + ] }; + const [prod] = playReleases(update); + expect(prod!.phase).toBe('released'); + expect(playReleaseLabel(prod!)).toBe('Released to production (Google may still be reviewing)'); + expect(laneText(laneOf('android', prod!))).toContain('Google may still be reviewing'); + expect(playReleases({ ...update, publicPage: { state: 'public', versionName: '1.1' } })[0]!.phase).toBe('live'); + }); + test('page not read = unknown, shown as unknown', () => { + const [prod] = playReleases({ tracks: PLAY_STATUS_FIRST_404.tracks }); + expect(prod).toMatchObject({ phase: 'released', publicPage: 'unknown' }); + expect(playReleaseLabel(prod!)).toContain('unknown'); + expect(laneOf('android', prod!).tone).toBe('neutral'); + }); +}); + +describe('public store page read', () => { + const answer = (status: number, body = '') => { const urls: string[] = []; globalThis.fetch = (async (u: string | URL | Request) => { urls.push(String(u)); return new Response(body, { status }); }) as unknown as typeof fetch; return urls; }; + test('404 = not public yet, 200 = public, the url has no auth and asks for English', async () => { + const urls = answer(404); + expect((await playPublicPage('com.example.first404', { noCache: true })).state).toBe('notPublic'); + expect(urls[0]).toBe('https://play.google.com/store/apps/details?id=com.example.first404&hl=en'); + answer(200, ''); + expect(await playPublicPage('com.example.first200', { noCache: true })).toMatchObject({ state: 'public', http: 200, versionName: '1.0.0' }); + }); + test('offline or a server error = unknown; unknown is never cached', async () => { + globalThis.fetch = (async () => { throw new Error('getaddrinfo ENOTFOUND play.google.com'); }) as unknown as typeof fetch; + const r = await playPublicPage('com.example.offline', { noCache: true }); + expect(r).toMatchObject({ state: 'unknown', http: null }); + expect(r.error).toContain('ENOTFOUND'); + answer(503); + expect((await playPublicPage('com.example.offline')).state).toBe('unknown'); + answer(404); + expect((await playPublicPage('com.example.offline')).state).toBe('notPublic'); + }); + test('answers are cached for a few minutes', async () => { + const urls = answer(404); + const pkg = `com.example.cache${Date.now()}`; + await playPublicPage(pkg); + answer(200); + expect((await playPublicPage(pkg)).state).toBe('notPublic'); + expect(urls).toHaveLength(1); + }); + test('the page version is read only from structured data', () => { + expect(pageVersion('{"softwareVersion": "2.3.1"}')).toBe('2.3.1'); + expect(pageVersion('{"softwareVersion":"Varies with device"}')).toBeNull(); + expect(pageVersion('
Version 1.0
')).toBeNull(); + }); +}); diff --git a/tests/portfolio.test.ts b/tests/portfolio.test.ts index 3d7d06b..c0a52d6 100644 --- a/tests/portfolio.test.ts +++ b/tests/portfolio.test.ts @@ -24,6 +24,7 @@ const play = { { track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] }, ], products: [{ productId: 'coins' }, { productId: 'no_ads' }, { sku: 'android_only' }], + publicPage: { state: 'public' }, }; describe('portfolio (apps, release trains, catalog parity)', () => { @@ -67,7 +68,7 @@ describe('portfolio (apps, release trains, catalog parity)', () => { const t = releaseTrains(appleReleases(apple), playReleases(play)); expect(t.current).toMatchObject({ version: '2.3.0', ios: { phase: 'review', build: '45' }, android: { phase: 'rollout', fraction: 0.2, build: '231' } }); expect(t.next).toMatchObject({ version: '2.4.0', ios: null, android: { phase: 'testing' } }); - const done = releaseTrains(appleReleases(apple), playReleases({ tracks: [play.tracks[0]!.releases[0] && { track: 'production', releases: [play.tracks[0]!.releases[0]] }] })); + const done = releaseTrains(appleReleases(apple), playReleases({ publicPage: play.publicPage, tracks: [play.tracks[0]!.releases[0] && { track: 'production', releases: [play.tracks[0]!.releases[0]] }] })); expect(done.current).toMatchObject({ version: '2.2.1', ios: { phase: 'live', build: '41' }, android: { phase: 'live', build: '220' } }); expect(done.next).toMatchObject({ version: '2.3.0', ios: { phase: 'review' }, android: null }); expect(releaseTrains([], [])).toEqual({ current: null, next: null }); diff --git a/tests/release-train.test.ts b/tests/release-train.test.ts index 01ac36f..b10a034 100644 --- a/tests/release-train.test.ts +++ b/tests/release-train.test.ts @@ -22,6 +22,7 @@ const play = { { track: 'production', releases: [{ name: '2.3.0', versionCodes: ['230'], status: 'inProgress', userFraction: 0.1 }, { name: '2.2.0', versionCodes: ['220'], status: 'completed' }] }, { track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] }, ], + publicPage: { state: 'public' }, }; const all: StoreRelease[] = [...appleReleases(apple), ...playReleases(play)]; diff --git a/tools/desktop-boot-check.ts b/tools/desktop-boot-check.ts index 86730e3..9210f58 100644 --- a/tools/desktop-boot-check.ts +++ b/tools/desktop-boot-check.ts @@ -21,7 +21,8 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { extname, join, resolve } from 'node:path'; import type { Browser, Page } from 'playwright'; -import { APPLE_STATUS_READY, APPLE_STATUS_UNRESOLVED, ownerDry, PLAY_STATUS } from '../apps/desktop/src/dev/submit-fixtures'; +import { APPLE_STATUS_FIRST_REVIEW, APPLE_STATUS_READY, APPLE_STATUS_UNRESOLVED, ownerDry, PLAY_STATUS, PLAY_STATUS_FIRST_200, PLAY_STATUS_FIRST_404 } from '../apps/desktop/src/dev/submit-fixtures'; +import { appleReleases, playReleases, releaseTrains } from '../cli/lib/portfolio'; const ROOT = resolve(import.meta.dir, '..'); const APP = join(ROOT, 'apps/desktop'); @@ -494,6 +495,92 @@ async function runSubmitCase(browser: Browser, sidecar: Sidecar, base: 'd3-full' return { name, ok: problems.length === 0, problems: [...new Set(problems)], visited, notes }; } +/** + * First release, live-shape store state (pitfall 56): App Store "1.0" waiting for review, Play production "1.0.0" + * completed with the public store page 404 (not public yet) or 200. The last live portfolio read (cache_get + * portfolio.status) carries that state; the check reads the Releases tab and the portfolio by DOM text: one row for + * 1.0 / 1.0.0, and no "Live" for Play while the page is 404. + */ +async function runReleaseStateCase(browser: Browser, sidecar: Sidecar, page404: boolean): Promise { + const name = `release-state (Play page ${page404 ? '404' : '200'})`; + const freeze = conf.app.security.freezePrototype === true; + const server = serve(DIST, cspHeader(conf.app.security.csp), false); + const ctx = await browser.newContext({ viewport: { width: 1360, height: 900 }, reducedMotion: 'reduce' }); + const page = await ctx.newPage(); + const problems: string[] = []; + const notes: string[] = []; + const unmocked = new Set(); + const logged: string[] = []; + const fx = liveFixture('d3-full'); + const play = page404 ? PLAY_STATUS_FIRST_404 : PLAY_STATUS_FIRST_200; + const live: LiveStores = { apple: APPLE_STATUS_FIRST_REVIEW, play, calls: [] }; + const base = host(fx, sidecar, unmocked, logged, live); + const ios = appleReleases(APPLE_STATUS_FIRST_REVIEW), android = playReleases(play); + const answer = async (cmd: string, a: Record): Promise => { + if (cmd === 'cache_get' && a.method === 'portfolio.status') { + const off = await base('portfolio_status', { live: false }) as { apps: Record[]; at: string }; + const apps = off.apps.map(x => ({ ...x, storeErrors: {}, release: { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] } })); + return { value: { apps, at: new Date().toISOString() }, at: new Date(Date.now() - 60_000).toISOString() }; + } + return base(cmd, a); + }; + await page.exposeFunction('__bootCheckHost', async (cmd: string, args: Record) => { + try { return { ok: (await answer(cmd, args)) ?? null }; } catch (e) { return { err: e }; } + }); + page.on('pageerror', e => problems.push(`uncaught: ${e.stack ?? e.message}`.split('\n').slice(0, 4).join(' | '))); + page.on('console', m => { if (m.type() === 'error') problems.push(`console.error: ${m.text().slice(0, 400)}`); }); + await page.addInitScript(initScript(freeze)); + let visited = 0; + const text = async (sel = '#content') => (await page.locator(sel).first().innerText().catch(() => '')).replace(/\s+/g, ' '); + const crashCheck = async (where: string) => { for (const c of (await state(page)).crash) problems.push(`${where}: error panel ${c}`); }; + const SENT = 'Sent to Google (in review or not yet published)'; + try { + await page.goto(`http://127.0.0.1:${server.port}/`, { waitUntil: 'load' }); + await page.waitForFunction(() => document.documentElement.dataset.booted === '1', null, { timeout: WAIT_MS }).catch(() => problems.push('React never drew the window (no data-booted)')); + await settle(page); + const wizard = page.locator('.wizard[role="dialog"]'); + if (await wizard.count()) { await wizard.press('Escape').catch(() => {}); await gone(page, '.wizard[role="dialog"]'); } + // the portfolio: Play's cell names the state, never "Live" while the page is 404 + await shows(page, '#content', page404 ? SENT : '1.0.0'); + const pf = await text(); + if (page404 && !pf.includes(SENT)) problems.push(`Portfolio: no "${SENT}"`); + await crashCheck('Portfolio'); + visited++; + const item = page.locator('nav.side .nav-app').filter({ hasText: /Prism Puddle|demo-game/ }).first(); + await item.click({ timeout: WAIT_MS }).catch(e => problems.push(`could not open the app: ${String(e).split('\n')[0]}`)); + await settle(page); + await page.locator('[role="tab"]#tab-releases').click({ timeout: WAIT_MS }).catch(() => {}); + await shows(page, '#content', 'Versions on the stores'); + await settle(page); + const rows = await page.locator('#content table tbody tr').evaluateAll(rs => rs.map(r => Array.from(r.querySelectorAll('td')).map(td => (td.textContent ?? '').trim()))); + notes.push(`history: ${JSON.stringify(rows)}`); + if (rows.length !== 1) problems.push(`Releases: want one row for 1.0 / 1.0.0, got ${rows.length}: ${JSON.stringify(rows)}`); + const row = rows[0] ?? []; + if (row[0] !== '1.0.0 / 1.0') problems.push(`Releases: version cell "${row[0]}" (want "1.0.0 / 1.0")`); + if (row[1] !== 'In review') problems.push(`Releases: App Store cell "${row[1]}" (want "In review")`); + if (row[3] !== (page404 ? SENT : 'Live')) problems.push(`Releases: Google Play cell "${row[3]}" (want "${page404 ? SENT : 'Live'}")`); + const rel = await text(); + if (/is not on (App Store|Google Play) yet/.test(rel)) problems.push('Releases: a lane says the version is not on a store (1.0 and 1.0.0 not joined)'); + for (const w of ['1.0 (3)', '1.0.0 (3)']) if (!rel.includes(w)) problems.push(`Releases: the lane does not show the store's own "${w}"`); + if (page404) { + if (!rel.includes(SENT)) problems.push(`Releases: no "${SENT}"`); + const heads = await page.locator('#content .train-head').evaluateAll(hs => hs.map(h => (h.textContent ?? '').trim())); + notes.push(`trains: ${JSON.stringify(heads)}`); + if (heads.some(h => /Live/.test(h))) problems.push(`Releases: a "Live" train with Play page 404: ${JSON.stringify(heads)}`); + } + await crashCheck('Releases'); + visited++; + } catch (e) { + problems.push(`case stopped: ${String(e).split('\n')[0]}`); + } finally { + await ctx.close(); + server.stop(true); + } + for (const l of logged) (l.startsWith('error') ? problems : notes).push(`webview.log: ${l}`); + if (unmocked.size) notes.push(`not answered (the window handled the rejection): ${[...unmocked].join(', ')}`); + return { name, ok: problems.length === 0, problems: [...new Set(problems)], visited, notes }; +} + /** * One headless browser for every case, as a browser server that is KILLED at the end (a throwaway profile, nothing to * flush): Google Chrome's graceful close takes 10-30 s after http pages (tests/helpers/browser.ts). Playwright's @@ -527,6 +614,7 @@ export async function bootCheck(): Promise { if (!ONLY.length || ONLY.includes('missing-bundle')) cases.push(() => runCase(browser, 'missing-bundle', sidecar, { breakBundle: true })); for (const base of ['d3-full', 'd1-missing-folders'] as const) for (const v of ['ready', 'unresolved'] as const) if (!ONLY.length || ONLY.includes('submit') || ONLY.includes(`submit-${v}`)) cases.push(() => runSubmitCase(browser, sidecar, base, v)); + for (const p404 of [true, false]) if (!ONLY.length || ONLY.includes('release-state')) cases.push(() => runReleaseStateCase(browser, sidecar, p404)); const results: CaseResult[] = new Array(cases.length); let next = 0; try { From 88a37e4735cffabeba51c8cff365d74d6b84e310 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 20:47:22 +0800 Subject: [PATCH 003/429] tests: unique package names for the public page cache test (the temp-folder cache outlives a run) --- tests/play-public-version-match.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/play-public-version-match.test.ts b/tests/play-public-version-match.test.ts index 2942134..7321826 100644 --- a/tests/play-public-version-match.test.ts +++ b/tests/play-public-version-match.test.ts @@ -94,14 +94,15 @@ describe('public store page read', () => { expect(await playPublicPage('com.example.first200', { noCache: true })).toMatchObject({ state: 'public', http: 200, versionName: '1.0.0' }); }); test('offline or a server error = unknown; unknown is never cached', async () => { + const off = `com.example.offline${Date.now()}`; globalThis.fetch = (async () => { throw new Error('getaddrinfo ENOTFOUND play.google.com'); }) as unknown as typeof fetch; - const r = await playPublicPage('com.example.offline', { noCache: true }); + const r = await playPublicPage(off, { noCache: true }); expect(r).toMatchObject({ state: 'unknown', http: null }); expect(r.error).toContain('ENOTFOUND'); answer(503); - expect((await playPublicPage('com.example.offline')).state).toBe('unknown'); + expect((await playPublicPage(off)).state).toBe('unknown'); answer(404); - expect((await playPublicPage('com.example.offline')).state).toBe('notPublic'); + expect((await playPublicPage(off)).state).toBe('notPublic'); }); test('answers are cached for a few minutes', async () => { const urls = answer(404); From f69c10d3a0fab146e4aca2711d6bd7decfc4c06e Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 20:48:01 +0800 Subject: [PATCH 004/429] tests: serve portfolio.status play fixture carries the public store page (200) --- tests/serve.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/serve.test.ts b/tests/serve.test.ts index ac31ca3..319d5bf 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -254,7 +254,7 @@ describe('serve --stdio: session', () => { const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary } : argv[0] === 'check' ? { data: { ok: true, problems: [], warnings: ['w'] } } : argv[0] === 'apple' ? { code: 1, out: 'error: ASC_KEY_ID and ASC_ISSUER_ID are not set' } - : argv[0] === 'play' ? { data: { tracks: [{ track: 'production', releases: [{ name: '1.2.0 (12)', versionCodes: ['12'], status: 'completed' }] }, { track: 'beta', releases: [{ name: '1.3.0', versionCodes: ['13'], status: 'completed' }] }], products: [{ productId: 'coins' }] } } : {}); + : argv[0] === 'play' ? { data: { tracks: [{ track: 'production', releases: [{ name: '1.2.0 (12)', versionCodes: ['12'], status: 'completed' }] }, { track: 'beta', releases: [{ name: '1.3.0', versionCodes: ['13'], status: 'completed' }] }], products: [{ productId: 'coins' }], publicPage: { state: 'public' } } } : {}); const r = resOf(await call('portfolio.status', { projects: [DEMO, '/nope/game'], live: true })) as { apps: J[] }; expect(r.apps[0]).toMatchObject({ project: DEMO, app: { id: DEMO, name: 'Demo', platforms: { ios: { bundleId: 'com.example.demo' }, android: { packageName: 'com.example.demo' } } }, check: { ok: true, warnings: ['w'] }, storeErrors: { ios: 'ASC_KEY_ID and ASC_ISSUER_ID are not set' }, ok: false }); From 89256f1e80869b7e7beb975ec5c0b03b67b2ebd7 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 23:20:04 +0800 Subject: [PATCH 005/429] Google API errors as typed findings, never raw JSON: cli/lib/google-errors.ts parses SERVICE_DISABLED (api-disabled: service, Cloud project, console page), PERMISSION_DENIED (no-app-access: which app, Users and permissions), 401 / invalid_grant (auth-revoked) and 429 (quota); health / analytics print one line with the URL, raw text in detail and the log; desktop Health tab: the line, 'Turn it on in Google Cloud' and 'Check again', raw text in a collapsed Details; Portfolio shows a Cloud project blocking several apps once. Findings exit codes are results: the sidecar reports outcome (ok / findings / declined / failed) and the command's own error line; scan / check / validate / health exit 1 with findings show and cache the findings; no bare 'Exit code N' anywhere. tests/google-errors.test.ts, boot check errors cases (api-disabled, scan-findings, scan-failed) (pitfall 57) --- CHANGELOG.md | 12 +++ apps/desktop/src-tauri/src/commands.rs | 10 +- apps/desktop/src/dev/error-fixtures.ts | 64 ++++++++++++ apps/desktop/src/i18n/en.ts | 20 +++- apps/desktop/src/i18n/tr.ts | 20 +++- apps/desktop/src/lib/model.ts | 10 +- apps/desktop/src/lib/results.ts | 20 ++++ apps/desktop/src/screens/AppFolders.tsx | 3 +- apps/desktop/src/screens/Portfolio.tsx | 27 ++++- apps/desktop/src/screens/tabs/Health.tsx | 5 +- apps/desktop/src/screens/tabs/Releases.tsx | 3 +- apps/desktop/src/store.tsx | 9 +- apps/desktop/src/ui/ConsoleFill.tsx | 5 +- apps/desktop/src/ui/ConsolePlan.tsx | 5 +- apps/desktop/src/ui/OwnerAction.tsx | 3 +- apps/desktop/src/ui/StoreError.tsx | 102 +++++++++++++++++++ cli/analytics.ts | 5 +- cli/health.ts | 8 +- cli/lib/analytics.ts | 3 +- cli/lib/desktop-protocol.ts | 42 ++++++++ cli/lib/google-errors.ts | 98 ++++++++++++++++++ cli/lib/health.ts | 24 +++-- cli/lib/runner.ts | 7 +- cli/serve.ts | 8 +- skills/store-pitfalls/SKILL.md | 11 +++ tests/google-errors.test.ts | 76 ++++++++++++++ tests/play-post-reads.test.ts | 4 +- tools/desktop-boot-check.ts | 109 +++++++++++++++++++++ 28 files changed, 666 insertions(+), 47 deletions(-) create mode 100644 apps/desktop/src/dev/error-fixtures.ts create mode 100644 apps/desktop/src/lib/results.ts create mode 100644 apps/desktop/src/ui/StoreError.tsx create mode 100644 cli/lib/google-errors.ts create mode 100644 tests/google-errors.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c2079f3..327617c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- **Google API errors in words, not JSON.** Google's error bodies are parsed centrally (`cli/lib/google-errors.ts`) + into typed findings: `api-disabled` (403 SERVICE_DISABLED: service, Cloud project id, the console page to turn it + on), `no-app-access` (403 PERMISSION_DENIED: which app, the Users and permissions step), `auth-revoked` (401, + invalid_grant) and `quota` (429, RESOURCE_EXHAUSTED). `health`, `analytics` and the health JSON say one line with the + URL ("Crash and ANR data needs the Google Play Developer Reporting API turned on in Google Cloud project . Turn + it on: ..."); the raw text stays in `detail` and the log. The desktop Health tab shows that line with "Turn it on in + Google Cloud" and "Check again", the raw text only in a collapsed Details; the Portfolio shows a Cloud project that + blocks several apps once ("1 Google Cloud project needs an API turned on: affects ..."). Pitfall 57. +- **Findings are results, not errors, in the desktop.** `scan`, `check`, `validate` and `health` exit 1 when they find + problems (by design); the sidecar now reports an `outcome` (ok / findings / declined / failed) and, for a real + failure, the command's own `error` line (stderr's last "error: ..." line). The Checks tab lists the findings instead + of "Exit code 1", findings results are cached, and every place that showed a bare "Exit code N" shows the error line. - **Play "Live" only when the store page proves it.** The Play Developer API has no review state: a production release reads `completed` while Google still reviews it. `play status` now checks the public store page (no auth, fast timeout, cached 5 minutes) and adds `publicPage` to its JSON: page 404 = "Sent to Google (in review or not yet diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 5310907..71c31bb 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -205,7 +205,7 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_ o.insert("credentials".into(), Value::Object(creds)); } let res = r.call_job(&method, p, job.as_deref()).await?; - if res["ok"] == Value::Bool(true) && !res["data"].is_null() { + if readable(&res) { let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso()); } return Ok(res); @@ -223,13 +223,19 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_ let res = r.call_job(&method, p, job.as_deref()).await?; if let Some(id) = cache_project { // only results that read something: a failed store read must not hide the last good one - if res["ok"] == Value::Bool(true) && !res["data"].is_null() { + if readable(&res) { let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso()); } } Ok(res) } +/// A result worth caching: it carries data and is ok, or "findings" (scan / check / validate / health exit 1 with their +/// result printed: by design, not a failure). A failed read must not hide the last good one. +fn readable(res: &Value) -> bool { + !res["data"].is_null() && (res["ok"] == Value::Bool(true) || res["outcome"] == Value::String("findings".into())) +} + /// The last cached result of a read (`project_id` "*" for the portfolio), with its time; null when never read. #[tauri::command] pub fn cache_get(window: WebviewWindow, state: State<'_, AppState>, method: String, project_id: String, args: Option) -> Res> { diff --git a/apps/desktop/src/dev/error-fixtures.ts b/apps/desktop/src/dev/error-fixtures.ts new file mode 100644 index 0000000..377519d --- /dev/null +++ b/apps/desktop/src/dev/error-fixtures.ts @@ -0,0 +1,64 @@ +// Live-shape failures for the boot check and tests: Google's 403 SERVICE_DISABLED body exactly as the Play Developer +// Reporting API answers it (the project id is an example), the health snapshot `storebound health --json` writes for +// it, and `storebound scan --json` results: findings with exit 1 (by design) and a real failure with its error line. +import { errorBody } from '../../../../cli/lib/http'; +import { storeReadError } from '../../../../cli/lib/google-errors'; +import { errorLine } from '../../../../cli/lib/desktop-protocol'; + +export const EXAMPLE_CLOUD_PROJECT = '123456789000'; +export const SERVICE_DISABLED_403 = `{ + "error": { + "code": 403, + "message": "Google Play Developer Reporting API has not been used in project ${EXAMPLE_CLOUD_PROJECT} before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/playdeveloperreporting.googleapis.com/overview?project=${EXAMPLE_CLOUD_PROJECT} then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.", + "status": "PERMISSION_DENIED", + "details": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "SERVICE_DISABLED", + "domain": "googleapis.com", + "metadata": { + "activationUrl": "https://console.developers.google.com/apis/api/playdeveloperreporting.googleapis.com/overview?project=${EXAMPLE_CLOUD_PROJECT}", + "service": "playdeveloperreporting.googleapis.com", + "consumer": "projects/${EXAMPLE_CLOUD_PROJECT}", + "serviceTitle": "Google Play Developer Reporting API", + "containerInfo": "${EXAMPLE_CLOUD_PROJECT}" + } + }, + { + "@type": "type.googleapis.com/google.rpc.LocalizedMessage", + "locale": "en-US", + "message": "Google Play Developer Reporting API has not been used in project ${EXAMPLE_CLOUD_PROJECT} before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/playdeveloperreporting.googleapis.com/overview?project=${EXAMPLE_CLOUD_PROJECT} then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry." + }, + { + "@type": "type.googleapis.com/google.rpc.Help", + "links": [{ "description": "Google developers console API activation", "url": "https://console.developers.google.com/apis/api/playdeveloperreporting.googleapis.com/overview?project=${EXAMPLE_CLOUD_PROJECT}" }] + } + ] + } +}`; + +/** The Error message storebound's Google client throws for it (play/google.ts). */ +export const serviceDisabledMessage = (pkg: string): string => `GET /v1beta1/apps/${pkg}/crashRateMetricSet -> 403 ${errorBody(SERVICE_DISABLED_403, 800)}`; + +/** `storebound health --json` when the Reporting API is off. */ +export const healthApiDisabled = (pkg: string) => ({ date: '2026-10-13', play: storeReadError(serviceDisabledMessage(pkg), { app: pkg }) }); + +/** `storebound scan --json` that found problems: exit 1 by design, the result still printed. */ +export const SCAN_FINDINGS = { + method: 'scan', ok: false, exitCode: 1, dryRun: false, command: 'storebound scan --json', outcome: 'findings' as const, + output: '12:00:00 [scan] 41 files\n12:00:00 [scan] 1 blocker, 0 warnings', + data: { + stacks: ['flutter'], sdks: [], counts: { blocker: 1, high: 0, medium: 0, low: 0, accepted: 0 }, + declarations: { changed: false, items: [] }, + findings: [{ rule: 'account-deletion', store: 'apple', severity: 'blocker', guideline: '5.1.1(v)', title: 'Sign-up without in-app account deletion', + evidence: [{ file: 'lib/auth/sign_up.dart', line: 12, text: 'createUserWithEmailAndPassword' }], fix: 'Add a "Delete account" action in the app settings', skill: 'account-deletion' }], + }, +}; + +/** A real failure: the config does not load; the sidecar sends the command's own error line. */ +const SCAN_STDERR = '\nerror: storebound.config.ts: app.name is missing'; +export const SCAN_FAILED = { + method: 'scan', ok: false, exitCode: 1, dryRun: false, command: 'storebound scan --json', outcome: 'failed' as const, + output: `12:00:00 [scan] loading the config${SCAN_STDERR}`, error: errorLine(SCAN_STDERR, ''), +}; +export const SCAN_FAILED_LINE = 'storebound.config.ts: app.name is missing'; diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 15451be..b400165 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -66,7 +66,25 @@ export const en = { 'common.unknown': 'Unknown', 'common.cancel': 'Cancel', 'common.close': 'Close', - 'common.exit': 'Exit code {code}', + 'common.exitNoMessage': 'The command stopped without an error message (exit {code}); the log has the details', + 'gerr.apiDisabled': '{what} needs the {service} turned on in Google Cloud project {project}.', + 'gerr.what.reporting': 'Crash and ANR data', + 'gerr.what.publisher': 'Reading the app on Google Play', + 'gerr.what.storage': 'Play statistics', + 'gerr.what.other': 'This read', + 'gerr.projectUnknown': '(the service account\'s project)', + 'gerr.turnOn': 'Turn it on in Google Cloud', + 'gerr.checkAgain': 'Check again', + 'gerr.noAccess': 'The service account has no access to {app} in Play Console: add it under Users and permissions.', + 'gerr.thisApp': 'this app', + 'gerr.openUsers': 'Open Users and permissions', + 'gerr.revoked': 'Google refused the service account key: it was revoked, deleted or has expired. Add a new JSON key in Accounts.', + 'gerr.quota': 'The Google API quota is used up for now. Try again later.', + 'gerr.details': 'Details', + 'gerr.openFailed': 'Could not open the page', + 'gerr.portfolio': '{count} Google Cloud projects need an API turned on: affects {apps}', + 'gerr.portfolio_one': '1 Google Cloud project needs an API turned on: affects {apps}', + 'gerr.portfolioProject': 'Project {project}: {service}', 'common.cachedFrom': 'Last read {when} (saved copy)', 'common.readWhen': 'Read {when}', 'common.readFailedKeep': 'The last read failed, so this shows the previous one: {error}', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index f02df46..617b88a 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -68,7 +68,25 @@ export const tr: Record = { 'common.unknown': 'Bilinmiyor', 'common.cancel': 'İptal', 'common.close': 'Kapat', - 'common.exit': 'Çıkış kodu {code}', + 'common.exitNoMessage': 'Komut bir hata mesajı vermeden durdu (çıkış {code}); ayrıntılar günlükte', + 'gerr.apiDisabled': '{what} için Google Cloud projesi {project} içinde {service} açılmalı.', + 'gerr.what.reporting': 'Çökme ve ANR verileri', + 'gerr.what.publisher': 'Uygulamayı Google Play\'den okumak', + 'gerr.what.storage': 'Play istatistikleri', + 'gerr.what.other': 'Bu okuma', + 'gerr.projectUnknown': '(hizmet hesabının projesi)', + 'gerr.turnOn': 'Google Cloud\'da aç', + 'gerr.checkAgain': 'Tekrar kontrol et', + 'gerr.noAccess': 'Hizmet hesabının Play Console\'da {app} için erişimi yok: Kullanıcılar ve izinler bölümünden ekleyin.', + 'gerr.thisApp': 'bu uygulama', + 'gerr.openUsers': 'Kullanıcılar ve izinler\'i aç', + 'gerr.revoked': 'Google hizmet hesabı anahtarını reddetti: iptal edilmiş, silinmiş ya da süresi dolmuş. Hesaplar\'da yeni bir JSON anahtarı ekleyin.', + 'gerr.quota': 'Google API kotası şimdilik doldu. Daha sonra tekrar deneyin.', + 'gerr.details': 'Ayrıntılar', + 'gerr.openFailed': 'Sayfa açılamadı', + 'gerr.portfolio': '{count} Google Cloud projesinde bir API açılmalı: etkilenenler {apps}', + 'gerr.portfolio_one': '1 Google Cloud projesinde bir API açılmalı: etkilenenler {apps}', + 'gerr.portfolioProject': 'Proje {project}: {service}', 'common.cachedFrom': 'Son okuma {when} (kayıtlı kopya)', 'common.readWhen': '{when} okundu', 'common.readFailedKeep': 'Son okuma başarısız oldu, bu yüzden bir öncekini gösteriyor: {error}', diff --git a/apps/desktop/src/lib/model.ts b/apps/desktop/src/lib/model.ts index ef209a5..7ee1677 100644 --- a/apps/desktop/src/lib/model.ts +++ b/apps/desktop/src/lib/model.ts @@ -1,6 +1,7 @@ // Pure view models for the screens: release timeline stages, health series against the store thresholds, review // inbox stats, catalog parity matrix, the portfolio's "needs attention" list, and the command palette matcher. // "Unknown, never false": every derivation keeps "not read" apart from "none" / "ok". +import { plainError } from '../../../../cli/lib/google-errors'; import type { AppStatus, ProjectSummary } from '../api'; import { t } from '../i18n'; @@ -23,7 +24,8 @@ export interface AppleHealth { signatures: { build: string; type: string; signature: string; weight: number }[]; betaCrashes: { build: string; count: number }[]; } -export interface HealthSnapshot { date: string; play?: PlayHealth | { error: string }; apple?: AppleHealth | { error: string } } +export type StoreReadError = import('../../../../cli/lib/health').StoreReadError; +export interface HealthSnapshot { date: string; play?: PlayHealth | StoreReadError; apple?: AppleHealth | StoreReadError } export interface Review { store: 'apple' | 'play'; id: string; rating: number; title?: string; body: string; where?: string; date: string; appVersion?: string; reply?: { text: string; date?: string; state?: string } } export interface TfGroup { id: string; name: string; internal: boolean; testers: number; builds: number | 'all'; publicLink: boolean } export interface TfBuild { version: string | null; build: string | null; processing: string | null; internal: string | null; external: string | null; uploaded: string | null } @@ -47,7 +49,7 @@ export interface ScanResult { declarations: { changed: boolean; items: { area: string; what: string; value: string; status: 'detected' | 'ask'; evidence: { file: string; line: number }[] }[] }; } -export const isError = (x: unknown): x is { error: string } => !!x && typeof x === 'object' && typeof (x as { error?: unknown }).error === 'string'; +export const isError = (x: unknown): x is StoreReadError => !!x && typeof x === 'object' && typeof (x as { error?: unknown }).error === 'string'; // ---- Release timeline ---- // The stages and lanes live in cli/lib/train.ts, shared with `storebound release status | plan`. @@ -139,8 +141,8 @@ export function attention(projectId: string, name: string, e: AppStatus | undefi for (const w of (e.check?.warnings ?? []).slice(0, 3)) out.push({ ...base, tone: 'warn', text: w, tab: 'checks' }); const l = live ?? (e.release.source === 'live' ? e : undefined); if (l) { - if (l.storeErrors.ios) out.push({ ...base, tone: 'warn', text: t('att.storeError', { store: 'App Store', error: l.storeErrors.ios }), tab: 'releases' }); - if (l.storeErrors.android) out.push({ ...base, tone: 'warn', text: t('att.storeError', { store: 'Google Play', error: l.storeErrors.android }), tab: 'releases' }); + if (l.storeErrors.ios) out.push({ ...base, tone: 'warn', text: t('att.storeError', { store: 'App Store', error: plainError(l.storeErrors.ios) }), tab: 'releases' }); + if (l.storeErrors.android) out.push({ ...base, tone: 'warn', text: t('att.storeError', { store: 'Google Play', error: plainError(l.storeErrors.android) }), tab: 'releases' }); for (const r of l.release.all ?? []) { if (r.phase === 'rejected') out.push({ ...base, tone: 'bad', text: t('att.rejected', { store: r.store === 'ios' ? 'App Store' : 'Google Play', version: r.version ?? '' }), tab: 'releases' }); if (r.phase === 'halted') out.push({ ...base, tone: 'bad', text: t('att.halted', { store: r.store === 'ios' ? 'App Store' : 'Google Play', version: r.version ?? '' }), tab: 'releases' }); diff --git a/apps/desktop/src/lib/results.ts b/apps/desktop/src/lib/results.ts new file mode 100644 index 0000000..d40bd90 --- /dev/null +++ b/apps/desktop/src/lib/results.ts @@ -0,0 +1,20 @@ +// What a command's result means for the window: exit 1 of scan / check / validate / health with the --json result +// printed is "found problems" (shown as the findings), 3 is "declined"; only a real failure is an error, and then in +// the command's own words (its error line, Google errors as one plain line), never a bare "Exit code N". +import { errorLine, type Outcome, outcomeOf, type ToolResult } from '../../../../cli/lib/desktop-protocol'; +import { plainError } from '../../../../cli/lib/google-errors'; +import { t } from '../i18n'; + +export function outcome(method: string, r: Pick): Outcome { + return r.outcome ?? outcomeOf(method, r.exitCode, r.data !== undefined); +} + +/** The result carries data the screen can show (ok, or findings). */ +export const usable = (method: string, r: Pick): boolean => + r.data !== undefined && ['ok', 'findings'].includes(outcome(method, r)); + +/** A failed run in words: the command's error line (Google JSON bodies as one plain line). */ +export function failureText(r: Pick): string { + const line = r.error || errorLine('', r.output ?? ''); + return line ? plainError(line) : t('common.exitNoMessage', { code: r.exitCode }); +} diff --git a/apps/desktop/src/screens/AppFolders.tsx b/apps/desktop/src/screens/AppFolders.tsx index 5e9a832..1162a6f 100644 --- a/apps/desktop/src/screens/AppFolders.tsx +++ b/apps/desktop/src/screens/AppFolders.tsx @@ -1,5 +1,6 @@ // Workspace: app folders (one storebound.config.ts per app), which store accounts each app uses, and starting a new // folder from the templates (`storebound init` with a profile, confirmed in a native dialog). +import { failureText } from '../lib/results'; import { useEffect, useRef, useState } from 'react'; import { api, errorText, newJob, onProgress, type Project, type ToolResult, type WriteOutcome } from '../api'; import { devSwitch } from '../dev/switches'; @@ -69,7 +70,7 @@ export function AppFolders() { const apple = d.accounts.filter(a => a.kind === 'apple'); const status = !run ? '' : run.error ? t('run.failed') : !run.result ? t('run.running') : run.outcome ? (run.outcome.confirmed ? t('run.applied') : run.outcome.stage === 'dialog' ? t('run.cancelled') : t('run.dryFailed')) - : run.result.ok ? t('run.done') : t('common.exit', { code: run.result.exitCode }); + : run.result.ok ? t('run.done') : failureText(run.result); return (
diff --git a/apps/desktop/src/screens/Portfolio.tsx b/apps/desktop/src/screens/Portfolio.tsx index 3078349..1048b5c 100644 --- a/apps/desktop/src/screens/Portfolio.tsx +++ b/apps/desktop/src/screens/Portfolio.tsx @@ -1,8 +1,10 @@ // Portfolio: every app of every studio on both stores. KPIs, a toolbar (search, studio chips with counts, sort, // grouping), one row per app (live version and state per store with its place on the release track, next version, // crash rate, catalog parity, config check), grouped by studio; then what needs attention and the workspace state. +import { plainError } from '../../../../cli/lib/google-errors'; +import { BlockedProjectsNotice, blockedProjects } from '../ui/StoreError'; import { useEffect, useMemo, useState } from 'react'; -import { api, type AppStatus, type StoreRelease, type ToolResult } from '../api'; +import { api, type AppStatus, newJob, type StoreRelease, type ToolResult } from '../api'; import { type Key, t } from '../i18n'; import { ago, pct, share } from '../lib/format'; import { filterSort, groupByStudio, type ListRow, type SortBy, studioCounts, type UnifiedApp } from '../lib/identity'; @@ -37,7 +39,7 @@ function StoreCell({ e, store, on }: { e: AppStatus | undefined; store: 'ios' | if (!on) return {t('app.notOnStore')}; if (!e) return {t('common.unknown')}; const err = e.storeErrors[store]; - if (err) return {t('portfolio.unreadable')}; + if (err) return {t('portfolio.unreadable')}; const all = e.release.all ?? [e.release.current?.ios, e.release.current?.android, e.release.next?.ios, e.release.next?.android].filter((x): x is StoreRelease => !!x); const { now, next } = storeNow(all, store); const r = now ?? next; @@ -67,9 +69,9 @@ function NextCell({ e }: { e: AppStatus | undefined }) { } /** Last cached health read of every app (the Health tab reads it; the portfolio only shows what is saved). */ -function useCachedHealth(targets: string[]): Record { +function useCachedHealth(targets: string[], round = 0): Record { const [m, set] = useState>({}); - const key = targets.join(); + const key = targets.join() + '#' + round; useEffect(() => { for (const id of targets) { api.cached('health', id).then(c => set(x => ({ ...x, [id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {}); @@ -131,7 +133,21 @@ export function Portfolio() { const [query, setQuery] = useState(''); const setView = (v: Partial) => setViewState(x => { const n = { ...x, ...v }; try { localStorage.setItem(VIEW_KEY, JSON.stringify(n)); } catch { /* private mode */ } return n; }); const visible = useMemo(() => d.apps.filter(a => !a.ignored), [d.apps]); - const health = useCachedHealth(visible.map(a => a.target)); + const [round, setRound] = useState(0); + const [rechecking, setRechecking] = useState(false); + const health = useCachedHealth(visible.map(a => a.target), round); + const blocked = useMemo(() => blockedProjects(visible.map(a => { + const h = health[a.target]?.h, l = d.liveFor(a); + return { app: a.name, errors: [h?.play && isError(h.play) ? h.play : null, l?.storeErrors.android] }; + })), [visible, health, d]); + // "Check again": read health of the blocked apps again (one at a time: the same Cloud project's quota), then the cache + const recheck = async () => { + setRechecking(true); + const names = new Set(blocked.flatMap(b => b.apps)); + for (const a of visible.filter(x => names.has(x.name))) await api.call('health', a.target, { args: {} }, newJob('health')).catch(() => null); + setRechecking(false); + setRound(n => n + 1); + }; const open = (a: UnifiedApp) => nav.go({ screen: 'app', appId: a.key, tab: 'releases' }); const all = useMemo(() => visible.map(app => { @@ -222,6 +238,7 @@ export function Portfolio() {
{d.portfolioError && {d.portfolioError}} + {neverImported > 0 && d.importApps()} disabled={d.importBusy}>{t('action.importApps')}}>{t('portfolio.notImported', { count: neverImported })}} {!known && d.ready && d.refreshPortfolio(true)}>{t('action.readStores')}}>{t('portfolio.notReadNotice')}} diff --git a/apps/desktop/src/screens/tabs/Health.tsx b/apps/desktop/src/screens/tabs/Health.tsx index 86f180f..d89aa2b 100644 --- a/apps/desktop/src/screens/tabs/Health.tsx +++ b/apps/desktop/src/screens/tabs/Health.tsx @@ -9,6 +9,7 @@ import { Icon } from '../../ui/icons'; import { Bar, Card, Chip, Empty, ErrorFoot, Notice, Skeleton, Sparkline } from '../../ui/kit'; import { exportName, healthMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; +import { StoreReadNotice } from '../../ui/StoreError'; function Metric({ title, s }: { title: string; s: Series }) { return ( @@ -146,9 +147,9 @@ export function HealthTab({ app }: { app: UnifiedApp }) {
{r.error && {t('common.readFailedKeep', { error: r.error })}}

Google Play

- {h.play === undefined ? {t('health.noPlay')} : isError(h.play) ? {t('health.unreadable', { store: 'Google Play', error: h.play.error })} : } + {h.play === undefined ? {t('health.noPlay')} : isError(h.play) ? : }

App Store

- {h.apple === undefined ? {t('health.noApple')} : isError(h.apple) ? {t('health.unreadable', { store: 'App Store', error: h.apple.error })} : } + {h.apple === undefined ? {t('health.noApple')} : isError(h.apple) ? : } ); } diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index caab9e7..0fcc87a 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -2,6 +2,7 @@ // rollout %), then every version read from the stores, then sending for review (Submit.tsx): App Store submit / // resubmit / in-app purchases and the Google Play production release as owner actions, the Play steps without an API // as console plans. Releasing an approved version (manual release) stays in App Store Connect. +import { plainError } from '../../../../../cli/lib/google-errors'; import { useState } from 'react'; import type { ReleaseTrain, StoreRelease } from '../../api'; import type { UnifiedApp } from '../../lib/identity'; @@ -155,7 +156,7 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { const errs = Object.entries(l.storeErrors); return ( <> - {errs.map(([s, msg]) => {t('releases.storeUnreadable', { store: storeName(s as 'ios'), error: msg })})} + {errs.map(([s, msg]) => {t('releases.storeUnreadable', { store: storeName(s as 'ios'), error: plainError(msg) })})} {l.release.next && } {l.release.current && } {!l.release.next && !l.release.current && {t('releases.noVersionsText')}} diff --git a/apps/desktop/src/store.tsx b/apps/desktop/src/store.tsx index c9b32fb..c1935a4 100644 --- a/apps/desktop/src/store.tsx +++ b/apps/desktop/src/store.tsx @@ -14,6 +14,7 @@ import { setCrashContext } from './lib/crash'; import { normalizeAccounts, normalizeProjects, normalizeWorkspace } from './lib/normalize'; import { keepLines, progressOf } from './lib/progress'; import { fixHint } from './lib/views'; +import { failureText, usable } from './lib/results'; export type ToastKind = 'job' | 'ok' | 'bad' | 'info'; export interface Toast { @@ -336,13 +337,13 @@ export function useWrite(projectId: string | null) { 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: withHint(lastLine(o.dryRun.output) || undefined), progress: undefined, job: undefined }); + if (o.stage === 'dry-run') d.updateToast(tid, { kind: 'bad', title: t('write.dryFailed'), detail: withHint(failureText(o.dryRun)), 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?.(); } // exit 3: the command stopped for an owner decision it did not get (a price change of a live product: the // Catalog tab's owner action applies it); everything else it could do was done else if (o.result?.exitCode === 3) { d.updateToast(tid, { kind: 'info', title: t('write.declined'), detail: lastLine(o.result.output) || undefined, progress: undefined, job: undefined }); w.after?.(); } - else d.updateToast(tid, { kind: 'bad', title: t('write.failed'), detail: withHint(lastLine(o.result?.output ?? '') || undefined), progress: undefined, job: undefined }); + else d.updateToast(tid, { kind: 'bad', title: t('write.failed'), detail: withHint(o.result ? failureText(o.result) : undefined), progress: undefined, job: undefined }); return o; } catch (e) { const msg = errorText(e); @@ -387,12 +388,12 @@ export function useRead(target: string, method: string, o: { network: boolean try { const r = await api.call(method, target, { args: JSON.parse(argsKey) as Record }, job); if (my !== seq.current) return; - if (r.ok && r.data !== undefined) { + if (usable(method, r)) { notifyAfterRead(method, dataRef.current, r.data, d.settings, o.appName); set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command }); if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined }); } else { - const msg = lastLine(r.output) || t('common.exit', { code: r.exitCode }); + const msg = failureText(r); set(x => ({ ...x, loading: false, error: msg, command: r.command })); if (tid) d.updateToast(tid, { kind: 'bad', title: t('toast.readFailedWhat', { what: o.title ?? method }), detail: withHint(msg), progress: undefined, job: undefined }); } diff --git a/apps/desktop/src/ui/ConsoleFill.tsx b/apps/desktop/src/ui/ConsoleFill.tsx index 9a7a1f3..b7b59ce 100644 --- a/apps/desktop/src/ui/ConsoleFill.tsx +++ b/apps/desktop/src/ui/ConsoleFill.tsx @@ -4,6 +4,7 @@ // write_with_confirm (the host shows the answers again in a native dialog and mints the token only on its button) -> // a visible browser the owner signs in to; storebound fills the fields, moves through the pages and never submits or publishes. The run // lasts until the owner closes that browser; Cancel here stops the command, which closes it. +import { failureText } from '../lib/results'; import { type KeyboardEvent, useEffect, useRef, useState } from 'react'; import { api, type ConsoleFillResult, type ConsoleForm, errorText, newJob, onProgress, type Project, type ToolResult } from '../api'; import { type Key, t } from '../i18n'; @@ -34,7 +35,7 @@ export function ConsoleFillButton({ project, form, small = true, primary }: { pr setSt({ s: 'dry' }); try { const r = await api.call('console.fill', project.id, { args: { form } }, newJob('console.fill-dry')); - if (!r.ok || !r.data) { setSt({ s: 'idle' }); d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: tail(r.output) || undefined }); return; } + if (!r.ok || !r.data) { setSt({ s: 'idle' }); d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: failureText(r) }); return; } setSt({ s: 'review', data: r.data }); } catch (e) { setSt({ s: 'idle' }); @@ -55,7 +56,7 @@ export function ConsoleFillButton({ project, form, small = true, primary }: { pr else if (o.stage === 'dry-run') setSt({ s: 'done', data, result: null, ok: false, detail: tail(o.dryRun.output) }); else { const res = (o.result?.data ?? null) as ConsoleFillResult | null; - setSt({ s: 'done', data, result: res, ok: !!o.result?.ok, detail: o.result?.ok ? undefined : tail(o.result?.output ?? '') }); + setSt({ s: 'done', data, result: res, ok: !!o.result?.ok, detail: o.result?.ok ? undefined : o.result ? failureText(o.result) : undefined }); } } catch (e) { const msg = errorText(e); diff --git a/apps/desktop/src/ui/ConsolePlan.tsx b/apps/desktop/src/ui/ConsolePlan.tsx index 3de0bb8..d4fb356 100644 --- a/apps/desktop/src/ui/ConsolePlan.tsx +++ b/apps/desktop/src/ui/ConsolePlan.tsx @@ -5,6 +5,7 @@ // record and the age rating). Nothing here clicks in a console: the owner's AI agent (or the owner) drives the page // with this plan, `Copy plan` hands it over as JSON; "Fill in console" (ui/ConsoleFill.tsx) is the scripted fast path // where it exists. Every form of `console plan`, including the Play pages added for the first production release. +import { failureText } from '../lib/results'; import { type KeyboardEvent, useEffect, useRef, useState } from 'react'; import { api, errorText, newJob, type Project, type ToolResult } from '../api'; import { type Key, t } from '../i18n'; @@ -61,7 +62,7 @@ export function ConsolePlanButton({ project, form, primary, label }: { project: setBusy(true); try { const r = await api.call('console.plan', project.id, { args: { form } }, newJob('console.plan')); - if (!r.ok || !r.data) d.toast({ kind: 'bad', title: t('cp.failed', { form: nameOf(form) }), detail: r.output.trim().split('\n').at(-1) }); + if (!r.ok || !r.data) d.toast({ kind: 'bad', title: t('cp.failed', { form: nameOf(form) }), detail: failureText(r) }); else setPlan(r.data); } catch (e) { d.toast({ kind: 'bad', title: t('cp.failed', { form: nameOf(form) }), detail: errorText(e) }); } finally { setBusy(false); } }; @@ -88,7 +89,7 @@ function PlanPanel({ project, plan, onClose }: { project: Project; plan: Plan; o try { const r = await api.call('console.verify', project.id, { args: { form: plan.form, ...(text.trim() ? { text: text.trim() } : {}) } }, newJob('console.verify')); if (r.data) setVerify({ busy: false, result: r.data }); - else setVerify({ busy: false, error: r.output.trim().split('\n').at(-1)?.replace(/^\S+ \[[^\]]+\] /, '') ?? t('common.exit', { code: r.exitCode }) }); + else setVerify({ busy: false, error: failureText(r) }); } catch (e) { setVerify({ busy: false, error: errorText(e) }); } }; const copy = () => { navigator.clipboard?.writeText(JSON.stringify(plan, null, 2)).then(() => d.toast({ kind: 'ok', title: t('cp.copied') }), () => {}); }; diff --git a/apps/desktop/src/ui/OwnerAction.tsx b/apps/desktop/src/ui/OwnerAction.tsx index d8bf460..6e64690 100644 --- a/apps/desktop/src/ui/OwnerAction.tsx +++ b/apps/desktop/src/ui/OwnerAction.tsx @@ -4,6 +4,7 @@ // the dialog's own button. While the real run goes (a submit retries up to 10 minutes while Apple says "not ready // yet"), its progress lines stream into the panel; Cancel stops the command. Used for submit for review, resubmit, // in-app purchases to review, the Play production release and price changes of existing products. +import { failureText } from '../lib/results'; import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from 'react'; import { api, errorText, newJob, onProgress, type Project, type ToolResult } from '../api'; import { t } from '../i18n'; @@ -72,7 +73,7 @@ export function OwnerAction(p: OwnerActionProps) { const r = o.result!; const declined = r.exitCode === DECLINED_EXIT; setSt({ s: 'done', dry, ok: r.ok, declined, lines: lines.slice(-200), detail: tail(r.output) }); - d.toast({ kind: r.ok ? 'ok' : declined ? 'info' : 'bad', title: r.ok ? p.done : declined ? t('write.declined') : t('write.failed'), detail: tail(r.output) || undefined }); + d.toast({ kind: r.ok ? 'ok' : declined ? 'info' : 'bad', title: r.ok ? p.done : declined ? t('write.declined') : t('write.failed'), detail: (r.ok || declined ? tail(r.output) : failureText(r)) || undefined }); if (r.ok) p.after?.(); } } catch (e) { diff --git a/apps/desktop/src/ui/StoreError.tsx b/apps/desktop/src/ui/StoreError.tsx new file mode 100644 index 0000000..6d21915 --- /dev/null +++ b/apps/desktop/src/ui/StoreError.tsx @@ -0,0 +1,102 @@ +// A store that could not be read, in one plain line: Google's typed errors (an API turned off in the Cloud project, no +// access to the app, a revoked key, a used-up quota) with the button that fixes them, and the raw API text only in a +// collapsed "Details" and the log (never a JSON dump in the window). +import { useEffect } from 'react'; +import { api, errorText } from '../api'; +import { type GoogleFinding, parseGoogleError, plainError } from '../../../../cli/lib/google-errors'; +import { t, type Key } from '../i18n'; +import { useData } from '../store'; +import { Icon } from './icons'; +import { Notice } from './kit'; + +const WHAT: Record = { + 'playdeveloperreporting.googleapis.com': 'gerr.what.reporting', + 'androidpublisher.googleapis.com': 'gerr.what.publisher', + 'storage.googleapis.com': 'gerr.what.storage', + 'storage-api.googleapis.com': 'gerr.what.storage', +}; + +/** The typed finding of a store read error (from the snapshot, else parsed from its text). */ +export function findingOf(e: { error: string; finding?: GoogleFinding; detail?: string }, app?: string | null): GoogleFinding | null { + return e.finding ?? parseGoogleError(e.detail ?? e.error, { app }); +} + +/** The one line for a finding, in the window's language. */ +export function findingLine(f: GoogleFinding): string { + switch (f.kind) { + case 'api-disabled': return t('gerr.apiDisabled', { what: t(WHAT[f.service] ?? 'gerr.what.other'), service: f.serviceTitle, project: f.projectId ?? t('gerr.projectUnknown') }); + case 'no-app-access': return t('gerr.noAccess', { app: f.app ?? t('gerr.thisApp') }); + case 'auth-revoked': return t('gerr.revoked'); + case 'quota': return t('gerr.quota'); + } +} + +export function TurnOnButton({ url, primary = true }: { url: string; primary?: boolean }) { + const d = useData(); + return ( + + ); +} + +/** One store's read error. `unreadable`: the sentence for an unknown error ({store} / {error}). */ +export function StoreReadNotice({ store, e, app, onRetry, busy, unreadable }: { + store: string; e: { error: string; finding?: GoogleFinding; detail?: string }; app?: string | null; onRetry?: () => void; busy?: boolean; unreadable: Key; +}) { + const d = useData(); + const f = findingOf(e, app); + const raw = e.detail ?? e.error; + useEffect(() => { api.logWebview('warn', `${store} could not be read${f ? ` (${f.kind})` : ''}`, raw).catch(() => {}); }, [store, raw]); // eslint-disable-line react-hooks/exhaustive-deps + const line = f ? findingLine(f) : t(unreadable, { store, error: plainError(raw) }); + const retry = onRetry && ; + const open = (url: string) => api.openExternal(url).catch(err => d.toast({ kind: 'bad', title: t('gerr.openFailed'), detail: errorText(err) })); + return ( + + {f?.kind === 'api-disabled' && } + {f?.kind === 'no-app-access' && } + {retry} + }> +
+ {line} + {raw !== line &&
{t('gerr.details')}
{raw}
} +
+
+ ); +} + +export interface BlockedProject { projectId: string | null; service: string; serviceTitle: string; activationUrl: string; apps: string[] } + +/** api-disabled findings across apps, one entry per Cloud project and API (several apps share one service account). Pure. */ +export function blockedProjects(items: { app: string; errors: ({ error: string; finding?: GoogleFinding; detail?: string } | string | undefined | null)[] }[]): BlockedProject[] { + const out = new Map(); + for (const it of items) for (const e of it.errors) { + if (!e) continue; + const f = typeof e === 'string' ? parseGoogleError(e) : findingOf(e); + if (f?.kind !== 'api-disabled') continue; + const k = `${f.projectId ?? '?'}|${f.service}`; + const b = out.get(k) ?? { projectId: f.projectId, service: f.service, serviceTitle: f.serviceTitle, activationUrl: f.activationUrl, apps: [] }; + if (!b.apps.includes(it.app)) b.apps.push(it.app); + out.set(k, b); + } + return [...out.values()]; +} + +/** The portfolio's one notice for Cloud projects that block reads of several apps. */ +export function BlockedProjectsNotice({ blocked, onRetry, busy }: { blocked: BlockedProject[]; onRetry: () => void; busy: boolean }) { + if (!blocked.length) return null; + const apps = [...new Set(blocked.flatMap(b => b.apps))]; + return ( + {t('gerr.checkAgain')}}> +
+ {t('gerr.portfolio', { count: blocked.length, apps: apps.join(', ') })} + {blocked.map(b => ( +
+ {findingLine({ kind: 'api-disabled', ...b })} + +
+ ))} +
+
+ ); +} diff --git a/cli/analytics.ts b/cli/analytics.ts index 58b139d..be3adb4 100644 --- a/cli/analytics.ts +++ b/cli/analytics.ts @@ -8,6 +8,7 @@ // Download reports > Statistics > Copy Cloud Storage URI) are read with the service account (store listing visitors, // acquisitions, daily user installs). compare lines the snapshots up with the git history of the store files (listing // text, screenshots, config): the days before vs after each change. Read-only on both stores except `setup`. +import { storeReadError } from './lib/google-errors'; import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { createOnce } from './lib/upsert'; @@ -120,11 +121,11 @@ export async function run(ctx: Ctx): Promise { const snap: Snapshot = { date: day(now), window: { start, end, days } }; if ((!store || store === 'apple') && config.apple) { try { const r = await appleSnapshot(ctx, start, end); snap.apple = { daily: r.daily, totals: appleTotals(r.daily) }; } - catch (e) { snap.apple = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `apple: ${snap.apple.error}`); } + catch (e) { snap.apple = { error: storeReadError((e as Error).message).error.slice(0, 400) }; warn(TAG, `apple: ${snap.apple.error}`); } } if ((!store || store === 'play') && config.play) { try { const r = await playSnapshot(ctx, start, end); snap.play = { daily: r.daily, totals: playTotals(r.daily) }; } - catch (e) { snap.play = { error: (e as Error).message.slice(0, 400) }; warn(TAG, `play: ${snap.play.error}`); } + catch (e) { snap.play = { error: storeReadError((e as Error).message, { app: config.play.packageName }).error.slice(0, 400) }; warn(TAG, `play: ${snap.play.error}`); } } const rows: (string | number)[][] = []; if (snap.apple && !('error' in snap.apple)) { const t = snap.apple.totals; rows.push(['apple', `${t.impressions} impressions`, `${t.pageViews} page views`, `${t.downloads} downloads`, pct(t.conversion ?? null)]); } diff --git a/cli/health.ts b/cli/health.ts index fe6322c..3547d20 100644 --- a/cli/health.ts +++ b/cli/health.ts @@ -17,6 +17,7 @@ import { issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString, } from './lib/health'; import { done, log, printJson, warn } from './lib/log'; +import { plainError, storeReadError } from './lib/google-errors'; import { formatFindings } from './lib/validate-rules'; import { googleClient, REPORTING_API } from './play/google'; @@ -35,7 +36,7 @@ export async function collectPlayHealth(root: string, pkg: string, days: number) // the top issues are extra: a failure there must not hide the crash and ANR rates already read let issues: PlayHealth['issues'] = [], issuesError: string | undefined; try { issues = parseIssues(await g.json('GET', `${app}/errorIssues:search?${issuesQuery(end, days)}`)); } catch (e) { - issuesError = (e as Error).message; + issuesError = plainError((e as Error).message, { app: pkg }); warn('health', `play: top issues not read: ${issuesError.slice(0, 200)}`); } const start = ymd(new Date(Date.UTC(end.year, end.month - 1, end.day)), days); @@ -69,10 +70,10 @@ export async function collectHealth(ctx: Ctx, o: { apple: boolean; play: boolean const { config, root } = ctx.loaded; const h: HealthSnapshot = { date: new Date().toISOString().slice(0, 10) }; if (o.play && config.play) { - try { h.play = await collectPlayHealth(root, config.play.packageName, o.days); } catch (e) { h.play = { error: (e as Error).message }; } + try { h.play = await collectPlayHealth(root, config.play.packageName, o.days); } catch (e) { h.play = storeReadError((e as Error).message, { app: config.play.packageName }); } } if (o.apple && config.apple) { - try { h.apple = await collectAppleHealth(root, config.apple.bundleId, config.apple.appId, o.days); } catch (e) { h.apple = { error: (e as Error).message }; } + try { h.apple = await collectAppleHealth(root, config.apple.bundleId, config.apple.appId, o.days); } catch (e) { h.apple = storeReadError((e as Error).message); } } return h; } @@ -93,6 +94,7 @@ export async function run(ctx: Ctx): Promise { const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days }); if (a.has('json')) { printJson(h); return; } console.log(healthTable(h)); + for (const [s, x] of [['Google Play', h.play], ['App Store', h.apple]] as const) if (x && 'error' in x) console.log(`\n${s}: ${x.error}`); console.log('\n' + formatFindings(healthFindings(h))); if (weekly) { const dir = ctx.loaded.resolve(a.get('out') ?? '.storebound/health'); diff --git a/cli/lib/analytics.ts b/cli/lib/analytics.ts index 0c5b0b0..d51f895 100644 --- a/cli/lib/analytics.ts +++ b/cli/lib/analytics.ts @@ -15,6 +15,7 @@ // stats/store_performance/store_performance___country.csv (Store listing acquisitions / visitors) // stats/installs/installs___country.csv (Daily User Installs, ...) // https://support.google.com/googleplay/android-developer/answer/6135870 +import { plainError } from './google-errors'; import { createHash } from 'node:crypto'; import { parseCsvRecords } from './csv'; import { mdTable, pct, textTable } from './table'; @@ -144,7 +145,7 @@ export function storeErrors(snaps: Snapshot[]): { apple?: string; play?: string for (const k of ['apple', 'play'] as const) { if (series[k].length) continue; const last = [...snaps].sort((x, y) => x.date.localeCompare(y.date)).reverse().find(s => s[k] && 'error' in s[k]!); - if (last) out[k] = (last[k] as { error: string }).error; + if (last) out[k] = plainError((last[k] as { error: string }).error, { withUrl: true }); } return out; } diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 9818a1f..9c3f70d 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -69,6 +69,48 @@ export interface ToolResult { output: string; /** Structured result of a --json capable command. */ data?: unknown; + /** What the exit code means: 0 = ok; a documented findings code with the --json result printed (scan / check / + * validate / health exit 1 when they find problems) = findings; 3 = declined; anything else = failed. Missing in + * results cached by older versions (outcomeOf below decides then). */ + outcome?: Outcome; + /** failed only: the command's own error line (stderr's last "error: ..." line, else its last meaningful line). */ + error?: string; +} + +export type Outcome = 'ok' | 'findings' | 'declined' | 'failed'; +/** Read tools whose exit code 1 means "found problems" (the result is still printed with --json): by design, so CI fails. */ +export const FINDINGS_EXIT: Readonly> = { + scan: [1], check: [1], validate: [1], health: [1], check_aso: [1], shots_check: [1], catalog_diff: [1], aso_audit: [1], +}; +/** lib/ctx DECLINED_EXIT: the owner's answer was missing or "no". */ +export const DECLINED_CODE = 3; + +/** The outcome of a run (`tool`: the MCP tool name or the desktop method, dots or underscores). */ +export function outcomeOf(tool: string, code: number, hasData: boolean): Outcome { + if (code === 0) return 'ok'; + if (code === DECLINED_CODE) return 'declined'; + if (hasData && (FINDINGS_EXIT[tool.replace(/\./g, '_')] ?? []).includes(code)) return 'findings'; + return 'failed'; +} + +/** Is this line noise rather than a message (blank, a stack frame, a lone brace, a usage line)? */ +const noise = (l: string): boolean => !l.trim() || /^\s+at\s/.test(l) || /^[\s{}[\](),;]*$/.test(l) || /^\s*(usage|options|examples?):/i.test(l) || /^\s{2,}--?\w/.test(l); +/** A log line without its "12:00:00 [tag] " prefix. */ +const bare = (l: string): string => l.trim().replace(/^\d\d:\d\d:\d\d \[[^\]]+\] /, '').replace(/^\S+ \[[^\]]+\] /, ''); + +/** + * The command's own error line: the last "error: ..." line of stderr (the CLI's top-level catch), else the first + * meaningful stderr line (unknown command / option: the message comes before the usage), else the last meaningful + * output line. '' when the command said nothing. Pure. + */ +export function errorLine(stderr: string, output = ''): string { + const err = stderr.split('\n'); + const tagged = err.filter(l => /^\s*error:\s*\S/i.test(bare(l))).at(-1); + if (tagged) return bare(tagged).replace(/^error:\s*/i, '').slice(0, 500); + const first = err.find(l => !noise(l)); + if (first) return bare(first).slice(0, 500); + const last = output.split('\n').filter(l => !noise(l)).at(-1); + return last ? bare(last).slice(0, 500) : ''; } export interface ProgressParams { requestId: string | number; line?: string; stream?: 'stdout' | 'stderr'; n?: number; total?: number; project?: string } diff --git a/cli/lib/google-errors.ts b/cli/lib/google-errors.ts new file mode 100644 index 0000000..91c0349 --- /dev/null +++ b/cli/lib/google-errors.ts @@ -0,0 +1,98 @@ +// Google API errors -> typed findings. Google answers a disabled API, a missing app permission, a revoked key or a +// used-up quota with a JSON body ({"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"reason": +// "SERVICE_DISABLED",...}]}}); storebound's clients put that body (on one line, maybe cut at 800 characters) into the +// Error message. This reads the message text (raw or cut), so every layer (CLI tables, health / analytics snapshots, +// the desktop window, even old cached snapshots) can say one plain line instead of showing the JSON. Pure. + +export type GoogleFinding = + /** An API is not enabled in the service account's Google Cloud project (403 SERVICE_DISABLED). */ + | { kind: 'api-disabled'; service: string; serviceTitle: string; projectId: string | null; activationUrl: string } + /** The service account has no access to this app in Play Console (403 PERMISSION_DENIED, not SERVICE_DISABLED). */ + | { kind: 'no-app-access'; app: string | null; usersUrl: string } + /** Google refused the key itself (401 UNAUTHENTICATED, invalid_grant, Invalid JWT): revoked, deleted or expired. */ + | { kind: 'auth-revoked' } + /** 429 / RESOURCE_EXHAUSTED / rateLimitExceeded: a quota is used up for now. */ + | { kind: 'quota'; serviceTitle: string | null }; + +export const PLAY_USERS_URL = 'https://play.google.com/console/developers/users-and-permissions'; + +const TITLES: Record = { + 'playdeveloperreporting.googleapis.com': 'Google Play Developer Reporting API', + 'androidpublisher.googleapis.com': 'Google Play Android Developer API', + 'storage.googleapis.com': 'Cloud Storage API', + 'storage-api.googleapis.com': 'Cloud Storage API', +}; +/** What the owner loses while that API is off (the start of the one line). */ +const NEEDS: Record = { + 'playdeveloperreporting.googleapis.com': 'Crash and ANR data', + 'androidpublisher.googleapis.com': 'Reading and updating the app on Google Play', + 'storage.googleapis.com': 'Play statistics (store listing visitors, installs)', + 'storage-api.googleapis.com': 'Play statistics (store listing visitors, installs)', +}; + +/** A JSON string's content without its escapes (\\n as a space: one line). */ +const unescape = (s: string): string => { try { return (JSON.parse(`"${s}"`) as string).replace(/\s+/g, ' ').trim(); } catch { return s.replace(/\\(.)/g, '$1'); } }; + +/** The API's own page in the Cloud console (the host the desktop may open), with the project chosen. */ +export function enableUrl(service: string, projectId: string | null): string { + return `https://console.cloud.google.com/apis/library/${service}${projectId ? `?project=${projectId}` : ''}`; +} + +/** The typed finding in a Google error text, or null when it is another error. `app`: the package, when the caller knows it. */ +export function parseGoogleError(text: string, o: { app?: string | null } = {}): GoogleFinding | null { + const s = String(text ?? ''); + const status = Number(/-> (\d{3})\b/.exec(s)?.[1] ?? /"code":\s*(\d{3})/.exec(s)?.[1] ?? NaN); + const app = o.app ?? /\/(?:applications|apps)\/([A-Za-z][\w.]*\.[\w.]+)/.exec(s)?.[1] ?? null; + if (/SERVICE_DISABLED|has not been used in project|accessNotConfigured|API has not been used|it is disabled\. Enable it| turned on in Google Cloud project/i.test(s)) { + const service = /"service":\s*"([a-z0-9.-]+\.googleapis\.com)"/.exec(s)?.[1] ?? /apis\/api\/([a-z0-9.-]+\.googleapis\.com)/.exec(s)?.[1] + ?? /apis\/library\/([a-z0-9.-]+\.googleapis\.com)/.exec(s)?.[1] ?? /([a-z0-9-]+\.googleapis\.com)/.exec(s)?.[1] ?? 'playdeveloperreporting.googleapis.com'; + const projectId = /"consumer":\s*"projects\/([a-z0-9-]+)"/i.exec(s)?.[1] ?? /in (?:Google Cloud )?project ([a-z0-9-]+)/i.exec(s)?.[1] ?? /[?&]project=([a-z0-9-]+)/i.exec(s)?.[1] ?? null; + const serviceTitle = (/"serviceTitle":\s*"((?:[^"\\]|\\.)*)"/.exec(s)?.[1] && unescape(/"serviceTitle":\s*"((?:[^"\\]|\\.)*)"/.exec(s)![1]!)) + ?? /"message":\s*"([^"]*?) has not been used in project/.exec(s)?.[1] ?? / needs the (.+?) turned on in Google Cloud/.exec(s)?.[1] ?? TITLES[service] ?? service; + return { kind: 'api-disabled', service, serviceTitle, projectId, activationUrl: enableUrl(service, projectId) }; + } + if (status === 429 || /RESOURCE_EXHAUSTED|rateLimitExceeded|quota(?: exceeded| metric)|Quota exceeded/i.test(s)) { + const service = /"service":\s*"([a-z0-9.-]+\.googleapis\.com)"/.exec(s)?.[1]; + return { kind: 'quota', serviceTitle: service ? TITLES[service] ?? service : null }; + } + if (status === 401 || /UNAUTHENTICATED|invalid_grant|Invalid JWT|account not found|invalid_client/i.test(s)) return { kind: 'auth-revoked' }; + if (status === 403 && /PERMISSION_DENIED|caller does not have permission|does not have permission|not have access/i.test(s)) return { kind: 'no-app-access', app, usersUrl: PLAY_USERS_URL }; + return null; +} + +/** The one plain line for a finding (no JSON). `withUrl`: the CLI adds where to fix it; the window has a button. */ +export function findingText(f: GoogleFinding, o: { withUrl?: boolean } = {}): string { + switch (f.kind) { + case 'api-disabled': { + const what = NEEDS[f.service] ?? 'This read'; + const line = `${what} needs the ${f.serviceTitle} turned on in Google Cloud project ${f.projectId ?? '(the service account\'s project)'}.`; + return o.withUrl ? `${line} Turn it on: ${f.activationUrl}` : line; + } + case 'no-app-access': { + const line = `The service account has no access to ${f.app ?? 'this app'} in Play Console: add it under Users and permissions (invite the service account, give it access to ${f.app ?? 'the app'}).`; + return o.withUrl ? `${line} ${f.usersUrl}` : line; + } + case 'auth-revoked': + return 'Google refused the service account key: it was revoked, deleted or has expired. Add a new JSON key (Google Cloud > IAM & Admin > Service accounts > Keys) and set it again.'; + case 'quota': + return `The ${f.serviceTitle ?? 'Google API'} quota is used up for now: try again later (quotas reset per minute and per day).`; + } +} + +/** An error text for people: the finding's line when there is one, else the text without a JSON body. */ +export function plainError(text: string, o: { app?: string | null; withUrl?: boolean } = {}): string { + const f = parseGoogleError(text, o); + if (f) return findingText(f, o); + const s = String(text ?? ''); + const msg = /"(?:message|detail|error_description)":\s*"((?:[^"\\]|\\.)*)"/.exec(s)?.[1]; + const head = s.split(/\s[{[]"/)[0]!.trim(); + return msg ? `${head} ${unescape(msg)}`.trim().slice(0, 300) : s.split('\n')[0]!.slice(0, 300); +} + +/** A store read that failed, for snapshots (health, analytics) and JSON results: the plain line (with the fix URL), + * the typed finding when Google said what is wrong, and the raw text as `detail` (logs, a collapsed "Details"). */ +export function storeReadError(raw: string, o: { app?: string | null } = {}): { error: string; finding?: GoogleFinding; detail?: string } { + const f = parseGoogleError(raw, o); + const error = f ? findingText(f, { withUrl: true }) : plainError(raw); + return { error, ...(f ? { finding: f } : {}), ...(error !== raw ? { detail: raw } : {}) }; +} diff --git a/cli/lib/health.ts b/cli/lib/health.ts index 6b563ff..c14fe6c 100644 --- a/cli/lib/health.ts +++ b/cli/lib/health.ts @@ -18,6 +18,7 @@ // (HANGS, DISK_WRITES, LAUNCHES), GET /v1/apps/{id}/betaFeedbackCrashSubmissions (TestFlight crash reports, API 4.0+). import type { Finding, Level } from './validate-rules'; import { mdTable, pct, textTable } from './table'; +import { findingText, type GoogleFinding, parseGoogleError, plainError } from './google-errors'; import { reportingEnableUrl } from './store-apps'; export const PLAY_THRESHOLDS = { crash: 0.0109, anr: 0.0047, perDevice: 0.08 } as const; @@ -115,7 +116,10 @@ export interface AppleHealth { betaCrashes: { build: string; count: number }[]; } -export interface HealthSnapshot { date: string; play?: PlayHealth | { error: string }; apple?: AppleHealth | { error: string } } +/** A store that could not be read: `error` is one plain line (never a JSON body), `finding` the typed Google error + * (google-errors.ts), `detail` the raw API text for logs and a collapsed "Details". */ +export interface StoreReadError { error: string; finding?: GoogleFinding; detail?: string } +export interface HealthSnapshot { date: string; play?: PlayHealth | StoreReadError; apple?: AppleHealth | StoreReadError } /** Last value of a metric over the rows (the 28-day rolling metrics: the latest row is the store's current view). */ export function lastValue(rows: MetricRow[], metric: string): number | null { @@ -186,11 +190,13 @@ export function healthFindings(h: HealthSnapshot, o: { unreadable?: Level; princ const f: Finding[] = []; const play = h.play; if (play && 'error' in play) { - const on = reportingEnableUrl(play.error, o.principal ?? null); - f.push(REPORTING_OFF.test(play.error) - ? { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: the Google Play Developer Reporting API is off in the service account's Google Cloud project${on.project ? ` ${on.project}` : ''}`, - fix: `enable "Google Play Developer Reporting API" for that project: ${on.url} (Enable), wait a few minutes (store-health skill)` } - : { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${play.error.slice(0, 200)}`, fix: 'store-health skill (Reporting API access)' }); + const raw = play.detail ?? play.error; + const g = play.finding ?? parseGoogleError(raw); + const on = reportingEnableUrl(raw, o.principal ?? null); + f.push(g?.kind === 'api-disabled' || REPORTING_OFF.test(raw) + ? { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: the ${g?.kind === 'api-disabled' ? g.serviceTitle : 'Google Play Developer Reporting API'} is off in the service account's Google Cloud project${(g?.kind === 'api-disabled' ? g.projectId : on.project) ? ` ${g?.kind === 'api-disabled' ? g.projectId : on.project}` : ''}`, + fix: `enable "${g?.kind === 'api-disabled' ? g.serviceTitle : 'Google Play Developer Reporting API'}" for that project: ${g?.kind === 'api-disabled' ? g.activationUrl : on.url} (Enable), wait a few minutes (store-health skill)` } + : { store: 'play', level: o.unreadable ?? 'warn', code: 'vitals', msg: `vitals not readable: ${g ? findingText(g) : plainError(raw).slice(0, 200)}`, fix: g?.kind === 'no-app-access' ? `Play Console > Users and permissions: ${g.usersUrl}` : 'store-health skill (Reporting API access)' }); } else if (play) { const crash = lastValue(play.crash, 'userPerceivedCrashRate28dUserWeighted') ?? weightedAverage(play.crash, 'userPerceivedCrashRate'); @@ -209,7 +215,7 @@ export function healthFindings(h: HealthSnapshot, o: { unreadable?: Level; princ } } const apple = h.apple; - if (apple && 'error' in apple) f.push({ store: 'apple', level: o.unreadable ?? 'warn', code: 'diagnostics', msg: `diagnostics not readable: ${apple.error.slice(0, 200)}` }); + if (apple && 'error' in apple) f.push({ store: 'apple', level: o.unreadable ?? 'warn', code: 'diagnostics', msg: `diagnostics not readable: ${plainError(apple.error).slice(0, 200)}` }); else if (apple) { const poor = apple.metrics.filter(m => m.goal === 'poor'); for (const m of poor) f.push({ store: 'apple', level: 'warn', code: 'perf', msg: `${m.metric} ${m.value} ${m.unit} on ${m.version}: Apple rates it poor`, fix: 'Xcode Organizer > Metrics; store-health skill' }); @@ -230,12 +236,12 @@ export function healthTable(h: HealthSnapshot): string { rows.push(['play', 'ANR rate (user-perceived, 28 d)', pct(lastValue(p.anr, 'userPerceivedAnrRate28dUserWeighted')), pct(PLAY_THRESHOLDS.anr)]); rows.push(['play', `ANR rate (user-perceived, ${p.window.days} d avg)`, pct(weightedAverage(p.anr, 'userPerceivedAnrRate')), '']); rows.push(['play', 'top issues', p.issuesError ? 'not read' : p.issues.length, '']); - } else if (h.play) rows.push(['play', 'error', h.play.error.slice(0, 80), '']); + } else if (h.play) rows.push(['play', 'not readable', h.play.finding ? h.play.finding.kind : h.play.error.slice(0, 80), '']); if (h.apple && !('error' in h.apple)) { for (const m of h.apple.metrics.slice(0, 12)) rows.push(['apple', `${m.metric} (${m.version})`, `${m.value} ${m.unit}`.trim(), m.goal ?? '']); rows.push(['apple', 'diagnostic signatures', h.apple.signatures.length, '']); rows.push(['apple', 'TestFlight crash reports', h.apple.betaCrashes.reduce((n, b) => n + b.count, 0), '']); - } else if (h.apple) rows.push(['apple', 'error', h.apple.error.slice(0, 80), '']); + } else if (h.apple) rows.push(['apple', 'not readable', h.apple.finding ? h.apple.finding.kind : h.apple.error.slice(0, 80), '']); return textTable(['store', 'metric', 'value', 'threshold / goal'], rows); } diff --git a/cli/lib/runner.ts b/cli/lib/runner.ts index ac0fdd6..51246f7 100644 --- a/cli/lib/runner.ts +++ b/cli/lib/runner.ts @@ -28,7 +28,8 @@ export interface RunOptions { machine?: boolean; } -export interface RunResult { code: number; out: string; data?: unknown; cancelled: boolean } +/** `err`: the stderr lines only (for the command's own error line). */ +export interface RunResult { code: number; out: string; err?: string; data?: unknown; cancelled: boolean } export interface Running { result: Promise; cancel(): void } @@ -70,6 +71,7 @@ export function runCommand(argv: string[], o: RunOptions): Running { const p = rt.spawn([...selfCommand(), ...argv], { cwd: o.cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: childEnv(o.env, o.machine) }); let cancelled = false; const lines: string[] = []; + const errs: string[] = []; let data: unknown; const each = (line: string, kind: 'stdout' | 'stderr'): void => { if (kind === 'stdout' && line.startsWith(RESULT_MARK)) { @@ -77,12 +79,13 @@ export function runCommand(argv: string[], o: RunOptions): Running { return; } lines.push(line); + if (kind === 'stderr') errs.push(line); o.onLine?.(line, kind); }; const result = (async (): Promise => { await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]); const code = await p.exited; - return { code, out: lines.join('\n').trim(), ...(data === undefined ? {} : { data }), cancelled }; + return { code, out: lines.join('\n').trim(), err: errs.join('\n').trim(), ...(data === undefined ? {} : { data }), cancelled }; })(); return { result, cancel: () => { cancelled = true; p.kill(); } }; } diff --git a/cli/serve.ts b/cli/serve.ts index 7863f91..fdf8acb 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -20,7 +20,7 @@ import pkg from '../package.json' with { type: 'json' }; import { canonical, parseSecret, TokenGuard } from './lib/confirm-token'; import { CONFIG_NAMES } from './lib/config'; import { - DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject, + DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject, errorLine, outcomeOf, } from './lib/desktop-protocol'; import { emptyStatus, fillAppStatus, lastLine } from './lib/app-status'; import { RENDER_FILE_RE } from './lib/project-files'; @@ -441,9 +441,11 @@ export class Session { 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'); + const outcome = outcomeOf(t.write ? '' : t.name, res.code, res.data !== undefined); + const error = outcome === 'failed' ? errorLine(res.err ?? '', res.out) : ''; return { method, ok: res.code === 0, exitCode: res.code, dryRun: t.write ? dryRun : false, command: `storebound ${argv.join(' ')}`, output: cut(res.out), - ...(res.data === undefined ? {} : { data: res.data }), + ...(res.data === undefined ? {} : { data: res.data }), outcome, ...(error ? { error } : {}), }; } @@ -461,7 +463,7 @@ export class Session { const argv = [...cmd, '--store', play ? 'play' : 'apple', ...(args.icons === true ? ['--icons'] : []), '--json']; const r = await this.track(id, this.run(argv, { cwd: neutralDir(), env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) })).result; if (r.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); - if (r.data === undefined) throw new RpcError(ERR.internal, lastLine(r.out) || `exit ${r.code}`); + if (r.data === undefined) throw new RpcError(ERR.internal, errorLine(r.err ?? '', r.out) || `storebound ${argv[0]} ${argv[1] ?? ''} stopped without an error message (exit ${r.code})`); return r.data; } diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index fb256af..aceceb3 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -660,3 +660,14 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `playPublicPage` (`cli/lib/play-public.ts`), `playReleases` / `versionKey` / `sameVersion` (`cli/lib/portfolio.ts`), `versionHistory` (`cli/lib/train.ts`), `tests/play-public-version-match.test.ts`, the desktop boot check's `release-state` cases (page 404 and 200). + +## 57. A raw Google JSON error in the window, and "Exit code 1" for a scan that found problems +- **Do:** never show an API error body to the owner. Parse Google errors into a typed finding (`parseGoogleError`): + SERVICE_DISABLED = the API is off in the service account's Cloud project (say which API and project, link the + console page to turn it on), PERMISSION_DENIED = the service account has no access to that app (Play Console > Users + and permissions), 401 / invalid_grant = the key is revoked or expired, 429 / RESOURCE_EXHAUSTED = quota. One project + that blocks several apps is one notice, not one error per app. Keep the raw text in a collapsed Details and the log. + Exit 1 of `scan` / `check` / `validate` / `health` with the JSON result printed means "found problems": show the + findings; a real failure shows the command's own error line, never a bare exit code. +- **Guard:** `cli/lib/google-errors.ts`, `outcomeOf` / `errorLine` (`cli/lib/desktop-protocol.ts`), + `tests/google-errors.test.ts`, the desktop boot check's `errors` cases (api-disabled, scan-findings, scan-failed). diff --git a/tests/google-errors.test.ts b/tests/google-errors.test.ts new file mode 100644 index 0000000..50c092c --- /dev/null +++ b/tests/google-errors.test.ts @@ -0,0 +1,76 @@ +// Google API errors as typed findings (pitfall 57): the live 403 SERVICE_DISABLED body of the Play Developer Reporting +// API, a missing app permission, a revoked key and a quota; the one plain line the CLI prints; and the desktop +// runner's outcome of exit codes (scan / check / validate exit 1 with findings is a result, not an error). +import { describe, expect, test } from 'bun:test'; +import { EXAMPLE_CLOUD_PROJECT, healthApiDisabled, SCAN_FAILED, SCAN_FAILED_LINE, serviceDisabledMessage } from '../apps/desktop/src/dev/error-fixtures'; +import { errorLine, outcomeOf } from '../cli/lib/desktop-protocol'; +import { findingText, parseGoogleError, plainError, storeReadError } from '../cli/lib/google-errors'; +import { healthFindings, healthTable } from '../cli/lib/health'; + +const URL = `https://console.cloud.google.com/apis/library/playdeveloperreporting.googleapis.com?project=${EXAMPLE_CLOUD_PROJECT}`; +const LINE = `Crash and ANR data needs the Google Play Developer Reporting API turned on in Google Cloud project ${EXAMPLE_CLOUD_PROJECT}.`; + +describe('403 SERVICE_DISABLED (live shape)', () => { + const msg = serviceDisabledMessage('com.example.demo'); + test('parses to api-disabled with the service, project and a console URL the desktop may open', () => { + expect(parseGoogleError(msg)).toEqual({ kind: 'api-disabled', service: 'playdeveloperreporting.googleapis.com', serviceTitle: 'Google Play Developer Reporting API', projectId: EXAMPLE_CLOUD_PROJECT, activationUrl: URL }); + }); + test('the CLI line: one line with the URL, no JSON', () => { + const e = storeReadError(msg, { app: 'com.example.demo' }); + expect(e.error).toBe(`${LINE} Turn it on: ${URL}`); + expect(e.error).not.toContain('{'); + expect(e.detail).toBe(msg); + expect(findingText(e.finding!)).toBe(LINE); + }); + test('the plain line parses back (cached snapshots and portfolio store errors carry only the line)', () => { + expect(parseGoogleError(storeReadError(msg).error)).toEqual(parseGoogleError(msg)); + }); + test('a body cut at 800 characters (errorBody) still parses', () => { + expect(parseGoogleError(msg.slice(0, 400))?.kind).toBe('api-disabled'); + }); + test('health: the table and findings say it in words', () => { + const h = healthApiDisabled('com.example.demo'); + expect(healthTable(h)).not.toContain('{"error"'); + const f = healthFindings(h); + expect(f[0]!.msg).toContain(`Reporting API is off in the service account's Google Cloud project ${EXAMPLE_CLOUD_PROJECT}`); + expect(f[0]!.fix).toContain(URL); + }); +}); + +describe('other Google errors', () => { + test('403 PERMISSION_DENIED without SERVICE_DISABLED: no access to that app, with the Users and permissions step', () => { + const m = 'GET /androidpublisher/v3/applications/com.example.somegame/edits -> 403 {"error":{"code":403,"message":"The caller does not have permission","status":"PERMISSION_DENIED"}}'; + const f = parseGoogleError(m); + expect(f).toMatchObject({ kind: 'no-app-access', app: 'com.example.somegame' }); + expect(findingText(f!)).toContain('no access to com.example.somegame in Play Console'); + expect(findingText(f!)).toContain('Users and permissions'); + }); + test('invalid_grant and 401: the key is revoked or expired', () => { + expect(parseGoogleError('Google token: invalid_grant: Invalid JWT Signature.')?.kind).toBe('auth-revoked'); + expect(parseGoogleError('GET /v1beta1/apps:search -> 401 {"error":{"code":401,"status":"UNAUTHENTICATED"}}')?.kind).toBe('auth-revoked'); + }); + test('429 / RESOURCE_EXHAUSTED: quota', () => { + const f = parseGoogleError('POST /v1beta1/apps/com.example.a/anrRateMetricSet:query -> 429 {"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"metadata":{"service":"playdeveloperreporting.googleapis.com"}}]}}'); + expect(f).toEqual({ kind: 'quota', serviceTitle: 'Google Play Developer Reporting API' }); + }); + test('an unknown error keeps its message, never the JSON', () => { + const p = plainError('GET /x -> 500 {"error":{"code":500,"message":"Internal error encountered.","status":"INTERNAL"}}'); + expect(p).toBe('GET /x -> 500 Internal error encountered.'); + }); +}); + +describe('desktop runner: exit codes', () => { + test('scan / check / validate / health exit 1 with the result printed are findings; without it, failed', () => { + for (const m of ['scan', 'check', 'validate', 'health']) expect(outcomeOf(m, 1, true)).toBe('findings'); + expect(outcomeOf('scan', 1, false)).toBe('failed'); + expect(outcomeOf('play_status', 1, true)).toBe('failed'); + expect(outcomeOf('owner.apple.submit', 3, false)).toBe('declined'); + expect(outcomeOf('scan', 0, true)).toBe('ok'); + }); + test('the error line is the command\'s own: "error: ..." of stderr, else the first message before the usage', () => { + expect(SCAN_FAILED.error).toBe(SCAN_FAILED_LINE); + expect(errorLine('unknown option for storebound scan: --x\n\nusage: storebound scan [--json]\n --json print JSON')).toBe('unknown option for storebound scan: --x'); + expect(errorLine('', '12:00:00 [scan] reading\n12:00:01 [scan] the folder has no app')).toBe('the folder has no app'); + expect(errorLine('', '')).toBe(''); + }); +}); diff --git a/tests/play-post-reads.test.ts b/tests/play-post-reads.test.ts index 9159923..7d3a9fa 100644 --- a/tests/play-post-reads.test.ts +++ b/tests/play-post-reads.test.ts @@ -107,7 +107,9 @@ describe('Play vitals: errorIssues:search time zone', () => { reporting(() => new Response(UNSUPPORTED_TZ, { status: 400 })); const h = await collectPlayHealth(mkdtempSync(join(tmpdir(), 'sb-post-')), PKG, 7); expect(h.crash).toEqual([]); - expect(h.issuesError).toStartWith(`GET /v1beta1/apps/${PKG}/errorIssues:search -> 400 {"error":{"code":400,"message":"Unsupported timezone`); + // one plain line: the API's message without the JSON around it (pitfall 57) + expect(h.issuesError).toStartWith(`GET /v1beta1/apps/${PKG}/errorIssues:search -> 400 Unsupported timezone`); + expect(h.issuesError).not.toContain('{"error"'); const f = healthFindings({ date: '2026-10-11', play: h }); expect(f.map(x => x.code)).toEqual(['vitals', 'vitals-issues']); expect(f[1]).toMatchObject({ level: 'warn', msg: expect.stringContaining('Unsupported timezone') }); diff --git a/tools/desktop-boot-check.ts b/tools/desktop-boot-check.ts index 9210f58..c55fc94 100644 --- a/tools/desktop-boot-check.ts +++ b/tools/desktop-boot-check.ts @@ -23,6 +23,7 @@ import { extname, join, resolve } from 'node:path'; import type { Browser, Page } from 'playwright'; import { APPLE_STATUS_FIRST_REVIEW, APPLE_STATUS_READY, APPLE_STATUS_UNRESOLVED, ownerDry, PLAY_STATUS, PLAY_STATUS_FIRST_200, PLAY_STATUS_FIRST_404 } from '../apps/desktop/src/dev/submit-fixtures'; import { appleReleases, playReleases, releaseTrains } from '../cli/lib/portfolio'; +import { EXAMPLE_CLOUD_PROJECT, healthApiDisabled, SCAN_FAILED, SCAN_FAILED_LINE, SCAN_FINDINGS } from '../apps/desktop/src/dev/error-fixtures'; const ROOT = resolve(import.meta.dir, '..'); const APP = join(ROOT, 'apps/desktop'); @@ -581,6 +582,113 @@ async function runReleaseStateCase(browser: Browser, sidecar: Sidecar, page404: return { name, ok: problems.length === 0, problems: [...new Set(problems)], visited, notes }; } +/** + * Errors the window must say in words (pitfall 57). `api-disabled`: the last health read of the app is Google's live + * 403 SERVICE_DISABLED (Reporting API off in Cloud project 123456789000): the portfolio shows it once for the project, + * the Health tab one line with "Turn it on in Google Cloud" and "Check again", and no '{"error"' text anywhere visible. + * `scan-findings`: `scan --json` exits 1 with its findings (by design): the Checks tab lists them, no "Exit code". + * `scan-failed`: a real failure shows the command's own error line. + */ +async function runErrorCase(browser: Browser, sidecar: Sidecar, variant: 'api-disabled' | 'scan-findings' | 'scan-failed'): Promise { + const name = `errors (${variant})`; + const freeze = conf.app.security.freezePrototype === true; + const server = serve(DIST, cspHeader(conf.app.security.csp), false); + const ctx = await browser.newContext({ viewport: { width: 1360, height: 900 }, reducedMotion: 'reduce' }); + const page = await ctx.newPage(); + const problems: string[] = []; + const notes: string[] = []; + const unmocked = new Set(); + const logged: string[] = []; + const fx = liveFixture('d3-full'); + const base = host(fx, sidecar, unmocked, logged); + const opened: string[] = []; + const answer = async (cmd: string, a: Record): Promise => { + if (variant === 'api-disabled' && cmd === 'cache_get' && a.method === 'health') { + const pkg = 'com.example.' + String(a.projectId).replace(/[^a-z0-9]/gi, '').toLowerCase().slice(0, 20); + return { value: { method: 'health', ok: true, exitCode: 0, dryRun: false, command: 'storebound health --json', output: '', data: healthApiDisabled(pkg) }, at: new Date(Date.now() - 60_000).toISOString() }; + } + if (cmd === 'open_external') { opened.push(String(a.url)); return null; } + if (cmd === 'sidecar_call' && a.method === 'scan' && variant !== 'api-disabled') return variant === 'scan-findings' ? SCAN_FINDINGS : SCAN_FAILED; + if (cmd === 'sidecar_call' && a.method === 'health') return { method: 'health', ok: true, exitCode: 0, dryRun: false, command: 'storebound health --json', output: '', data: healthApiDisabled('com.example.app') }; + return base(cmd, a); + }; + await page.exposeFunction('__bootCheckHost', async (cmd: string, args: Record) => { + try { return { ok: (await answer(cmd, args)) ?? null }; } catch (e) { return { err: e }; } + }); + page.on('pageerror', e => problems.push(`uncaught: ${e.stack ?? e.message}`.split('\n').slice(0, 4).join(' | '))); + page.on('console', m => { if (m.type() === 'error') problems.push(`console.error: ${m.text().slice(0, 400)}`); }); + await page.addInitScript(initScript(freeze)); + let visited = 0; + const text = async (sel = '#content') => (await page.locator(sel).first().innerText().catch(() => '')).replace(/\s+/g, ' '); + const crashCheck = async (where: string) => { for (const c of (await state(page)).crash) problems.push(`${where}: error panel ${c}`); }; + const noRaw = (where: string, s: string) => { + if (s.includes('{"error"') || s.includes('"status":') || /SERVICE_DISABLED|PERMISSION_DENIED/.test(s)) problems.push(`${where}: raw API error text is visible`); + if (/Exit code \d/.test(s)) problems.push(`${where}: a bare "Exit code N" is visible`); + }; + const LINE = `Crash and ANR data needs the Google Play Developer Reporting API turned on in Google Cloud project ${EXAMPLE_CLOUD_PROJECT}.`; + try { + await page.goto(`http://127.0.0.1:${server.port}/`, { waitUntil: 'load' }); + await page.waitForFunction(() => document.documentElement.dataset.booted === '1', null, { timeout: WAIT_MS }).catch(() => problems.push('React never drew the window (no data-booted)')); + await settle(page); + const wizard = page.locator('.wizard[role="dialog"]'); + if (await wizard.count()) { await wizard.press('Escape').catch(() => {}); await gone(page, '.wizard[role="dialog"]'); } + if (variant === 'api-disabled') { + await shows(page, '#content', 'needs an API turned on'); + const pf = await text(); + const m = /(\d+) Google Cloud projects? needs? an API turned on: affects ([^.]{0,160}?)(?= Project | Crash |$)/.exec(pf); + notes.push(`portfolio: ${m ? m[0].slice(0, 200) : 'no project notice'}`); + if (!m) problems.push('Portfolio: no "1 Google Cloud project needs an API turned on" notice'); + else if (m[1] !== '1') problems.push(`Portfolio: ${m[1]} projects for one Cloud project (want 1)`); + const count = (pf.match(/needs the Google Play Developer Reporting API turned on/g) ?? []).length; + if (count !== 1) problems.push(`Portfolio: the project line shows ${count} times (want once, not per app)`); + noRaw('Portfolio', pf); + await crashCheck('Portfolio'); + visited++; + } + const item = page.locator('nav.side .nav-app').filter({ hasText: /Prism Puddle|demo-game/ }).first(); + await item.click({ timeout: WAIT_MS }).catch(e => problems.push(`could not open the app: ${String(e).split('\n')[0]}`)); + await settle(page); + if (variant === 'api-disabled') { + await page.locator('[role="tab"]#tab-health').click({ timeout: WAIT_MS }).catch(e => problems.push(`no Health tab: ${String(e).split('\n')[0]}`)); + await shows(page, '#content', 'Turn it on in Google Cloud'); + await settle(page); + const h = await text(); + if (!h.includes(LINE)) problems.push(`Health: no "${LINE}"`); + const turnOn = page.locator('#content button', { hasText: 'Turn it on in Google Cloud' }).first(); + if (!(await turnOn.count())) problems.push('Health: no "Turn it on in Google Cloud" button'); + if (!(await page.locator('#content button', { hasText: 'Check again' }).count())) problems.push('Health: no "Check again" button'); + if (!(await page.locator('#content details.store-error-details:not([open])').count())) problems.push('Health: the raw text is not in a collapsed Details'); + noRaw('Health', h); + await turnOn.click({ timeout: WAIT_MS }).catch(() => {}); + await settle(page); + const want = `https://console.cloud.google.com/apis/library/playdeveloperreporting.googleapis.com?project=${EXAMPLE_CLOUD_PROJECT}`; + if (!opened.includes(want)) problems.push(`Health: the button opened ${JSON.stringify(opened)} (want ${want})`); + await crashCheck('Health'); + visited++; + } else { + await page.locator('[role="tab"]#tab-checks').click({ timeout: WAIT_MS }).catch(e => problems.push(`no Checks tab: ${String(e).split('\n')[0]}`)); + await shows(page, '#content', variant === 'scan-findings' ? 'Sign-up without in-app account deletion' : SCAN_FAILED_LINE); + await settle(page); + const c = await text(); + if (variant === 'scan-findings') { + if (!c.includes('5.1.1(v) · Sign-up without in-app account deletion')) problems.push('Checks: the scan findings (exit 1) are not listed'); + if (!c.includes('lib/auth/sign_up.dart:12')) problems.push('Checks: the finding\'s evidence is not shown'); + } else if (!c.includes(SCAN_FAILED_LINE)) problems.push(`Checks: the failure does not show the command's error line "${SCAN_FAILED_LINE}"`); + noRaw('Checks', c); + await crashCheck('Checks'); + visited++; + } + } catch (e) { + problems.push(`case stopped: ${String(e).split('\n')[0]}`); + } finally { + await ctx.close(); + server.stop(true); + } + for (const l of logged) (l.startsWith('error') ? problems : notes).push(`webview.log: ${l}`); + if (unmocked.size) notes.push(`not answered (the window handled the rejection): ${[...unmocked].join(', ')}`); + return { name, ok: problems.length === 0, problems: [...new Set(problems)], visited, notes }; +} + /** * One headless browser for every case, as a browser server that is KILLED at the end (a throwaway profile, nothing to * flush): Google Chrome's graceful close takes 10-30 s after http pages (tests/helpers/browser.ts). Playwright's @@ -615,6 +723,7 @@ export async function bootCheck(): Promise { for (const base of ['d3-full', 'd1-missing-folders'] as const) for (const v of ['ready', 'unresolved'] as const) if (!ONLY.length || ONLY.includes('submit') || ONLY.includes(`submit-${v}`)) cases.push(() => runSubmitCase(browser, sidecar, base, v)); for (const p404 of [true, false]) if (!ONLY.length || ONLY.includes('release-state')) cases.push(() => runReleaseStateCase(browser, sidecar, p404)); + for (const v of ['api-disabled', 'scan-findings', 'scan-failed'] as const) if (!ONLY.length || ONLY.includes('errors') || ONLY.includes(`errors-${v}`)) cases.push(() => runErrorCase(browser, sidecar, v)); const results: CaseResult[] = new Array(cases.length); let next = 0; try { From 0fb4ce0001bf96675a2a0f8163b270a53b4f9007 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 23:36:30 +0800 Subject: [PATCH 006/429] desktop reads everything by itself: one background read scheduler (4 per store, starts spaced per account, App Store Connect X-Rate-Limit slows it below 20 % and pauses at 100 left, backoff with jitter on 429 / RESOURCE_EXHAUSTED, visible app first, one read per key), per-method TTLs over the saved reads, Settings auto-read (on) and interval (15 min, paused while hidden), Refresh all, a refresh icon and 'read 3 min ago' / 'couldn't refresh' per card, writes invalidate, status line with progress and quota; quota reaches the window through ToolResult.quota (cli/lib/quota.ts); Health top issues open with versions, sample stack (health --issue / --signature, read health_issue), Open in Play Console, Copy for AI and likely-cause hints (cli/lib/crash-hints.ts); tests/scheduler.test.ts, tests/quota-crash-hints.test.ts, boot check auto-read case --- CHANGELOG.md | 14 + apps/desktop/src-tauri/src/workspace.rs | 12 +- apps/desktop/src-tauri/tests/workspace.rs | 9 + apps/desktop/src/App.tsx | 25 +- apps/desktop/src/api.ts | 5 +- apps/desktop/src/dev/fixtures.ts | 26 +- apps/desktop/src/i18n/en.ts | 33 +++ apps/desktop/src/i18n/tr.ts | 33 +++ apps/desktop/src/lib/freshness.ts | 77 ++++++ apps/desktop/src/lib/issues.ts | 60 ++++ apps/desktop/src/lib/model.ts | 10 +- apps/desktop/src/lib/normalize.ts | 3 +- apps/desktop/src/lib/scheduler.ts | 243 +++++++++++++++++ apps/desktop/src/screens/Portfolio.tsx | 9 +- apps/desktop/src/screens/Settings.tsx | 12 +- apps/desktop/src/screens/tabs/Catalog.tsx | 8 +- apps/desktop/src/screens/tabs/Checks.tsx | 6 +- apps/desktop/src/screens/tabs/Growth.tsx | 6 +- apps/desktop/src/screens/tabs/Health.tsx | 105 +++++-- apps/desktop/src/screens/tabs/Prices.tsx | 4 +- apps/desktop/src/screens/tabs/Releases.tsx | 3 +- apps/desktop/src/screens/tabs/Reviews.tsx | 8 +- apps/desktop/src/screens/tabs/Submit.tsx | 10 +- apps/desktop/src/screens/tabs/TestFlight.tsx | 9 +- apps/desktop/src/store.tsx | 226 +++++++++++---- apps/desktop/src/styles.css | 13 + apps/desktop/src/ui/kit.tsx | 16 +- .../state/d1-missing-folders.host.json | 2 + .../tests/fixtures/state/d3-full.host.json | 2 + .../tests/fixtures/state/empty.host.json | 2 + .../fixtures/state/shared-profiles.host.json | 2 + apps/desktop/tests/scheduler.test.ts | 257 ++++++++++++++++++ cli/apple/asc.ts | 4 + cli/health.ts | 35 ++- cli/lib/crash-hints.ts | 22 ++ cli/lib/desktop-protocol.ts | 2 + cli/lib/health.ts | 82 +++++- cli/lib/quota.ts | 51 ++++ cli/lib/runner.ts | 10 +- cli/mcp-tools.ts | 4 + cli/play/client.ts | 2 + cli/play/google.ts | 2 + cli/serve.ts | 6 +- docs/desktop.md | 31 ++- tests/quota-crash-hints.test.ts | 61 +++++ tools/desktop-boot-check.ts | 110 +++++++- 46 files changed, 1531 insertions(+), 141 deletions(-) create mode 100644 apps/desktop/src/lib/freshness.ts create mode 100644 apps/desktop/src/lib/issues.ts create mode 100644 apps/desktop/src/lib/scheduler.ts create mode 100644 apps/desktop/tests/scheduler.test.ts create mode 100644 cli/lib/crash-hints.ts create mode 100644 cli/lib/quota.ts create mode 100644 tests/quota-crash-hints.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 327617c..d82704e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- **Desktop reads everything by itself.** No more "Not read yet" and a Read button on every page: on start, when the + window shows again and every 15 minutes while it is open (Settings: auto-read on / off, interval), every app's + status, releases and submission state, TestFlight, catalog, prices, listings, health, reviews, analytics and checks + are read in the background when their saved copy is older than its TTL (5 min to 6 h). Saved reads show at once + with "read 3 min ago"; a failed refresh keeps them with "couldn't refresh: ". One scheduler keeps it inside + the stores' limits: 4 at a time per store, starts spaced per account, slower below 20 % of App Store Connect's + hourly limit (read from `X-Rate-Limit`) and a pause at 100 left, exponential backoff with jitter on 429 / + RESOURCE_EXHAUSTED, the visible app first. "Refresh all" in the toolbar, a refresh icon per card, writes refresh + what they changed, and a status line: "Reading 12 of 48 · App Store limit 3,412/3,600 left this hour". +- **Health: open a top issue.** Full title, type, counts, versionCode range, Android API range, last report, a sample + stack trace (`storebound health --issue ` / `--signature `, new read `health_issue`), Open in Play Console, + Copy for AI, and a likely cause for known signatures (`cli/lib/crash-hints.ts`; first entry: the Capacitor + `Bridge.getPermissionStates` NullPointerException from `checkPermissions()` during an activity transition). + - **Google API errors in words, not JSON.** Google's error bodies are parsed centrally (`cli/lib/google-errors.ts`) into typed findings: `api-disabled` (403 SERVICE_DISABLED: service, Cloud project id, the console page to turn it on), `no-app-access` (403 PERMISSION_DENIED: which app, the Users and permissions step), `auth-revoked` (401, diff --git a/apps/desktop/src-tauri/src/workspace.rs b/apps/desktop/src-tauri/src/workspace.rs index 5be38c0..e8e7ab3 100644 --- a/apps/desktop/src-tauri/src/workspace.rs +++ b/apps/desktop/src-tauri/src/workspace.rs @@ -251,6 +251,12 @@ pub struct RefreshSettings { pub parallel: u8, /// Read app icons from the stores when importing (an extra request per app). pub icons: bool, + /// Background reading of every app (status, releases, catalog, prices, listings, TestFlight, health, reviews, + /// analytics, checks): on start, when the window shows again and every `every_minutes` while it is open. + pub auto_read: bool, + /// Minutes between background passes while the window is visible (only reads past their TTL run); 0 = only on + /// start and when the window shows again. + pub every_minutes: u32, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -282,7 +288,7 @@ pub struct Settings { // build that lacks a newer setting keeps the rest. impl Default for RefreshSettings { fn default() -> RefreshSettings { - RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true } + RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true, auto_read: true, every_minutes: 15 } } } @@ -306,11 +312,15 @@ impl Default for Settings { pub const AUTO_MINUTES: &[u32] = &[0, 15, 30, 60, 180, 720]; pub const KEEP_DAYS: &[u32] = &[0, 7, 30, 90, 365]; +pub const EVERY_MINUTES: &[u32] = &[0, 5, 15, 30, 60]; pub fn check_settings(s: &Settings) -> Result<(), String> { if !AUTO_MINUTES.contains(&s.refresh.auto_minutes) { return Err("refresh: 0 (off), 15, 30, 60, 180 or 720 minutes".into()); } + if !EVERY_MINUTES.contains(&s.refresh.every_minutes) { + return Err("background reading: 0 (only on start), 5, 15, 30 or 60 minutes".into()); + } if !(1..=8).contains(&s.refresh.parallel) { return Err("parallel reads: 1 to 8".into()); } diff --git a/apps/desktop/src-tauri/tests/workspace.rs b/apps/desktop/src-tauri/tests/workspace.rs index 143331c..26c49b3 100644 --- a/apps/desktop/src-tauri/tests/workspace.rs +++ b/apps/desktop/src-tauri/tests/workspace.rs @@ -106,6 +106,15 @@ fn settings_have_safe_defaults_and_bounds() { s = d.clone(); s.refresh.auto_minutes = 1; assert!(check_settings(&s).is_err(), "no tight polling of the store APIs"); + assert_eq!((d.refresh.auto_read, d.refresh.every_minutes), (true, 15), "background reading is on by default, every 15 minutes"); + s = d.clone(); + s.refresh.every_minutes = 1; + assert!(check_settings(&s).is_err(), "no background pass more often than every 5 minutes"); + s = d.clone(); + s.refresh.every_minutes = 0; + assert!(check_settings(&s).is_ok()); + let old: Settings = serde_json::from_value(serde_json::json!({ "refresh": { "autoMinutes": 15 } })).unwrap(); + assert_eq!((old.refresh.auto_read, old.refresh.every_minutes, old.refresh.auto_minutes), (true, 15, 15), "an older settings file gets the new defaults"); s = d.clone(); s.cache.keep_days = 3; assert!(check_settings(&s).is_err()); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 12c9780..4c77cad 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { FIXTURES, onDeepLink, onDeepLinkFolder } from './api'; import { devSwitch } from './dev/switches'; import { type Key, t } from './i18n'; -import { ago } from './lib/format'; +import { ago, num } from './lib/format'; import { groupByStudio, type UnifiedApp } from './lib/identity'; import { NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav'; import { usePrefs } from './prefs-ctx'; @@ -133,6 +133,9 @@ export function App({ onTheme }: { onTheme: () => void }) { : route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }] : [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }]; const lastRead = d.live?.at ?? null; + // the app on screen is read first by the background reader + const { setFocus } = d; + useEffect(() => { setFocus(app?.key ?? null); }, [app?.key, setFocus]); const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]); const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) || (r.screen !== 'app' && r.screen !== 'portfolio' && r.screen === route.screen) ? 'page' : undefined); const groups = d.studios.length ? groupByStudio(visible.map(a => ({ app: a })), d.studios) : [{ studio: null as string | null, rows: visible.map(a => ({ app: a })) }]; @@ -202,6 +205,7 @@ export function App({ onTheme }: { onTheme: () => void }) {
{d.sidecar?.running ? t('foot.cli', { version: d.sidecar.version }) : d.sidecarError ? t('foot.cliDown') : t('foot.cliStarting')}
{lastRead ? t('foot.lastRead', { when: ago(lastRead) }) : t('foot.neverRead')}
+
@@ -217,8 +221,8 @@ export function App({ onTheme }: { onTheme: () => void }) { {FIXTURES && {t('dev.fixtures')}} {lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')} - @@ -242,3 +246,18 @@ export function App({ onTheme }: { onTheme: () => void }) { ); } + +/** The background reader in one line: "Reading 12 of 48 · App Store limit 3 412/3 600 left this hour". */ +function ReaderLine() { + const d = useData(); + const r = d.reader; + const q = Object.values(r.quota).sort((a, b) => a.remaining - b.remaining)[0]; + const parts: string[] = []; + if (r.total > 0 && (r.running || r.queued)) parts.push(t('reader.progress', { done: r.done, total: r.total })); + else if (!d.reader.autoRead) parts.push(t('reader.off')); + else if (d.ready && d.apps.length) parts.push(t('reader.upToDate')); + if (Object.keys(r.paused).length) parts.push(t('reader.backoff')); + if (q) parts.push(t('reader.appleQuota', { left: num(q.remaining), limit: num(q.limit) })); + if (!parts.length) return null; + return
{parts.join(' · ')}
; +} diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 68c32f8..31a5b1f 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -28,12 +28,13 @@ export type StudioColor = (typeof STUDIO_COLORS)[number]; /** A user-named group of store accounts (and so of apps). */ export interface Studio { id: string; name: string; color: StudioColor; logo: string | null; created: string } export interface Settings { - refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean }; + /** autoRead / everyMinutes: the background reader (store.tsx); autoMinutes / onLaunch: older builds' settings, kept for them. */ + refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean; autoRead: boolean; everyMinutes: 0 | 5 | 15 | 30 | 60 }; cache: { keepDays: 0 | 7 | 30 | 90 | 365 }; notify: { reviewState: boolean; lowReviews: boolean; crash: boolean }; channel: 'stable' | 'beta'; } -export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' }; +export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true, autoRead: true, everyMinutes: 15 }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' }; export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings } export interface AccountApps { account: string; entry: CacheEntry | null } export interface CacheInfo { rows: number; bytes: number; oldest: string | null; file_bytes: number } diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 496024b..5e1a63a 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -216,8 +216,8 @@ const HEALTH: Record = { anr: rows('Anr', series(28, 0.0024, 0.0004, 2), 0.0027), devices: [{ model: 'Galaxy A12', crash: 0.061, users: 1900 }, { model: 'Redmi 9A', crash: 0.042, users: 1400 }, { model: 'Moto G Power (2021)', crash: 0.019, users: 900 }, { model: 'Pixel 6a', crash: 0.008, users: 2100 }, { model: 'Galaxy S23', crash: 0.004, users: 2600 }], issues: [ - { type: 'CRASH', cause: 'java.lang.IllegalStateException', location: 'com.example.prismpuddle.combo.ComboMeter.update', reports: 412, users: 268, lastVersion: '231' }, - { type: 'ANR', cause: 'Input dispatching timed out', location: 'com.example.prismpuddle.MainActivity', reports: 133, users: 120, lastVersion: '231' }, + { type: 'CRASH', cause: 'java.lang.IllegalStateException: ComboMeter.update called after the level ended (com.example.prismpuddle.combo.ComboMeter)', location: 'com.example.prismpuddle.combo.ComboMeter.update', reports: 412, users: 268, lastVersion: '231', firstVersion: '224', firstOs: '26', lastOs: '35', lastSeen: iso(95), id: 'a1b2c3', uri: 'https://play.google.com/console/developers/app/vitals/crashes/a1b2c3/details' }, + { type: 'ANR', cause: 'Input dispatching timed out', location: 'com.example.prismpuddle.MainActivity', reports: 133, users: 120, lastVersion: '231', firstVersion: '229', lastSeen: iso(300), id: 'd4e5f6', uri: 'https://play.google.com/console/developers/app/vitals/crashes/d4e5f6/details' }, { type: 'CRASH', cause: 'java.lang.OutOfMemoryError', location: 'android.graphics.Bitmap.createBitmap', reports: 74, users: 61, lastVersion: '221' }, ], }, @@ -230,7 +230,7 @@ const HEALTH: Record = { { category: 'Battery', metric: 'Foreground energy', unit: '%/h', version: '2.3.0', value: 9.4, goal: 'poor' }, ], signatures: [ - { build: '48', type: 'HANGS', signature: 'ComboMeter.update(delta:) + 212', weight: 0.31 }, + { build: '48', type: 'HANGS', signature: 'ComboMeter.update(delta:) + 212', weight: 0.31, id: 'sig-hang-1' }, { build: '48', type: 'DISK_WRITES', signature: 'SaveStore.flush() + 88', weight: 0.12 }, { build: '47', type: 'LAUNCHES', signature: 'AssetCache.warmUp() + 64', weight: 0.07 }, ], @@ -411,7 +411,23 @@ const STORE_REVIEWS: Review[] = [ R('play', 's-p2', 2, 'Too many ads', 'An ad after every round is too much.', 'en', 5), R('apple', 's-a3', 5, 'Harika', 'Her gün kullanıyorum, çok sade.', 'TUR', 7), ]; +/** A sample report of a Health issue (`health --issue / --signature --json`). */ +const ISSUE_SAMPLE = (args: Record) => ({ sample: args.signature ? { + store: 'apple', version: '2.3.0 (48)', device: 'iPhone15,2', os: 'iOS 18.6', stack: ['PrismPuddle ComboMeter.update(delta:) + 212', 'PrismPuddle GameLoop.tick() + 88', 'QuartzCore CA::Display::DisplayLink::dispatch_items + 1012', 'UIKitCore -[UIApplication _run] + 888', 'PrismPuddle main + 64'], +} : { + store: 'play', type: 'CRASH', version: '231', device: 'Galaxy A12', os: 'API 31', time: iso(95), + stack: ['java.lang.IllegalStateException: ComboMeter.update called after the level ended', '\tat com.example.prismpuddle.combo.ComboMeter.update(ComboMeter.kt:88)', '\tat com.example.prismpuddle.level.Level.tick(Level.kt:214)', '\tat com.example.prismpuddle.GameLoop.run(GameLoop.kt:51)', '\tat android.os.Handler.handleCallback(Handler.java:958)', '\tat android.os.Looper.loop(Looper.java:294)'], +} }); + +/** One read as the sidecar would answer it (exported for the desktop boot check's auto-read case). */ +export function fixtureRead(method: string, id: string, args: Record = {}): ToolResult { + const r = read(method, id, args); + // App Store Connect reads carry the key's hourly quota (X-Rate-Limit), so the status line has something to show + return method.startsWith('apple.') && r.ok ? { ...r, quota: { store: 'apple', limit: 3600, remaining: 3412 } } : r; +} + function read(method: string, id: string, args: Record = {}): ToolResult { + if (method === 'health.issue') return ok(method, ISSUE_SAMPLE(args)); if (id.startsWith('store:')) { const play = /android:/.test(id); switch (method) { @@ -475,7 +491,7 @@ const CONSOLE_FILL: Record = { }; const CACHED_AGO: Record = { health: 60 * 3, 'reviews.list': 45, 'apple.testflight_status': 60 * 5, 'catalog.diff': 60 * 26, validate: 60 * 2, 'prices.current': 60 * 4, 'apple.ppo_status': 60 * 6 }; -const NETWORK = new Set(['health', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'prices.current', 'prices.diff', 'apple.ppo_status', 'apple.status', 'play.status', 'console.verify']); +const NETWORK = new Set(['health', 'health.issue', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'prices.current', 'prices.diff', 'apple.ppo_status', 'apple.status', 'play.status', 'console.verify']); async function progressLines(job: string | null, lines: string[]) { for (const line of lines) { await sleep(260); if (job) emit('sidecar-progress', { params: { requestId: 1, line, stream: 'stderr' }, job }); } @@ -549,7 +565,7 @@ async function answer(cmd: string, a: Record): Promise if (NETWORK.has(method)) await progressLines(job, [`[${method}] reading App Store Connect`, `[${method}] reading Google Play`, `[${method}] done`]); else await sleep(150); if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; - return read(method, id, ((a.params as { args?: Record } | null)?.args) ?? {}); + return fixtureRead(method, id, ((a.params as { args?: Record } | null)?.args) ?? {}); } case 'job_cancel': cancelled.add(a.job as string); return true; case 'write_with_confirm': { diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index b400165..9013ee9 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -753,6 +753,39 @@ export const en = { 'set.refreshSub': 'Reads use each account\'s API quota: they run when you ask, or on the schedule here', 'set.autoRefresh': 'Read the stores automatically', 'set.autoHint': 'While the app is open. Off by default.', + 'health.likelyCause': 'Likely cause:', + 'health.suggestedFix': 'Fix:', + 'health.copied': "Copied for AI: paste it into your agent", + 'health.copyFailed': "Could not copy to the clipboard", + 'health.issueType': "Type", + 'health.issueWhere': "Location", + 'health.issueShare': "Share of reports", + 'health.issueVersions': "versionCode", + 'health.issueBuild': "Build", + 'health.issueOs': "Android API", + 'health.issueLastSeen': "Last report", + 'health.sample': "Sample stack trace", + 'health.noSample': "No sample report in the last 28 days.", + 'health.copyForAi': "Copy for AI", + 'health.openConsole': "Open in Play Console", + 'health.issuesUnread': "Top issues not read: {error}", + 'set.autoRead': "Read everything automatically", + 'set.autoReadHint': "Status, releases, catalog, prices, listings, TestFlight, health, reviews and checks of every app, in the background, inside the stores' limits", + 'set.everyMinutes': "While the app is open, read again every", + 'set.onlyOnStart': "Only on start", + 'set.everyHint': "Only reads past their age limit run (status 5 min, reviews 15 min, catalog and prices 30 min, health and analytics 6 h). Paused while the window is hidden.", + 'action.refreshAll': "Refresh all", + 'action.refreshAllHint': "Read everything of every app again now (read-only, inside the stores' limits)", + 'read.ago': "read {when}", + 'read.refreshing': "Refreshing…", + 'read.couldNotRefresh': "couldn't refresh: {reason}", + 'read.refresh': "Refresh", + 'read.waiting': "Reading…", + 'reader.progress': "Reading {done} of {total}", + 'reader.upToDate': "Everything read", + 'reader.off': "Auto-read is off", + 'reader.appleQuota': "App Store limit {left}/{limit} left this hour", + 'reader.backoff': "The store asked to slow down: waiting", 'set.off': 'Off', 'set.min': '{n} min', 'set.hour': '{n} h', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 617b88a..703ba4a 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -755,6 +755,39 @@ export const tr: Record = { 'set.refreshSub': 'Okumalar her hesabın API kotasını kullanır: siz istediğinizde ya da buradaki zamanlamayla çalışır', 'set.autoRefresh': 'Mağazaları otomatik oku', 'set.autoHint': 'Uygulama açıkken. Varsayılan olarak kapalı.', + 'health.likelyCause': 'Olası neden:', + 'health.suggestedFix': 'Çözüm:', + 'health.copied': "Yapay zekâ için kopyalandı: ajanınıza yapıştırın", + 'health.copyFailed': "Panoya kopyalanamadı", + 'health.issueType': "Tür", + 'health.issueWhere': "Konum", + 'health.issueShare': "Raporlardaki payı", + 'health.issueVersions': "versionCode", + 'health.issueBuild': "Derleme", + 'health.issueOs': "Android API", + 'health.issueLastSeen': "Son rapor", + 'health.sample': "Örnek yığın izi", + 'health.noSample': "Son 28 günde örnek rapor yok.", + 'health.copyForAi': "Yapay zekâ için kopyala", + 'health.openConsole': "Play Console'da aç", + 'health.issuesUnread': "Öne çıkan hatalar okunamadı: {error}", + 'set.autoRead': "Her şeyi otomatik oku", + 'set.autoReadHint': "Her uygulamanın durumu, sürümleri, kataloğu, fiyatları, mağaza metinleri, TestFlight, sağlık, yorumlar ve kontrolleri arka planda, mağaza limitlerinin içinde okunur", + 'set.everyMinutes': "Uygulama açıkken yeniden okuma aralığı", + 'set.onlyOnStart': "Sadece açılışta", + 'set.everyHint': "Yalnızca süresi dolan okumalar çalışır (durum 5 dk, yorumlar 15 dk, katalog ve fiyatlar 30 dk, sağlık ve analiz 6 sa). Pencere gizliyken durur.", + 'action.refreshAll': "Hepsini yenile", + 'action.refreshAllHint': "Her uygulamanın her şeyini şimdi yeniden oku (salt okunur, mağaza limitlerinin içinde)", + 'read.ago': "{when} okundu", + 'read.refreshing': "Yenileniyor…", + 'read.couldNotRefresh': "yenilenemedi: {reason}", + 'read.refresh': "Yenile", + 'read.waiting': "Okunuyor…", + 'reader.progress': "{total} okumadan {done} tamam", + 'reader.upToDate': "Her şey okundu", + 'reader.off': "Otomatik okuma kapalı", + 'reader.appleQuota': "App Store limiti: bu saat {left}/{limit} kaldı", + 'reader.backoff': "Mağaza yavaşlamamızı istedi: bekleniyor", 'set.off': 'Kapalı', 'set.min': '{n} dk', 'set.hour': '{n} sa', diff --git a/apps/desktop/src/lib/freshness.ts b/apps/desktop/src/lib/freshness.ts new file mode 100644 index 0000000..1866caa --- /dev/null +++ b/apps/desktop/src/lib/freshness.ts @@ -0,0 +1,77 @@ +// How long a saved read stays fresh, which store lanes a read uses, and the reads the background reader does for +// every app. Pure (tests/scheduler.test.ts). +import type { Lane } from './scheduler'; + +const MIN = 60_000; + +/** Time to live of a saved read per method: status and submission state 5 min, reviews 15 min, catalog / prices / + * listings 30 min, health and analytics 6 h (the stores update them daily). */ +export const TTL: Record = { + 'portfolio.status': 5 * MIN, + 'apple.status': 5 * MIN, + 'play.status': 5 * MIN, + 'apple.testflight_status': 5 * MIN, + 'reviews.list': 15 * MIN, + 'catalog.diff': 30 * MIN, + 'prices.current': 30 * MIN, + 'project.listings': 30 * MIN, + 'apple.ppo_status': 30 * MIN, + validate: 30 * MIN, + scan: 30 * MIN, + health: 6 * 60 * MIN, + 'health.issue': 6 * 60 * MIN, + 'analytics.compare': 6 * 60 * MIN, + 'aso.audit': 6 * 60 * MIN, +}; +export const DEFAULT_TTL = 30 * MIN; + +export const ttlOf = (method: string): number => TTL[method] ?? DEFAULT_TTL; + +/** True when a read saved at `at` (ISO) is older than its TTL, or there is none. */ +export function isStale(method: string, at: string | null | undefined, now = Date.now()): boolean { + if (!at) return true; + const t = Date.parse(at); + return !Number.isFinite(t) || now - t >= ttlOf(method); +} + +/** The store lanes a read takes a slot in. */ +export function lanesOf(method: string, o: { ios: boolean; android: boolean }): Lane[] { + if (method.startsWith('apple.')) return ['apple']; + if (method.startsWith('play.')) return ['play']; + if (['project.listings', 'scan', 'analytics.compare', 'aso.audit', 'reviews.drafts', 'project.declarations', 'project.renders', 'project.icon'].includes(method)) return ['local']; + const l: Lane[] = []; + if (o.ios) l.push('apple'); + if (o.android) l.push('play'); + return l.length ? l : ['local']; +} + +export interface PlannedRead { method: string; args: Record } + +/** The reads the background reader does for one app (the ones its tabs show), by what the app has. */ +export function readsFor(o: { folder: boolean; ios: boolean; android: boolean }): PlannedRead[] { + const r: PlannedRead[] = []; + const add = (method: string, args: Record = {}) => r.push({ method, args }); + if (o.ios) { add('apple.status'); add('apple.testflight_status'); } + if (o.android) add('play.status'); + if (o.ios || o.android) { add('reviews.list', { days: 30 }); add('health'); } + if (o.folder) { + add('scan'); add('project.listings'); + if (o.ios || o.android) { add('catalog.diff'); add('prices.current'); add('validate'); } + add('analytics.compare'); add('aso.audit'); + } + if (o.ios) add('apple.ppo_status'); + return r; +} + +/** Key of one read in the scheduler and the read bus. */ +export const readKey = (target: string, method: string, args: Record = {}): string => `${target}\u001f${method}\u001f${JSON.stringify(args)}`; + +/** "429", "RESOURCE_EXHAUSTED", "rate limit": the store refused for its quota (not the read itself). */ +export const looksThrottled = (text: string | undefined): boolean => !!text && /\b429\b|RESOURCE_EXHAUSTED|rate.?limit|quota exceeded/i.test(text); + +/** The one-line reason of a failed read, for "couldn't refresh: ". */ +export function oneLine(text: string, max = 140): string { + const l = text.trim().split('\n').map(s => s.trim()).filter(Boolean).at(-1) ?? ''; + const s = l.replace(/^\S+ \[[^\]]+\] /, ''); + return s.length > max ? `${s.slice(0, max - 1)}…` : s; +} diff --git a/apps/desktop/src/lib/issues.ts b/apps/desktop/src/lib/issues.ts new file mode 100644 index 0000000..5c8660d --- /dev/null +++ b/apps/desktop/src/lib/issues.ts @@ -0,0 +1,60 @@ +// One crash / ANR issue in detail (Health tab): the Play error issue or App Store diagnostic signature, its sample +// stack (`health.issue`), and the compact "Copy for AI" markdown. Pure (tests/model.test.ts). +import { type CrashHint, crashHint } from '../../../../cli/lib/crash-hints'; +import type { IssueSample, PlayIssue, AppleSignature } from './model'; + +/** Likely cause of a known signature, from the issue text and its sample stack. */ +export const hintFor = (v: IssueView, sample: IssueSample | null): CrashHint | null => crashHint(v.title, v.where, ...(sample?.stack.slice(0, 30) ?? [])); + +export interface IssueView { + store: 'play' | 'apple'; + title: string; + /** Exception type / diagnostic type. */ + kind: string; + where?: string; + reports?: number; + users?: number; + weight?: number; + versions?: { first?: string; last?: string }; + os?: { first?: string; last?: string }; + lastSeen?: string; + build?: string; + url?: string; + /** Args of the `health.issue` read for its sample stack; null when there is no id to ask for. */ + sampleArgs: Record | null; +} + +export function playIssueView(i: PlayIssue): IssueView { + return { + store: 'play', title: i.cause || i.location || '?', kind: i.type === 'ANR' ? 'ANR' : i.type, where: i.location || undefined, reports: i.reports, users: i.users, + versions: { first: i.firstVersion, last: i.lastVersion }, os: i.firstOs || i.lastOs ? { first: i.firstOs, last: i.lastOs } : undefined, lastSeen: i.lastSeen, url: i.uri, + sampleArgs: i.id ? { issue: i.id } : null, + }; +} + +export function appleSignatureView(s: AppleSignature): IssueView { + return { store: 'apple', title: s.signature || s.type, kind: s.type, weight: s.weight, build: s.build, sampleArgs: s.id ? { signature: s.id } : null }; +} + +/** The top frames worth pasting (the full sample stays in the window). */ +export const TOP_FRAMES = 15; + +/** Compact markdown for an AI agent: title, type, where, counts, versions, top frames. */ +export function issueMarkdown(app: string, v: IssueView, sample: IssueSample | null): string { + const out = [`## ${v.store === 'play' ? 'Google Play' : 'App Store'} ${v.kind}: ${v.title}`, '', `- App: ${app}`]; + if (v.where && v.where !== v.title) out.push(`- Location: ${v.where}`); + if (v.reports !== undefined) out.push(`- Reports: ${v.reports}${v.users !== undefined ? `, users: ${v.users}` : ''}`); + if (v.weight !== undefined) out.push(`- Share of reports: ${Math.round(v.weight * 1000) / 10} %`); + if (v.versions?.first || v.versions?.last) out.push(`- versionCode: ${v.versions.first ?? '?'} to ${v.versions.last ?? '?'}`); + if (v.build) out.push(`- Build: ${v.build}`); + if (v.os) out.push(`- Android API: ${v.os.first ?? '?'} to ${v.os.last ?? '?'}`); + if (v.lastSeen) out.push(`- Last report: ${v.lastSeen}`); + const hint = hintFor(v, sample); + if (hint) out.push(`- Likely cause: ${hint.cause}`, `- Suggested fix: ${hint.fix}`); + if (sample) { + const meta = [sample.version && `version ${sample.version}`, sample.device, sample.os].filter(Boolean).join(', '); + out.push('', `Sample report${meta ? ` (${meta})` : ''}, top frames:`, '', '```', ...sample.stack.slice(0, TOP_FRAMES), ...(sample.stack.length > TOP_FRAMES ? [`... ${sample.stack.length - TOP_FRAMES} more frames`] : []), '```'); + } + if (v.url) out.push('', `Console: ${v.url}`); + return out.join('\n') + '\n'; +} diff --git a/apps/desktop/src/lib/model.ts b/apps/desktop/src/lib/model.ts index 7ee1677..6eed9e5 100644 --- a/apps/desktop/src/lib/model.ts +++ b/apps/desktop/src/lib/model.ts @@ -17,11 +17,17 @@ export interface PlayHealth { crash: MetricRow[]; anr: MetricRow[]; devices?: { model: string; crash?: number; anr?: number; users?: number }[]; - issues: { type: string; cause: string; location: string; reports: number; users: number; lastVersion?: string }[]; + issues: PlayIssue[]; + issuesError?: string; } +/** One Play error issue (errorIssues:search; id / versions / API levels / last report when the API sent them). */ +export interface PlayIssue { type: string; cause: string; location: string; reports: number; users: number; lastVersion?: string; uri?: string; id?: string; firstVersion?: string; firstOs?: string; lastOs?: string; lastSeen?: string } +export interface AppleSignature { build: string; type: string; signature: string; weight: number; id?: string } +/** `health --issue / --signature --json`: one sample report's stack, top frame first. */ +export interface IssueSample { store: 'play' | 'apple'; time?: string; version?: string; os?: string; device?: string; type?: string; stack: string[] } export interface AppleHealth { metrics: { category: string; metric: string; unit: string; version: string; value: number; goal?: string }[]; - signatures: { build: string; type: string; signature: string; weight: number }[]; + signatures: AppleSignature[]; betaCrashes: { build: string; count: number }[]; } export type StoreReadError = import('../../../../cli/lib/health').StoreReadError; diff --git a/apps/desktop/src/lib/normalize.ts b/apps/desktop/src/lib/normalize.ts index c26f5eb..36e7844 100644 --- a/apps/desktop/src/lib/normalize.ts +++ b/apps/desktop/src/lib/normalize.ts @@ -55,7 +55,8 @@ export function normalizeSettings(v: unknown): Settings { if (!isRec(v)) return d; const r = isRec(v.refresh) ? v.refresh : {}, c = isRec(v.cache) ? v.cache : {}, n = isRec(v.notify) ? v.notify : {}; return { - refresh: { autoMinutes: pick(r.autoMinutes, d.refresh.autoMinutes, isNum), onLaunch: pick(r.onLaunch, d.refresh.onLaunch, isBool), parallel: pick(r.parallel, d.refresh.parallel, isNum), icons: pick(r.icons, d.refresh.icons, isBool) }, + refresh: { autoMinutes: pick(r.autoMinutes, d.refresh.autoMinutes, isNum), onLaunch: pick(r.onLaunch, d.refresh.onLaunch, isBool), parallel: pick(r.parallel, d.refresh.parallel, isNum), icons: pick(r.icons, d.refresh.icons, isBool), + autoRead: pick(r.autoRead, d.refresh.autoRead, isBool), everyMinutes: pick(r.everyMinutes, d.refresh.everyMinutes, (x: unknown) => [0, 5, 15, 30, 60].includes(x as number)) }, cache: { keepDays: pick(c.keepDays, d.cache.keepDays, isNum) }, notify: { reviewState: pick(n.reviewState, d.notify.reviewState, isBool), lowReviews: pick(n.lowReviews, d.notify.lowReviews, isBool), crash: pick(n.crash, d.notify.crash, isBool) }, channel: v.channel === 'beta' ? 'beta' : 'stable', diff --git a/apps/desktop/src/lib/scheduler.ts b/apps/desktop/src/lib/scheduler.ts new file mode 100644 index 0000000..14586de --- /dev/null +++ b/apps/desktop/src/lib/scheduler.ts @@ -0,0 +1,243 @@ +// The background read scheduler: every store read of the window goes through one queue, so reading "everything for +// every app" stays far inside the stores' limits. Pure logic with an injectable clock (tests/scheduler.test.ts). +// +// - Lanes: 'apple' (App Store Connect), 'play' (Google Play Developer + Reporting API), 'local' (offline project +// reads). A task takes one slot in each of its lanes; each lane has its own concurrency limit (default 4). +// - Credentials: starts on one key are spaced (default 250 ms apart). App Store Connect sends X-Rate-Limit +// (user-hour-lim / user-hour-rem, about 3600 per key per hour): below 20 % left, the spacing spreads the rest over the +// hour; at the reserve (default 100, kept for the owner's own commands) the key pauses for 10 minutes. +// - 429 / RESOURCE_EXHAUSTED: the task waits and runs again with exponential backoff and jitter (and its key waits too), +// at most `maxAttempts` times. +// - Priority: 0 the visible app and tab, 1 portfolio status, 2 the rest; FIFO within a priority. +// - Dedupe: one in-flight (or queued) read per key; enqueueing it again returns the same promise (and may raise its +// priority). + +export type Lane = 'apple' | 'play' | 'local'; +export type Priority = 0 | 1 | 2; + +export interface Clock { + now(): number; + setTimeout(fn: () => void, ms: number): unknown; + clearTimeout(h: unknown): void; + random(): number; +} + +export const realClock: Clock = { + now: () => Date.now(), + setTimeout: (fn, ms) => setTimeout(fn, ms), + clearTimeout: h => clearTimeout(h as ReturnType), + random: () => Math.random(), +}; + +export interface QuotaSeen { limit?: number; remaining?: number; throttled?: boolean } + +/** What one finished run says about the store's limits. */ +export interface Outcome { + /** 429 / RESOURCE_EXHAUSTED: run it again later. */ + throttled?: boolean; + /** Quota per credential (App Store Connect X-Rate-Limit). */ + quota?: { credential: string; limit: number; remaining: number }; +} + +export interface ReadTask { + key: string; + lanes: Lane[]; + /** Keys of the store credentials it uses ("apple:", "play:"). */ + credentials: string[]; + priority: Priority; + run: () => Promise; +} + +export interface SchedulerOptions { + limits?: Partial>; + /** Minimum gap between two starts on one credential. */ + spacingMs?: number; + /** Requests per hour kept free on an App Store Connect key for the owner's own commands. */ + reserve?: number; + /** Below this share of the hourly limit left, starts are spread over the rest of the hour. */ + slowBelow?: number; + /** How long a key pauses once it is at the reserve. */ + pauseMs?: number; + backoffBaseMs?: number; + backoffMaxMs?: number; + maxAttempts?: number; + clock?: Clock; + /** Reads a result (or the error) for throttling and quota. */ + classify?: (result: unknown, error: unknown, task: ReadTask) => Outcome; +} + +export interface SchedulerStats { + queued: number; + running: number; + /** Finished in this round (since the queue was last empty). */ + done: number; + /** done + running + queued of this round. */ + total: number; + failed: number; + /** The lowest App Store Connect quota seen per credential this hour. */ + quota: Record; + /** Credentials waiting on a backoff or quota pause, with the time they may start again. */ + paused: Record; +} + +interface Item { + task: ReadTask; + seq: number; + attempt: number; + notBefore: number; + resolve: (r: R) => void; + reject: (e: unknown) => void; + promise: Promise; +} + +const HOUR = 3_600_000; + +export class ReadScheduler { + private o: Required> & { limits: Record }; + private clock: Clock; + private classify: (result: unknown, error: unknown, task: ReadTask) => Outcome; + private queue: Item[] = []; + private running = new Map>(); + private busy: Record = { apple: 0, play: 0, local: 0 }; + private nextAt = new Map(); + private quotas = new Map(); + private seq = 0; + private done = 0; + private failed = 0; + private timer: unknown = null; + private timerAt = 0; + private listeners = new Set<() => void>(); + + constructor(o: SchedulerOptions = {}) { + this.o = { + limits: { apple: 4, play: 4, local: 2, ...o.limits }, + spacingMs: o.spacingMs ?? 250, + reserve: o.reserve ?? 100, + slowBelow: o.slowBelow ?? 0.2, + pauseMs: o.pauseMs ?? 10 * 60_000, + backoffBaseMs: o.backoffBaseMs ?? 5_000, + backoffMaxMs: o.backoffMaxMs ?? 5 * 60_000, + maxAttempts: o.maxAttempts ?? 4, + }; + this.clock = o.clock ?? realClock; + this.classify = o.classify ?? (() => ({})); + } + + setLimits(limits: Partial>): void { this.o.limits = { ...this.o.limits, ...limits }; this.pump(); } + + subscribe(fn: () => void): () => void { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; } + + has(key: string): boolean { return this.running.has(key) || this.queue.some(i => i.task.key === key); } + + enqueue(task: ReadTask): Promise { + const run = this.running.get(task.key); + if (run) return run.promise as Promise; + const queued = this.queue.find(i => i.task.key === task.key); + if (queued) { + if (task.priority < queued.task.priority) { queued.task = { ...queued.task, priority: task.priority }; this.pump(); } + return queued.promise as Promise; + } + let resolve!: (r: R) => void, reject!: (e: unknown) => void; + const promise = new Promise((a, b) => { resolve = a; reject = b; }); + this.queue.push({ task, seq: ++this.seq, attempt: 0, notBefore: 0, resolve, reject, promise } as unknown as Item); + this.pump(); + this.emit(); + return promise; + } + + /** Drops queued tasks (not the running ones); their promises reject with "cancelled". */ + clear(filter: (key: string) => boolean = () => true): void { + const drop = this.queue.filter(i => filter(i.task.key)); + this.queue = this.queue.filter(i => !filter(i.task.key)); + for (const i of drop) i.reject(new Error('cancelled')); + this.pump(); + this.emit(); + } + + stats(): SchedulerStats { + const now = this.clock.now(); + const paused: Record = {}; + for (const [c, at] of this.nextAt) if (at - now > this.o.spacingMs) paused[c] = at; + const quota: SchedulerStats['quota'] = {}; + for (const [c, q] of this.quotas) if (now - q.at < HOUR) quota[c] = q; + return { queued: this.queue.length, running: this.running.size, done: this.done, total: this.done + this.running.size + this.queue.length, failed: this.failed, quota, paused }; + } + + /** Earliest time a credential may start again. */ + private gap(cred: string, now: number): number { + const q = this.quotas.get(cred); + if (!q || now - q.at >= HOUR) return this.o.spacingMs; + if (q.remaining <= this.o.reserve) return this.o.pauseMs; + if (q.remaining < q.limit * this.o.slowBelow) return Math.max(this.o.spacingMs, Math.ceil(HOUR / Math.max(1, q.remaining - this.o.reserve))); + return this.o.spacingMs; + } + + private ready(i: Item, now: number): number { + // 0 = can start now; otherwise the time it can (Infinity: waits on a lane slot) + let at = i.notBefore; + for (const c of i.task.credentials) at = Math.max(at, this.nextAt.get(c) ?? 0); + if (i.task.lanes.some(l => this.busy[l] >= Math.max(1, this.o.limits[l]))) return Infinity; + return at <= now ? 0 : at; + } + + private pump(): void { + const now = this.clock.now(); + let wake = Infinity; + for (;;) { + const order = [...this.queue].sort((a, b) => a.task.priority - b.task.priority || a.seq - b.seq); + let started = false; + for (const i of order) { + const r = this.ready(i, now); + if (r === 0) { this.start(i, now); started = true; break; } + if (r !== Infinity) wake = Math.min(wake, r); + } + if (!started) break; + } + if (this.timer !== null && (wake === Infinity || wake !== this.timerAt)) { this.clock.clearTimeout(this.timer); this.timer = null; } + if (wake !== Infinity && this.timer === null) { + this.timerAt = wake; + this.timer = this.clock.setTimeout(() => { this.timer = null; this.pump(); }, Math.max(0, wake - now)); + } + } + + private start(i: Item, now: number): void { + this.queue = this.queue.filter(x => x !== i); + this.running.set(i.task.key, i); + for (const l of i.task.lanes) this.busy[l]++; + for (const c of i.task.credentials) this.nextAt.set(c, now + this.gap(c, now)); + i.attempt++; + this.emit(); + i.task.run().then(r => this.finish(i, r, undefined, true), e => this.finish(i, undefined, e, false)); + } + + private finish(i: Item, result: unknown, error: unknown, ok: boolean): void { + const now = this.clock.now(); + this.running.delete(i.task.key); + for (const l of i.task.lanes) this.busy[l]--; + let out: Outcome = {}; + try { out = this.classify(result, error, i.task); } catch { /* a classifier bug never stalls the queue */ } + if (out.quota) { + const prev = this.quotas.get(out.quota.credential); + // the hour is the key's: keep the lowest count seen in it + const q = prev && now - prev.at < HOUR && prev.remaining < out.quota.remaining ? prev : { limit: out.quota.limit, remaining: out.quota.remaining, at: now }; + this.quotas.set(out.quota.credential, q); + this.nextAt.set(out.quota.credential, Math.max(this.nextAt.get(out.quota.credential) ?? 0, now + this.gap(out.quota.credential, now))); + } + if (out.throttled && i.attempt < this.o.maxAttempts) { + const exp = Math.min(this.o.backoffMaxMs, this.o.backoffBaseMs * 2 ** (i.attempt - 1)); + const delay = Math.round(exp / 2 + this.clock.random() * exp / 2); // "equal jitter" + i.notBefore = now + delay; + for (const c of i.task.credentials) this.nextAt.set(c, Math.max(this.nextAt.get(c) ?? 0, now + delay)); + this.queue.push(i); + } else { + this.done++; + if (!ok || out.throttled) this.failed++; + if (ok) i.resolve(result); else i.reject(error); + } + if (!this.queue.length && !this.running.size) { this.done = 0; this.failed = 0; } + this.pump(); + this.emit(); + } + + private emit(): void { for (const f of this.listeners) { try { f(); } catch { /* listeners never break the queue */ } } } +} diff --git a/apps/desktop/src/screens/Portfolio.tsx b/apps/desktop/src/screens/Portfolio.tsx index 1048b5c..91dc8d1 100644 --- a/apps/desktop/src/screens/Portfolio.tsx +++ b/apps/desktop/src/screens/Portfolio.tsx @@ -225,6 +225,7 @@ export function Portfolio() { ); }; + const notRead = d.portfolioBusy === 'live' ? t('read.waiting') : t('kpi.notRead'); return (
@@ -240,13 +241,13 @@ export function Portfolio() { {d.portfolioError && {d.portfolioError}} {neverImported > 0 && d.importApps()} disabled={d.importBusy}>{t('action.importApps')}}>{t('portfolio.notImported', { count: neverImported })}} - {!known && d.ready && d.refreshPortfolio(true)}>{t('action.readStores')}}>{t('portfolio.notReadNotice')}} + {!known && d.ready && d.portfolioBusy !== 'live' && d.refreshPortfolio(true)}>{t('action.readStores')}}>{t('portfolio.notReadNotice')}}
- - r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} /> - `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} /> + + r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} /> + `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} />
diff --git a/apps/desktop/src/screens/Settings.tsx b/apps/desktop/src/screens/Settings.tsx index a93177b..96ded11 100644 --- a/apps/desktop/src/screens/Settings.tsx +++ b/apps/desktop/src/screens/Settings.tsx @@ -122,11 +122,11 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
-
{t('set.autoRefresh')} - set(x => ({ ...x, refresh: { ...x.refresh, autoMinutes: Number(v) as S['refresh']['autoMinutes'] } }))} - options={[['0', t('set.off')], ['15', t('set.min', { n: 15 })], ['30', t('set.min', { n: 30 })], ['60', t('set.hour', { n: 1 })], ['180', t('set.hour', { n: 3 })], ['720', t('set.hour', { n: 12 })]]} /> - {t('set.autoHint')}
- set(x => ({ ...x, refresh: { ...x.refresh, onLaunch: v } }))} /> + set(x => ({ ...x, refresh: { ...x.refresh, autoRead: v } }))} /> +
{t('set.everyMinutes')} + set(x => ({ ...x, refresh: { ...x.refresh, everyMinutes: Number(v) as S['refresh']['everyMinutes'] } }))} + options={[['0', t('set.onlyOnStart')], ['5', t('set.min', { n: 5 })], ['15', t('set.min', { n: 15 })], ['30', t('set.min', { n: 30 })], ['60', t('set.hour', { n: 1 })]]} /> + {t('set.everyHint')}
set(x => ({ ...x, refresh: { ...x.refresh, icons: v } }))} />
{t('set.parallelHint')}
- + {d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')}
diff --git a/apps/desktop/src/screens/tabs/Catalog.tsx b/apps/desktop/src/screens/tabs/Catalog.tsx index 1eb33cc..7dedd9d 100644 --- a/apps/desktop/src/screens/tabs/Catalog.tsx +++ b/apps/desktop/src/screens/tabs/Catalog.tsx @@ -8,7 +8,7 @@ import { useData, useRead, useWrite } from '../../store'; import { Icon, type IconName, StoreGlyph } from '../../ui/icons'; import { OwnerAction } from '../../ui/OwnerAction'; import { WriteButton } from '../../ui/WriteButton'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Skeleton } from '../../ui/kit'; +import { Card, Chip, Empty, ErrorNotice, Kpi, ReadControl, Skeleton } from '../../ui/kit'; import { catalogMd, exportName } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; import { useNav } from '../../nav'; @@ -87,13 +87,13 @@ export function CatalogTab({ project }: { project: Project }) {
- r.kind !== 'extra').length}` : '–'} sub={read ? t('cat.parityRead', { when: ago(diff.at) }) : t('kpi.notRead')} tone={read && inParity < rows.length ? 'warn' : undefined} /> - + r.kind !== 'extra').length}` : '–'} sub={read ? t('cat.parityRead', { when: ago(diff.at) }) : diff.loading ? t('read.waiting') : t('kpi.notRead')} tone={read && inParity < rows.length ? 'warn' : undefined} /> +
{diff.error && } { diff.refresh(); }} /> {read ? t('action.refresh') : t('cat.compare')}}> + actions={}>
diff --git a/apps/desktop/src/screens/tabs/Checks.tsx b/apps/desktop/src/screens/tabs/Checks.tsx index 5e0dde6..32dc2a4 100644 --- a/apps/desktop/src/screens/tabs/Checks.tsx +++ b/apps/desktop/src/screens/tabs/Checks.tsx @@ -6,7 +6,7 @@ import { ago } from '../../lib/format'; import type { Finding, ScanResult, ScanSeverity, ValidateResult } from '../../lib/model'; import { useData, useRead } from '../../store'; import { Icon } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Skeleton } from '../../ui/kit'; +import { Card, Chip, Empty, ErrorNotice, ReadControl, Skeleton } from '../../ui/kit'; import { exportName, validateMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; @@ -22,7 +22,7 @@ function ScanCard({ project }: { project: Project }) { const asks = (Array.isArray(s.data?.declarations?.items) ? s.data!.declarations.items : []).filter(x => x.status === 'ask').length; return ( x.name).join(', ') }) : t('checks.scanSub')} pad={false} - actions={}> + actions={}> {s.error &&
} {!s.data ? (s.loading && !s.error ?
: null) : !findings.length ? {t('checks.scanCleanText')} : ( @@ -80,7 +80,7 @@ export function ChecksTab({ project }: { project: Project }) { )}
{v.data ? t('action.refresh') : t('checks.run')}}> + actions={}> {v.error &&
} {!v.data ? ( v.loading && !v.error ?
: {t('checks.validateEmptyText')} diff --git a/apps/desktop/src/screens/tabs/Growth.tsx b/apps/desktop/src/screens/tabs/Growth.tsx index cf40c5d..7849f96 100644 --- a/apps/desktop/src/screens/tabs/Growth.tsx +++ b/apps/desktop/src/screens/tabs/Growth.tsx @@ -14,7 +14,7 @@ import { useNav } from '../../nav'; import { useData, useRead, useWrite } from '../../store'; import { useExports } from '../../ui/Exports'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, Seg, Skeleton } from '../../ui/kit'; +import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, ReadControl, Seg, Skeleton } from '../../ui/kit'; import { LineChart } from '../../ui/LineChart'; import { RankChart } from '../../ui/RankChart'; import { WriteButton } from '../../ui/WriteButton'; @@ -107,7 +107,7 @@ function Aso({ projectId }: { projectId: string }) { })) : []; return ( {t('action.refresh')}}> + actions={}> {r.error ?
: !a ?
: (
@@ -167,7 +167,7 @@ function Experiments({ app }: { app: UnifiedApp }) { {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : t('gr.ppoSub')}} pad={false} actions={<> - + }> {r.error &&
} {!r.data ? (r.loading && !r.error ?
: {t('gr.ppoNotReadText')}) diff --git a/apps/desktop/src/screens/tabs/Health.tsx b/apps/desktop/src/screens/tabs/Health.tsx index d89aa2b..9986790 100644 --- a/apps/desktop/src/screens/tabs/Health.tsx +++ b/apps/desktop/src/screens/tabs/Health.tsx @@ -4,9 +4,13 @@ import type { UnifiedApp } from '../../lib/identity'; import { t } from '../../i18n'; import { ago, date, num, pct } from '../../lib/format'; import { type AppleHealth, healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type PlayHealth, type Series } from '../../lib/model'; -import { useRead } from '../../store'; +import { useState } from 'react'; +import { api } from '../../api'; +import { appleSignatureView, hintFor, type IssueView, issueMarkdown, playIssueView } from '../../lib/issues'; +import type { IssueSample } from '../../lib/model'; +import { useData, useRead } from '../../store'; import { Icon } from '../../ui/icons'; -import { Bar, Card, Chip, Empty, ErrorFoot, Notice, Skeleton, Sparkline } from '../../ui/kit'; +import { Bar, Card, Chip, Empty, ErrorFoot, ErrorNotice, Notice, ReadControl, Skeleton, Sparkline } from '../../ui/kit'; import { exportName, healthMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; import { StoreReadNotice } from '../../ui/StoreError'; @@ -33,7 +37,47 @@ function Metric({ title, s }: { title: string; s: Series }) { ); } -function Play({ h }: { h: PlayHealth }) { +/** One issue's detail: full title and type, counts, versions, last report, a sample stack (read and cached like the + * rest), "Open in Play Console" and "Copy for AI" (compact markdown for an agent). */ +function IssueDetail({ app, v }: { app: UnifiedApp; v: IssueView }) { + const d = useData(); + const s = useRead<{ sample: IssueSample | null }>(app.target, 'health.issue', { network: true, args: v.sampleArgs ?? {}, skip: !v.sampleArgs }); + const sample = s.data?.sample ?? null; + const copy = () => { + navigator.clipboard?.writeText(issueMarkdown(app.name, v, sample)).then(() => d.toast({ kind: 'ok', title: t('health.copied') }), () => d.toast({ kind: 'bad', title: t('health.copyFailed') })); + }; + const range = (a?: string, b?: string) => (a && b && a !== b ? `${a} – ${b}` : a ?? b ?? '–'); + return ( +
+
{v.title}
+
+
{t('health.issueType')}
{v.kind}
+ {v.where && v.where !== v.title && <>
{t('health.issueWhere')}
{v.where}
} + {v.reports !== undefined && <>
{t('col.reports')}
{num(v.reports)}{v.users !== undefined ? ` · ${t('col.users')} ${num(v.users)}` : ''}
} + {v.weight !== undefined && <>
{t('health.issueShare')}
{num(v.weight * 100, 1)}%
} + {(v.versions?.first || v.versions?.last) && <>
{t('health.issueVersions')}
{range(v.versions.first, v.versions.last)}
} + {v.build && <>
{t('health.issueBuild')}
{v.build}
} + {v.os && <>
{t('health.issueOs')}
{range(v.os.first, v.os.last)}
} + {v.lastSeen && <>
{t('health.issueLastSeen')}
{ago(v.lastSeen)}
} +
+ {(() => { const h = hintFor(v, sample); return h ?
{t('health.likelyCause')} {h.cause}{t('health.suggestedFix')} {h.fix}
: null; })()} + {v.sampleArgs && ( +
+
{t('health.sample')}{sample ? ` · ${[sample.version, sample.device, sample.os].filter(Boolean).join(' · ')}` : ''}
+ {sample ?
{sample.stack.join('\n')}
+ : s.loading ? : !s.error ?

{t('health.noSample')}

: null} +
+ )} +
+ + {v.url && } +
+
+ ); +} + +function Play({ h, app }: { h: PlayHealth; app: UnifiedApp }) { + const [open, setOpen] = useState(null); const crash = healthSeries(h.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash); const anr = healthSeries(h.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr); const devices = (h.devices ?? []).slice(0, 6); @@ -67,11 +111,11 @@ function Play({ h }: { h: PlayHealth }) {
{h.issues.slice(0, 6).map((i, n) => ( - - - - + setOpen(open === n ? null : n)} cols={3} + head={<>
{i.type === 'ANR' ? 'ANR' : t('health.crashShort')}{i.cause || '?'}
+
{i.location}
} + cells={<>
} + detail={} /> ))}
{t('col.item')}{t('col.type')}{t('col.config')}App StoreGoogle Play{t('col.priceGap')}
{t('col.issue')}{t('col.reports')}{t('col.users')}
{i.type === 'ANR' ? 'ANR' : t('health.crashShort')}{i.cause || '?'}
-
{i.location}
{num(i.reports)}{num(i.users)}
{num(i.reports)}{num(i.users)}
@@ -82,7 +126,21 @@ function Play({ h }: { h: PlayHealth }) { ); } -function Apple({ h }: { h: AppleHealth }) { +/** A table row that opens its detail row below it (click or Enter / Space). */ +function IssueRows({ open, onToggle, head, cells, detail, cols }: { open: boolean; onToggle: () => void; head: React.ReactNode; cells: React.ReactNode; detail: React.ReactNode; cols: number }) { + return ( + <> + { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggle(); } }} tabIndex={0} aria-expanded={open} role="button"> +
{head}
+ {cells} + + {open && {detail}} + + ); +} + +function Apple({ h, app }: { h: AppleHealth; app: UnifiedApp }) { + const [open, setOpen] = useState(null); const maxCrash = Math.max(1, ...h.betaCrashes.map(b => b.count)); return (
@@ -102,15 +160,16 @@ function Apple({ h }: { h: AppleHealth }) {
{h.signatures.length ? ( -
- {h.signatures.slice(0, 5).map((s, i) => ( -
- -
{s.signature || s.type}{s.type} · {t('health.build', { build: s.build })}
- {num(s.weight * 100, 1)}% -
- ))} -
+ + + {h.signatures.slice(0, 5).map((s, i) => ( + setOpen(open === i ? null : i)} cols={2} + head={<>
{s.signature || s.type}
{s.type} · {t('health.build', { build: s.build })}
} + cells={
} + detail={} /> + ))} + +
{num(s.weight * 100, 1)}%
) : }
@@ -128,7 +187,6 @@ function Apple({ h }: { h: AppleHealth }) { export function HealthTab({ app }: { app: UnifiedApp }) { const r = useRead(app.target, 'health', { network: true, title: t('tab.health'), appName: app.name }); useExports('health', [{ id: 'health-md', label: t('export.health'), icon: 'activity', kind: 'md', file: exportName(app.name, 'health'), disabled: r.data ? false : t('export.readFirst'), build: () => healthMd(app.name, r.data!) }]); - const refresh = ; if (!r.data) { if (r.loading && !r.error) return ; return ( @@ -142,14 +200,13 @@ export function HealthTab({ app }: { app: UnifiedApp }) { return ( <>
- {r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })} - {refresh} + +
- {r.error && {t('common.readFailedKeep', { error: r.error })}}

Google Play

- {h.play === undefined ? {t('health.noPlay')} : isError(h.play) ? : } + {h.play === undefined ? {t('health.noPlay')} : isError(h.play) ? : <>{h.play.issuesError && }}

App Store

- {h.apple === undefined ? {t('health.noApple')} : isError(h.apple) ? : } + {h.apple === undefined ? {t('health.noApple')} : isError(h.apple) ? : } ); } diff --git a/apps/desktop/src/screens/tabs/Prices.tsx b/apps/desktop/src/screens/tabs/Prices.tsx index aa0496e..4f51cb1 100644 --- a/apps/desktop/src/screens/tabs/Prices.tsx +++ b/apps/desktop/src/screens/tabs/Prices.tsx @@ -10,7 +10,7 @@ import { changePct, diffSummary, priceMatrix, priceStats, type RegionRow, region import { type ReadState, useData, useRead, useWrite } from '../../store'; import { type ExportItem, useExports, useRunExport } from '../../ui/Exports'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, Skeleton } from '../../ui/kit'; +import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, ReadControl, Skeleton } from '../../ui/kit'; import { WriteButton } from '../../ui/WriteButton'; const GAP = 10; @@ -158,7 +158,7 @@ export function PricesTab({ project }: { project: Project }) { - + }>
diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index 0fcc87a..a480227 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -13,7 +13,7 @@ import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } import { useData, useRead, useWrite } from '../../store'; import { Icon, StoreGlyph } from '../../ui/icons'; import { RolloutBar } from '../../ui/charts'; -import { Card, Chip, Empty, Notice, PhaseChip, storeName } from '../../ui/kit'; +import { Card, Chip, Empty, Notice, PhaseChip, Skeleton, storeName } from '../../ui/kit'; import { AppleSubmitCard, PlayProductionCard } from './Submit'; const STAGE_KEY: Record<(typeof STAGES)[number], Key> = { build: 'stage.build', testing: 'stage.testing', review: 'stage.review', live: 'stage.live', rollout: 'stage.rollout' }; @@ -139,6 +139,7 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { ) : null; + if (!l && d.portfolioBusy === 'live') return <>{submit}; if (!l) { return ( <> diff --git a/apps/desktop/src/screens/tabs/Reviews.tsx b/apps/desktop/src/screens/tabs/Reviews.tsx index 0998440..95b5348 100644 --- a/apps/desktop/src/screens/tabs/Reviews.tsx +++ b/apps/desktop/src/screens/tabs/Reviews.tsx @@ -5,12 +5,12 @@ 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 { date, num } from '../../lib/format'; import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model'; import { useRead, useWrite } from '../../store'; import { WriteButton } from '../../ui/WriteButton'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Bar, Card, Chip, Empty, ErrorFoot, Notice, Seg, Skeleton, Stars } from '../../ui/kit'; +import { Bar, Card, Chip, Empty, ErrorFoot, ReadControl, Seg, Skeleton, Stars } from '../../ui/kit'; import { exportName, reviewsCsv } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; @@ -111,13 +111,11 @@ export function ReviewsTab({ app }: { app: UnifiedApp }) { return ( <>
- {list.fromCache ? t('common.cachedFrom', { when: ago(list.at) }) : t('common.readWhen', { when: ago(list.at) })} +
{project && {t('reviews.makeDrafts')}} -
- {list.error && {t('common.readFailedKeep', { error: list.error })}}
diff --git a/apps/desktop/src/screens/tabs/Submit.tsx b/apps/desktop/src/screens/tabs/Submit.tsx index e0243da..3486eb1 100644 --- a/apps/desktop/src/screens/tabs/Submit.tsx +++ b/apps/desktop/src/screens/tabs/Submit.tsx @@ -15,7 +15,7 @@ import type { UnifiedApp } from '../../lib/identity'; import { useData, useRead } from '../../store'; import { ConsolePlanButton } from '../../ui/ConsolePlan'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Notice, Seg, Skeleton } from '../../ui/kit'; +import { Card, Chip, Empty, ErrorNotice, Notice, ReadControl, Seg, Skeleton } from '../../ui/kit'; import { OwnerAction } from '../../ui/OwnerAction'; import { ascUrl, PLAY_CONSOLE } from '../AppView'; @@ -40,9 +40,9 @@ export function AppleSubmitCard({ app, project }: { app: UnifiedApp; project: Pr const args = { build, ...(version ? { version: version.version } : {}), ...(resolveIaps ? { resolve_iaps: true } : {}) }; const refresh = () => { r.refresh(); }; return ( - {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : t('sub.appleSub')}} + {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : r.loading ? t('read.waiting') : t('sub.appleSub')}} actions={<> - + refresh() }} label={t('sub.read')} /> }> {r.error && } @@ -142,9 +142,9 @@ export function PlayProductionCard({ app, project }: { app: UnifiedApp; project: const picked = s?.codes.find(c => c.code === code) ?? null; const args = { version_code: code, status, ...(status === 'inProgress' ? { percent: Number(share) } : {}) }; return ( - {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : t('sub.playSub')}} + {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : r.loading ? t('read.waiting') : t('sub.playSub')}} actions={<> - + }> {r.error && } diff --git a/apps/desktop/src/screens/tabs/TestFlight.tsx b/apps/desktop/src/screens/tabs/TestFlight.tsx index 2e28e90..52403de 100644 --- a/apps/desktop/src/screens/tabs/TestFlight.tsx +++ b/apps/desktop/src/screens/tabs/TestFlight.tsx @@ -4,11 +4,11 @@ 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 { date, num } from '../../lib/format'; 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'; +import { Card, Chip, Empty, Notice, ReadControl, Skeleton } from '../../ui/kit'; /** Beta state word -> tone and a short label. */ export function betaState(s: string | null): { tone: Tone; text: string } { @@ -96,10 +96,9 @@ export function TestFlightTab({ app }: { app: UnifiedApp }) { return ( <>
- {r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })} - + +
- {r.error && {t('common.readFailedKeep', { error: r.error })}} {s.missingGroups.length > 0 && ( {t('tf.groupsSync')} : undefined}> {t('tf.missingGroups', { groups: s.missingGroups.join(', ') })} diff --git a/apps/desktop/src/store.tsx b/apps/desktop/src/store.tsx index c1935a4..c51239f 100644 --- a/apps/desktop/src/store.tsx +++ b/apps/desktop/src/store.tsx @@ -13,6 +13,8 @@ import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify'; import { setCrashContext } from './lib/crash'; import { normalizeAccounts, normalizeProjects, normalizeWorkspace } from './lib/normalize'; import { keepLines, progressOf } from './lib/progress'; +import { isStale, lanesOf, looksThrottled, oneLine, readKey, readsFor } from './lib/freshness'; +import { type Outcome, type Priority, ReadScheduler, type ReadTask, type SchedulerStats } from './lib/scheduler'; import { fixHint } from './lib/views'; import { failureText, usable } from './lib/results'; @@ -32,6 +34,31 @@ export interface Toast { export interface AccountHealth { check?: AccountCheck; error?: string; at: string } +/** What the read bus tells the cards showing one read (key: lib/freshness.ts readKey). */ +export type ReadEvent = { kind: 'start' } | { kind: 'done'; result: ToolResult } | { kind: 'error'; error: string } | { kind: 'invalidate' }; + +/** The background reader's state for the status line. */ +export interface ReaderState extends SchedulerStats { autoRead: boolean } + +/** Throttling and App Store Connect quota of one finished read (the ToolResult's `quota`, else its text). */ +export function classifyRead(result: unknown, error: unknown, task: ReadTask): Outcome { + const r = result as ToolResult | undefined; + const q = r?.quota; + const out: Outcome = {}; + if (q?.store === 'apple' && typeof q.limit === 'number' && typeof q.remaining === 'number') + out.quota = { credential: task.credentials.find(c => c.startsWith('apple:')) ?? 'apple:default', limit: q.limit, remaining: q.remaining }; + if (r && !r.ok && (q?.throttled || looksThrottled(r.output))) out.throttled = true; + if (error !== undefined && looksThrottled(errorText(error))) out.throttled = true; + return out; +} + +/** Which stores an app has (for the reads it gets and the lanes they take). */ +export function platformsOf(a: UnifiedApp | undefined, status?: AppStatus): { ios: boolean; android: boolean } { + if (!a) return { ios: false, android: false }; + const pl = status?.app?.platforms as { ios?: unknown; android?: unknown } | undefined; + return { ios: !!a.ios || !!pl?.ios || (!!a.project?.appleAccount && !pl), android: !!a.android || !!pl?.android || (!!a.project?.playAccount && !pl) }; +} + export interface Data { ready: boolean; info: AppInfo | null; @@ -56,7 +83,20 @@ export interface Data { portfolioError: string | null; importBusy: boolean; icons: Record; - refreshPortfolio: (live?: boolean) => Promise; + /** Background reader: progress and the App Store Connect quota seen this hour. */ + reader: ReaderState; + /** Runs one read through the scheduler (deduped, rate limited); the result also goes to the read bus. */ + schedule: (target: string, method: string, args: Record, priority: Priority) => Promise; + /** Listens to one read's bus key. */ + onRead: (key: string, fn: (e: ReadEvent) => void) => () => void; + isReading: (key: string) => boolean; + /** Reads everything of every app that is past its TTL (force: everything). */ + readAll: (force?: boolean) => Promise; + /** After a write: the app's reads are read again. */ + invalidate: (target: string) => void; + /** The app on screen (its reads go first). */ + setFocus: (key: string | null) => void; + refreshPortfolio: (live?: boolean, quiet?: boolean) => Promise; /** Reads the apps of one account (or all) from the stores. */ importApps: (account?: string) => Promise; checkAccount: (id: string) => Promise; @@ -155,10 +195,10 @@ export function DataProvider({ children }: { children: ReactNode }) { const appsRef = useRef(apps); appsRef.current = apps; - const refreshPortfolio = useCallback(async (liveRead = false) => { + const refreshPortfolio = useCallback(async (liveRead = false, quiet = false) => { const job = newJob(liveRead ? 'portfolio-live' : 'portfolio'); setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null); - const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; + const tid = liveRead && !quiet ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; try { const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : []; const r = await api.portfolio(liveRead, job, stores); @@ -179,6 +219,78 @@ export function DataProvider({ children }: { children: ReactNode }) { } finally { setBusy(null); } }, [toast, updateToast]); + // ---- background reader: one scheduler for every store read of the window (lib/scheduler.ts) ---- + const schedRef = useRef(null); + if (!schedRef.current) schedRef.current = new ReadScheduler({ classify: classifyRead, limits: { apple: settings.refresh.parallel, play: settings.refresh.parallel } }); + const sched = schedRef.current; + const [reader, setReader] = useState(() => sched.stats()); + useEffect(() => { + let tm: ReturnType | null = null; + const un = sched.subscribe(() => { if (!tm) tm = setTimeout(() => { tm = null; setReader(sched.stats()); }, 150); }); + return () => { un(); if (tm) clearTimeout(tm); }; + }, [sched]); + useEffect(() => { sched.setLimits({ apple: settings.refresh.parallel, play: settings.refresh.parallel }); }, [sched, settings.refresh.parallel]); + const bus = useRef(new Map void>>()); + const emitRead = useCallback((key: string, e: ReadEvent) => { for (const f of bus.current.get(key) ?? []) { try { f(e); } catch { /* a card's listener never breaks the bus */ } } }, []); + const onRead = useCallback((key: string, fn: (e: ReadEvent) => void) => { + const set = bus.current.get(key) ?? new Set(); + set.add(fn); bus.current.set(key, set); + return () => { set.delete(fn); if (!set.size) bus.current.delete(key); }; + }, []); + const isReading = useCallback((key: string) => sched.has(key), [sched]); + const focusRef = useRef(null); + const setFocus = useCallback((key: string | null) => { focusRef.current = key; }, []); + + const credentialsOf = (a: UnifiedApp | undefined, lanes: string[]): string[] => { + const c: string[] = []; + if (lanes.includes('apple')) c.push(`apple:${a?.project?.appleAccount ?? a?.ios?.account ?? 'default'}`); + if (lanes.includes('play')) c.push(`play:${a?.project?.playAccount ?? a?.android?.account ?? 'default'}`); + return c; + }; + const statusRef = useRef<(a: UnifiedApp) => AppStatus | undefined>(() => undefined); + + const schedule = useCallback((target: string, method: string, args: Record, priority: Priority): Promise => { + const key = readKey(target, method, args); + const app = appsRef.current.find(a => a.target === target); + const pf = platformsOf(app, app ? statusRef.current(app) : undefined); + const lanes = lanesOf(method, pf); + const p = sched.enqueue({ key, lanes, credentials: credentialsOf(app, lanes), priority, run: () => api.call(method, target, { args }, newJob(method)) }); + emitRead(key, { kind: 'start' }); + p.then(result => emitRead(key, { kind: 'done', result }), e => emitRead(key, { kind: 'error', error: errorText(e) })); + return p; + }, [sched, emitRead]); + + const readAll = useCallback(async (force = false) => { + if (!force && !settingsRef.current.refresh.autoRead) return; + if (force || isStale('portfolio.status', liveRef.current?.at)) { + sched.enqueue({ key: '*\u001fportfolio.status', lanes: ['apple', 'play'], credentials: [], priority: 1, run: () => refreshPortfolio(true, true) }).catch(() => {}); + } + const list = [...appsRef.current].filter(a => !a.ignored && !a.project?.missing) + .sort((a, b) => Number(b.key === focusRef.current) - Number(a.key === focusRef.current)); + for (const a of list) { + const pf = platformsOf(a, statusRef.current(a)); + for (const r of readsFor({ folder: !!a.project, ...pf })) { + const key = readKey(a.target, r.method, r.args); + if (sched.has(key)) continue; + if (!force) { + const c = await api.cached(r.method, a.target, r.args).catch(() => null); + if (c && !isStale(r.method, c.at)) continue; + } + schedule(a.target, r.method, r.args, a.key === focusRef.current ? 0 : 2).catch(() => {}); + } + } + }, [sched, schedule, refreshPortfolio]); + + const invalidate = useCallback((target: string) => { + const pre = `${target}\u001f`; + for (const k of [...bus.current.keys()]) if (k.startsWith(pre)) emitRead(k, { kind: 'invalidate' }); + const a = appsRef.current.find(x => x.target === target); + if (a) for (const r of readsFor({ folder: !!a.project, ...platformsOf(a, statusRef.current(a)) })) { + const key = readKey(target, r.method, r.args); + if (!bus.current.has(key)) schedule(target, r.method, r.args, 1).catch(() => {}); + } + }, [emitRead, schedule]); + const importApps = useCallback(async (account?: string) => { const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`)); if (!ids.length) return; @@ -236,21 +348,27 @@ export function DataProvider({ children }: { children: ReactNode }) { useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]); - // Settings > Refresh: on launch, then every N minutes (store reads use the accounts' API quota: off by default) + // Settings > Reading: everything past its TTL is read in the background on start, when the window shows again after + // a while, and every N minutes while it is visible (the scheduler keeps it inside the stores' limits). const launched = useRef(false); useEffect(() => { - if (!ready || launched.current) return; + if (!ready || launched.current || !apps.length) return; launched.current = true; - if (settings.refresh.onLaunch && (projects.length || accounts.length)) importApps().finally(() => refreshPortfolio(true)); - }, [ready, settings.refresh.onLaunch, projects.length, accounts.length, importApps, refreshPortfolio]); - const busyRef = useRef(portfolioBusy); - busyRef.current = portfolioBusy; + if (settings.refresh.autoRead) readAll(false).catch(() => {}); + }, [ready, apps.length, settings.refresh.autoRead, readAll]); useEffect(() => { - const m = settings.refresh.autoMinutes; - if (!m) return; - const tm = setInterval(() => { if (!busyRef.current) refreshPortfolio(true); }, m * 60_000); - return () => clearInterval(tm); - }, [settings.refresh.autoMinutes, refreshPortfolio]); + if (!settings.refresh.autoRead) return; + let hiddenAt = 0; + const vis = () => { + if (document.hidden) { hiddenAt = Date.now(); return; } + if (hiddenAt && Date.now() - hiddenAt > 60_000) readAll(false).catch(() => {}); + hiddenAt = 0; + }; + document.addEventListener('visibilitychange', vis); + const m = settings.refresh.everyMinutes; + const tm = m ? setInterval(() => { if (!document.hidden) readAll(false).catch(() => {}); }, m * 60_000) : null; + return () => { document.removeEventListener('visibilitychange', vis); if (tm) clearInterval(tm); }; + }, [settings.refresh.autoRead, settings.refresh.everyMinutes, readAll]); // icons: cached first, then read (offline, cheap) useEffect(() => { @@ -296,12 +414,15 @@ export function DataProvider({ children }: { children: ReactNode }) { const liveFor = useCallback((a: UnifiedApp) => (a.project ? liveOf(a.project) : portfolio?.apps.find(x => x.project === a.target && x.release.source === 'live') ?? live?.value.apps.find(x => x.project === a.target)), [liveOf, portfolio, live]); const iconFor = useCallback((a: UnifiedApp) => (a.project ? icons[a.project.id] ?? a.storeIcon : a.storeIcon), [icons]); const appByKey = useCallback((key: string) => apps.find(a => a.key === key), [apps]); + statusRef.current = statusFor; + const readerState = useMemo(() => ({ ...reader, autoRead: settings.refresh.autoRead }), [reader, settings.refresh.autoRead]); const value = useMemo(() => ({ ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, - importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, + importBusy, icons, reader: readerState, schedule, onRead, isReading, readAll, invalidate, setFocus, + refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, toasts, toast, updateToast, dismiss, cancelJob, - }), [ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, + }), [readerState, schedule, onRead, isReading, readAll, invalidate, setFocus, ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, toasts, toast, updateToast, dismiss, cancelJob]); return {children}; @@ -309,6 +430,8 @@ export function DataProvider({ children }: { children: ReactNode }) { export interface ReadState { data: T | null; + /** Past its TTL (lib/freshness.ts): a refresh is due or running. */ + stale?: boolean; /** When `data` was read (from the store or the cache). */ at: string | null; fromCache: boolean; @@ -339,7 +462,7 @@ export function useWrite(projectId: string | null) { 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: withHint(failureText(o.dryRun)), 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 if (o.result?.ok) { d.updateToast(tid, { kind: 'ok', title: w.done, detail: lastLine(o.result.output) || undefined, progress: undefined, job: undefined }); w.after?.(); d.invalidate(projectId); } // exit 3: the command stopped for an owner decision it did not get (a price change of a live product: the // Catalog tab's owner action applies it); everything else it could do was done else if (o.result?.exitCode === 3) { d.updateToast(tid, { kind: 'info', title: t('write.declined'), detail: lastLine(o.result.output) || undefined, progress: undefined, job: undefined }); w.after?.(); } @@ -369,52 +492,63 @@ function notifyAfterRead(method: string, prev: unknown, next: unknown, settings: /** * One read method of one app (a project id, or a store-only app's store target). The cached value shows at once with - * its time; offline reads (`network: false`) then refresh by themselves, store reads only on demand (they use the - * account's API quota). A failed read keeps the last good value and says so: never an empty "all fine". + * its time; then, past its TTL (lib/freshness.ts), it is read again through the background scheduler (offline reads + * always; store reads while Settings > Reading > auto-read is on). A read the background reader runs for this key + * lands here too (the read bus). A failed read keeps the last good value and says so: never an empty "all fine". */ export function useRead(target: string, method: string, o: { network: boolean; args?: Record; title?: string; appName?: string; skip?: boolean }): ReadState { const d = useData(); const argsKey = JSON.stringify(o.args ?? {}); + const key = readKey(target, method, JSON.parse(argsKey) as Record); const [s, set] = useState, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); - const seq = useRef(0); const dataRef = useRef(null); dataRef.current = s.data; + const dRef = useRef(d); + dRef.current = d; + const skipRef = useRef(o.skip); + skipRef.current = o.skip; const refresh = useCallback(async () => { - const my = ++seq.current; - const job = newJob(method); - set(x => ({ ...x, loading: true, error: null })); - const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null; - try { - const r = await api.call(method, target, { args: JSON.parse(argsKey) as Record }, job); - if (my !== seq.current) return; - if (usable(method, r)) { - notifyAfterRead(method, dataRef.current, r.data, d.settings, o.appName); - set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command }); - if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined }); - } else { - const msg = failureText(r); - set(x => ({ ...x, loading: false, error: msg, command: r.command })); - if (tid) d.updateToast(tid, { kind: 'bad', title: t('toast.readFailedWhat', { what: o.title ?? method }), detail: withHint(msg), progress: undefined, job: undefined }); + if (skipRef.current) return; + set(x => ({ ...x, loading: true })); + await dRef.current.schedule(target, method, JSON.parse(argsKey) as Record, 0).catch(() => {}); + }, [target, method, argsKey]); + + // results of this key, whoever asked for them (this card, the background reader, a write's invalidation) + useEffect(() => { + if (o.skip) return; + return d.onRead(key, e => { + if (e.kind === 'start') set(x => ({ ...x, loading: true })); + else if (e.kind === 'invalidate') { set(x => ({ ...x, stale: true })); refresh(); } + else if (e.kind === 'error') { if (/cancel/i.test(e.error)) set(x => ({ ...x, loading: false })); else set(x => ({ ...x, loading: false, error: oneLine(e.error) })); } + else { + const r = e.result; + if (usable(method, r)) { + notifyAfterRead(method, dataRef.current, r.data, dRef.current.settings, o.appName); + set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, stale: false, error: null, command: r.command }); + } else set(x => ({ ...x, loading: false, error: oneLine(failureText(r)), command: r.command })); } - } catch (e) { - if (my !== seq.current) return; - const msg = errorText(e); - set(x => ({ ...x, loading: false, error: msg })); - if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined }); - } - }, [target, method, argsKey, o.network, o.title, o.appName, d.settings]); // eslint-disable-line react-hooks/exhaustive-deps + }); + }, [key, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { let alive = true; if (o.skip) { set({ data: null, at: null, fromCache: false, loading: false, error: null, command: null }); return; } + const auto = !o.network || dRef.current.settings.refresh.autoRead; + const running = dRef.current.isReading(key); set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); + const go = (at: string | null) => { + if (!alive) return; + const due = !o.network || isStale(method, at); + if (running) set(x => ({ ...x, loading: true })); + else if (auto && due) refresh(); + else set(x => ({ ...x, loading: false })); + }; api.cached(method, target, JSON.parse(argsKey) as Record).then(c => { if (!alive) return; - if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command }); - else set(x => ({ ...x, loading: !o.network })); - if (!o.network) refresh(); - }, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } }); + if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: true, stale: isStale(method, c.at), error: null, command: c.value.command }); + go(c && c.value.data !== undefined ? c.at : null); + }, () => go(null)); return () => { alive = false; }; }, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index 5a83d17..8685ddd 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -169,6 +169,11 @@ svg { flex: none; } .topbar .spacer { flex: 1; } .stamp { display: inline-flex; align-items: center; gap: 6px; font-size: var(--t-meta); color: var(--muted); white-space: nowrap; } .stamp svg { width: 13px; height: 13px; } +.read-ctl { display: inline-flex; align-items: center; gap: 8px; min-width: 0; } +.read-stamp { font-size: var(--t-meta); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 360px; } +.read-stamp.read-err { color: var(--warn-ink); } +.reader-line { display: flex; align-items: center; gap: 6px; font-size: var(--t-meta); color: var(--muted); min-width: 0; } +.reader-line > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .dev-pill { font: 700 10px/1 var(--mono); letter-spacing: .06em; color: var(--warn-ink); background: var(--warn-bg); border: 1px solid color-mix(in srgb, var(--warn-solid) 45%, transparent); padding: 5px 7px; border-radius: 5px; } .content { flex: 1; overflow: auto; min-height: 0; scroll-behavior: smooth; } .page { padding: 24px 28px 48px; max-width: 1360px; margin: 0 auto; display: grid; gap: 20px; } @@ -794,6 +799,14 @@ h2[tabindex="-1"]:focus, h2[tabindex="-1"]:focus-visible { outline: none; } .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); } +.issue-row { cursor: pointer; } +.issue-row:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.issue-row .chev { flex: none; color: var(--muted); transition: transform var(--speed) var(--ease); } +.issue-row .chev.rot { transform: rotate(90deg); } +.ellipsis { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.issue-detail { display: grid; gap: 12px; padding: 4px 0; min-width: 0; } +.issue-title { overflow-wrap: anywhere; } +.stack-trace { margin: 0; max-height: 280px; overflow: auto; padding: 10px 12px; border-radius: 8px; background: var(--surface); border: 1px solid var(--line, var(--border)); font: 12px/1.5 var(--mono, ui-monospace, monospace); white-space: pre; } .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; } diff --git a/apps/desktop/src/ui/kit.tsx b/apps/desktop/src/ui/kit.tsx index 0e3283d..f65ea4e 100644 --- a/apps/desktop/src/ui/kit.tsx +++ b/apps/desktop/src/ui/kit.tsx @@ -4,7 +4,7 @@ import { StarIcon } from '@phosphor-icons/react/dist/csr/Star'; import type { ReactNode } from 'react'; import type { ReleasePhase, StoreRelease } from '../api'; import { t } from '../i18n'; -import { share } from '../lib/format'; +import { ago, share } from '../lib/format'; import { hueOf, monogram, type Tone } from '../lib/model'; import { fixHint } from '../lib/views'; import { Icon, type IconName, StoreGlyph } from './icons'; @@ -173,3 +173,17 @@ export function StudioMark({ studio, size = 'md' }: { studio: { name: string; co export function StoreOnlyTag() { return {t('apps.storeOnly')}; } + +/** The state of one read beside its card's title: "read 3 min ago" with a small spinner while it refreshes, or + * "couldn't refresh: " over the last good value, and the per-card refresh icon (no "Read" button first). */ +export function ReadControl({ r, label }: { r: { data: unknown; at: string | null; loading: boolean; error: string | null; refresh: () => Promise }; label?: string }) { + const text = r.error ? t('read.couldNotRefresh', { reason: r.error }) : r.at ? t('read.ago', { when: ago(r.at) }) : r.loading ? t('read.waiting') : ''; + return ( + + {text && {text}} + + + ); +} diff --git a/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json b/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json index 798b8e9..fc2b8b4 100644 --- a/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json +++ b/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json @@ -39,6 +39,8 @@ }, "refresh": { "autoMinutes": 0, + "autoRead": true, + "everyMinutes": 15, "icons": true, "onLaunch": false, "parallel": 4 diff --git a/apps/desktop/tests/fixtures/state/d3-full.host.json b/apps/desktop/tests/fixtures/state/d3-full.host.json index 65fe250..42fd2c9 100644 --- a/apps/desktop/tests/fixtures/state/d3-full.host.json +++ b/apps/desktop/tests/fixtures/state/d3-full.host.json @@ -84,6 +84,8 @@ }, "refresh": { "autoMinutes": 0, + "autoRead": true, + "everyMinutes": 15, "icons": true, "onLaunch": false, "parallel": 4 diff --git a/apps/desktop/tests/fixtures/state/empty.host.json b/apps/desktop/tests/fixtures/state/empty.host.json index f1c3a55..cfb10be 100644 --- a/apps/desktop/tests/fixtures/state/empty.host.json +++ b/apps/desktop/tests/fixtures/state/empty.host.json @@ -22,6 +22,8 @@ }, "refresh": { "autoMinutes": 0, + "autoRead": true, + "everyMinutes": 15, "icons": true, "onLaunch": false, "parallel": 4 diff --git a/apps/desktop/tests/fixtures/state/shared-profiles.host.json b/apps/desktop/tests/fixtures/state/shared-profiles.host.json index 23b62fe..38ac38f 100644 --- a/apps/desktop/tests/fixtures/state/shared-profiles.host.json +++ b/apps/desktop/tests/fixtures/state/shared-profiles.host.json @@ -81,6 +81,8 @@ }, "refresh": { "autoMinutes": 0, + "autoRead": true, + "everyMinutes": 15, "icons": true, "onLaunch": false, "parallel": 4 diff --git a/apps/desktop/tests/scheduler.test.ts b/apps/desktop/tests/scheduler.test.ts new file mode 100644 index 0000000..b2ba8d1 --- /dev/null +++ b/apps/desktop/tests/scheduler.test.ts @@ -0,0 +1,257 @@ +// The background read scheduler (src/lib/scheduler.ts) with a fake clock: concurrency per lane, priority, dedupe, +// spacing per credential, backoff with jitter on 429, slowing down and pausing on App Store Connect's quota header; +// and the TTLs / plan of src/lib/freshness.ts, the "Copy for AI" markdown of src/lib/issues.ts. +import { describe, expect, test } from 'bun:test'; +import { isStale, lanesOf, looksThrottled, oneLine, readKey, readsFor, ttlOf } from '../src/lib/freshness'; +import { appleSignatureView, issueMarkdown, playIssueView } from '../src/lib/issues'; +import { type Clock, type Outcome, ReadScheduler, type ReadTask } from '../src/lib/scheduler'; + +class FakeClock implements Clock { + t = 0; + private timers: { at: number; fn: () => void; id: number }[] = []; + private n = 0; + rand = 0.5; + now() { return this.t; } + setTimeout(fn: () => void, ms: number) { const id = ++this.n; this.timers.push({ at: this.t + ms, fn, id }); return id; } + clearTimeout(h: unknown) { this.timers = this.timers.filter(x => x.id !== h); } + random() { return this.rand; } + /** Moves time forward, firing due timers in order (and letting promise callbacks run in between). */ + async advance(ms: number) { + const end = this.t + ms; + for (;;) { + await flush(); + const next = this.timers.filter(x => x.at <= end).sort((a, b) => a.at - b.at)[0]; + if (!next) break; + this.t = next.at; + this.timers = this.timers.filter(x => x !== next); + next.fn(); + } + this.t = end; + await flush(); + } +} +const flush = async () => { for (let i = 0; i < 10; i++) await Promise.resolve(); }; + +/** A task whose run resolves when the test says so. */ +function controlled() { + const runs: { key: string; done: (v: unknown) => void; fail: (e: unknown) => void }[] = []; + const task = (key: string, o: Partial> = {}): ReadTask => ({ + key, lanes: ['apple'], credentials: ['apple:k1'], priority: 2, ...o, + run: () => new Promise((done, fail) => { runs.push({ key, done, fail }); }), + }); + return { runs, task }; +} + +describe('ReadScheduler', () => { + test('at most N at once per lane, the rest wait for a slot', async () => { + const clock = new FakeClock(); + const s = new ReadScheduler({ clock, spacingMs: 0, limits: { apple: 2, play: 1 } }); + const { runs, task } = controlled(); + for (const k of ['a', 'b', 'c', 'd']) s.enqueue(task(k)).catch(() => {}); + s.enqueue(task('p1', { lanes: ['play'], credentials: ['play:k'] })).catch(() => {}); + s.enqueue(task('p2', { lanes: ['play'], credentials: ['play:k'] })).catch(() => {}); + await clock.advance(0); + expect(runs.map(r => r.key)).toEqual(['a', 'b', 'p1']); + expect(s.stats()).toMatchObject({ running: 3, queued: 3, total: 6 }); + runs[0]!.done(1); + await clock.advance(0); + expect(runs.map(r => r.key)).toEqual(['a', 'b', 'p1', 'c']); + // a task in both lanes needs a slot in each + const both = new ReadScheduler({ clock, spacingMs: 0, limits: { apple: 1, play: 1 } }); + const c2 = controlled(); + both.enqueue(c2.task('apple-only')).catch(() => {}); + both.enqueue(c2.task('both', { lanes: ['apple', 'play'], credentials: [] })).catch(() => {}); + both.enqueue(c2.task('play-only', { lanes: ['play'], credentials: [] })).catch(() => {}); + await clock.advance(0); + expect(c2.runs.map(r => r.key)).toEqual(['apple-only', 'play-only']); + }); + + test('priority first (visible app, portfolio, the rest), FIFO within one; re-enqueueing raises it', async () => { + const clock = new FakeClock(); + const s = new ReadScheduler({ clock, spacingMs: 0, limits: { apple: 1 } }); + const { runs, task } = controlled(); + s.enqueue(task('first')).catch(() => {}); + s.enqueue(task('rest-1', { priority: 2 })).catch(() => {}); + s.enqueue(task('rest-2', { priority: 2 })).catch(() => {}); + s.enqueue(task('portfolio', { priority: 1 })).catch(() => {}); + s.enqueue(task('visible', { priority: 0 })).catch(() => {}); + s.enqueue(task('rest-2', { priority: 0 })).catch(() => {}); // the owner opened that tab + await clock.advance(0); + for (let i = 0; i < 5; i++) { runs.at(-1)!.done(i); await clock.advance(0); } + expect(runs.map(r => r.key)).toEqual(['first', 'rest-2', 'visible', 'portfolio', 'rest-1']); + }); + + test('one in-flight read per key: the same promise, one run', async () => { + const clock = new FakeClock(); + const s = new ReadScheduler({ clock, spacingMs: 0 }); + const { runs, task } = controlled(); + const p1 = s.enqueue(task('k')); + const p2 = s.enqueue(task('k')); + await clock.advance(0); + const p3 = s.enqueue(task('k')); + expect(s.has('k')).toBe(true); + expect(runs).toHaveLength(1); + runs[0]!.done('v'); + expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']); + expect(s.has('k')).toBe(false); + // finished: a new enqueue runs again + s.enqueue(task('k')).catch(() => {}); + await clock.advance(0); + expect(runs).toHaveLength(2); + }); + + test('starts on one credential are spaced; other credentials are not held up', async () => { + const clock = new FakeClock(); + const s = new ReadScheduler({ clock, spacingMs: 400, limits: { apple: 8 } }); + const { runs, task } = controlled(); + for (const k of ['a', 'b', 'c']) s.enqueue(task(k)).catch(() => {}); + s.enqueue(task('other', { credentials: ['apple:k2'] })).catch(() => {}); + await clock.advance(0); + expect(runs.map(r => r.key)).toEqual(['a', 'other']); + await clock.advance(399); + expect(runs).toHaveLength(2); + await clock.advance(1); + expect(runs.map(r => r.key)).toEqual(['a', 'other', 'b']); + await clock.advance(400); + expect(runs.map(r => r.key)).toEqual(['a', 'other', 'b', 'c']); + }); + + test('429: runs again later with exponential backoff and jitter, the key waits too; gives up after maxAttempts', async () => { + const clock = new FakeClock(); + let attempts = 0; + const classify = (r: unknown): Outcome => ({ throttled: (r as { status: number }).status === 429 }); + const s = new ReadScheduler({ clock, spacingMs: 0, backoffBaseMs: 1000, backoffMaxMs: 60_000, maxAttempts: 4, classify }); + const starts: number[] = []; + const p = s.enqueue({ key: 'x', lanes: ['play'], credentials: ['play:k'], priority: 0, run: async () => { starts.push(clock.now()); attempts++; return { status: attempts < 3 ? 429 : 200 }; } }); + let other = false; + await clock.advance(0); + s.enqueue({ key: 'y', lanes: ['play'], credentials: ['play:k'], priority: 2, run: async () => { other = true; return { status: 200 }; } }).catch(() => {}); + await clock.advance(0); + // first try at 0; jitter (rand 0.5) -> 0.75 x the exponential step: 750 ms, then 1500 ms + expect(starts).toEqual([0]); + expect(s.stats().paused['play:k']).toBe(750); + await clock.advance(749); + expect(starts).toEqual([0]); + expect(other).toBe(false); // the throttled key holds back its other reads as well + await clock.advance(1); + expect(starts).toEqual([0, 750]); + await clock.advance(1500); + expect(starts).toEqual([0, 750, 2250]); + expect(await p).toEqual({ status: 200 }); + await clock.advance(0); + expect(other).toBe(true); + // always 429: resolved with the last answer after maxAttempts, counted as failed + const s2 = new ReadScheduler({ clock, spacingMs: 0, backoffBaseMs: 10, maxAttempts: 3, classify }); + let n = 0; + const q = s2.enqueue({ key: 'z', lanes: ['play'], credentials: ['play:k'], priority: 0, run: async () => { n++; return { status: 429 }; } }); + await clock.advance(1000); + expect(await q).toEqual({ status: 429 }); + expect(n).toBe(3); + }); + + test('App Store Connect quota: spreads the rest of the hour when it runs low, pauses at the reserve', async () => { + const clock = new FakeClock(); + let remaining = 3412; + const classify = (_r: unknown, _e: unknown, t: ReadTask): Outcome => ({ quota: { credential: t.credentials[0]!, limit: 3600, remaining } }); + const s = new ReadScheduler({ clock, spacingMs: 100, reserve: 100, slowBelow: 0.2, pauseMs: 600_000, limits: { apple: 4 }, classify }); + const starts: number[] = []; + const run = async () => { starts.push(clock.now()); return {}; }; + const add = (k: string) => s.enqueue({ key: k, lanes: ['apple'], credentials: ['apple:k1'], priority: 2, run }).catch(() => {}); + add('a'); add('b'); + await clock.advance(0); + await clock.advance(100); + expect(starts).toEqual([0, 100]); // plenty left: the base spacing + expect(s.stats().quota['apple:k1']).toMatchObject({ limit: 3600, remaining: 3412 }); + remaining = 500; // under 20 %: (500 - 100 reserve) left for the hour -> one start every 9 s + add('c'); add('d'); + await clock.advance(100); + const c = starts.at(-1)!; + await clock.advance(8_000); + expect(starts.at(-1)).toBe(c); + await clock.advance(1_100); + expect(starts.at(-1)! - c).toBe(9_000); + remaining = 80; // at the reserve: the key pauses for 10 minutes + add('e'); add('f'); + await clock.advance(9_000); + const e = starts.at(-1)!; + await clock.advance(599_000); + expect(starts.at(-1)).toBe(e); + expect(Object.keys(s.stats().paused)).toEqual(['apple:k1']); + await clock.advance(2_000); + expect(starts.at(-1)! - e).toBe(600_000); + // the quota a run reported stays the lowest of the hour, and is forgotten after it + remaining = 3000; + add('g'); + await clock.advance(600_000); + expect(s.stats().quota['apple:k1']!.remaining).toBe(80); + await clock.advance(3_600_000); + expect(s.stats().quota['apple:k1']).toBeUndefined(); + }); + + test('progress for the status line: done of total in one round, failures, clear()', async () => { + const clock = new FakeClock(); + const s = new ReadScheduler({ clock, spacingMs: 0, limits: { apple: 1 } }); + const { runs, task } = controlled(); + const ps = ['a', 'b', 'c'].map(k => s.enqueue(task(k)).catch(e => String(e))); + await clock.advance(0); + runs[0]!.done(1); + await clock.advance(0); + expect(s.stats()).toMatchObject({ done: 1, running: 1, queued: 1, total: 3 }); + runs[1]!.fail(new Error('boom')); + await clock.advance(0); + expect(s.stats()).toMatchObject({ done: 2, failed: 1, total: 3 }); + s.clear(); + runs[2]?.done(1); + await clock.advance(0); + expect(await ps[1]).toBe('Error: boom'); + expect(s.stats()).toMatchObject({ done: 0, total: 0, running: 0, queued: 0 }); + }); +}); + +describe('freshness', () => { + test('TTLs: status 5 min, reviews 15 min, catalog / prices / listings 30 min, health / analytics 6 h', () => { + expect([ttlOf('apple.status'), ttlOf('play.status'), ttlOf('reviews.list'), ttlOf('catalog.diff'), ttlOf('prices.current'), ttlOf('project.listings'), ttlOf('health'), ttlOf('analytics.compare')].map(x => x / 60_000)) + .toEqual([5, 5, 15, 30, 30, 30, 360, 360]); + const now = Date.parse('2026-10-13T12:00:00Z'); + expect(isStale('apple.status', '2026-10-13T11:56:00Z', now)).toBe(false); + expect(isStale('apple.status', '2026-10-13T11:55:00Z', now)).toBe(true); + expect(isStale('health', '2026-10-13T07:00:00Z', now)).toBe(false); + expect(isStale('health', null, now)).toBe(true); + expect(isStale('health', 'garbage', now)).toBe(true); + }); + test('lanes, the reads of an app, keys, throttling text, one-line reasons', () => { + expect(lanesOf('apple.status', { ios: true, android: true })).toEqual(['apple']); + expect(lanesOf('health', { ios: true, android: true })).toEqual(['apple', 'play']); + expect(lanesOf('health', { ios: false, android: true })).toEqual(['play']); + expect(lanesOf('scan', { ios: true, android: true })).toEqual(['local']); + const all = readsFor({ folder: true, ios: true, android: true }).map(r => r.method); + expect(all).toEqual(expect.arrayContaining(['apple.status', 'play.status', 'apple.testflight_status', 'reviews.list', 'health', 'catalog.diff', 'prices.current', 'project.listings', 'validate', 'scan', 'analytics.compare', 'aso.audit', 'apple.ppo_status'])); + expect(readsFor({ folder: false, ios: false, android: true }).map(r => r.method)).toEqual(['play.status', 'reviews.list', 'health']); + expect(readKey('p1', 'reviews.list', { days: 30 })).toBe(readKey('p1', 'reviews.list', { days: 30 })); + expect(readKey('p1', 'reviews.list', { days: 30 })).not.toBe(readKey('p1', 'reviews.list', {})); + expect(looksThrottled('GET /v1/apps -> 429 Too Many Requests')).toBe(true); + expect(looksThrottled('{"error":{"status":"RESOURCE_EXHAUSTED"}}')).toBe(true); + expect(looksThrottled('-> 403 forbidden')).toBe(false); + expect(oneLine('12:00:01 [health] reading\n12:00:02 [health] error: key not found\n')).toBe('error: key not found'); + }); +}); + +describe('issue detail', () => { + test('Copy for AI: title, type, counts, versions, top frames, console link', () => { + const v = playIssueView({ type: 'CRASH', cause: 'java.lang.IllegalStateException', location: 'com.example.Combo.update', reports: 412, users: 268, firstVersion: '224', lastVersion: '231', id: 'a1', uri: 'https://play.google.com/console/x' }); + expect(v.sampleArgs).toEqual({ issue: 'a1' }); + const stack = Array.from({ length: 20 }, (_, i) => `\tat com.example.F${i}(F.kt:${i})`); + const md = issueMarkdown('Prism Puddle', v, { store: 'play', version: '231', device: 'Galaxy A12', os: 'API 31', stack }); + expect(md).toContain('## Google Play CRASH: java.lang.IllegalStateException'); + expect(md).toContain('- Reports: 412, users: 268'); + expect(md).toContain('- versionCode: 224 to 231'); + expect(md).toContain('F14(F.kt:14)'); + expect(md).not.toContain('F15(F.kt:15)'); + expect(md).toContain('... 5 more frames'); + expect(md).toContain('Console: https://play.google.com/console/x'); + const a = appleSignatureView({ build: '48', type: 'HANGS', signature: 'ComboMeter.update + 212', weight: 0.31, id: 's1' }); + expect(a.sampleArgs).toEqual({ signature: 's1' }); + expect(issueMarkdown('X', a, null)).toContain('- Share of reports: 31 %'); + expect(playIssueView({ type: 'CRASH', cause: '', location: '', reports: 1, users: 1 }).sampleArgs).toBeNull(); + }); +}); diff --git a/cli/apple/asc.ts b/cli/apple/asc.ts index e9202ae..0af1831 100644 --- a/cli/apple/asc.ts +++ b/cli/apple/asc.ts @@ -4,6 +4,7 @@ import { createHash, createPrivateKey, sign } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { ascKey } from '../lib/credentials'; import { errorBody } from '../lib/http'; +import { noteAsc } from '../lib/quota'; import { AmbiguousWriteError, retrySafe } from '../lib/upsert'; import * as rt from '../lib/rt'; @@ -77,6 +78,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri if (!safe) throw new AmbiguousWriteError(`${method} ${path} -> no answer (${(e as Error).message})`); throw e; } + noteAsc(r); const t = await r.text(); if ((r.status === 429 || (r.status >= 500 && safe)) && attempt < 5) { await rt.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); } if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${method} ${path} -> ${r.status} ${errorBody(t)}`, r.status); @@ -89,6 +91,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri async function getAs(path: string, accept: string): Promise { for (let attempt = 1; ; attempt++) { const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } }); + noteAsc(r); const t = await r.text(); if ((r.status >= 500 || r.status === 429) && attempt < 5) { await rt.sleep(2000 * attempt); continue; } if (!r.ok) throw new Error(`GET ${path} -> ${r.status} ${errorBody(t, 800)}`); @@ -101,6 +104,7 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri async function bytes(path: string, accept = 'application/a-gzip'): Promise { for (let attempt = 1; ; attempt++) { const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } }); + noteAsc(r); if ((r.status >= 500 || r.status === 429) && attempt < 5) { await r.body?.cancel(); await rt.sleep(2000 * attempt); continue; } if (r.status === 404) { await r.body?.cancel(); return null; } if (!r.ok) throw new Error(`GET ${path.replace(/\?.*$/, '')} -> ${r.status} ${errorBody(await r.text(), 600)}`); diff --git a/cli/health.ts b/cli/health.ts index 3547d20..1b19376 100644 --- a/cli/health.ts +++ b/cli/health.ts @@ -14,7 +14,7 @@ import type { Ctx } from './lib/ctx'; import { REPORTING_SCOPE } from './lib/google-auth'; import { type AppleHealth, ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable, - issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString, + type IssueSample, issuesQuery, latestDailyEnd, metricQuery, parseDiagnosticLogs, parseErrorReports, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, reportsQuery, ymd, ymdString, } from './lib/health'; import { done, log, printJson, warn } from './lib/log'; import { plainError, storeReadError } from './lib/google-errors'; @@ -55,7 +55,7 @@ export async function collectAppleHealth(root: string, bundleId: string, appIdHi for (const b of builds) { log('health', `apple: diagnostic signatures of build ${b.attributes.version}`); for (const s of ((await c.asc('GET', `/v1/builds/${b.id}/diagnosticSignatures?limit=10`).catch(none({ data: [] }))).data ?? []) as J[]) - signatures.push({ build: b.attributes.version, type: s.attributes.diagnosticType, signature: s.attributes.signature ?? '', weight: Number(s.attributes.weight ?? 0) }); + signatures.push({ build: b.attributes.version, type: s.attributes.diagnosticType, signature: s.attributes.signature ?? '', weight: Number(s.attributes.weight ?? 0), ...(s.id ? { id: String(s.id) } : {}) }); } signatures.sort((a, b) => b.weight - a.weight); log('health', 'apple: TestFlight crash reports'); @@ -65,6 +65,24 @@ export async function collectAppleHealth(root: string, bundleId: string, appIdHi return { metrics, signatures: signatures.slice(0, 15), betaCrashes: betaCrashCounts(subs, buildNo, since) }; } +/** One sample report of a Play error issue (`--issue `, errorReports:search over the last `days`). */ +export async function playIssueSample(root: string, pkg: string, issueId: string, days: number): Promise { + const g = googleClient(root, REPORTING_SCOPE); + const app = `${REPORTING_API}/apps/${encodeURIComponent(pkg)}`; + const set = await g.json[0]>('GET', `${app}/crashRateMetricSet`); + const end = latestDailyEnd(set) ?? ymd(new Date(), 2); + log('health', `play: a sample report of issue ${issueId}`); + return parseErrorReports(await g.json('GET', `${app}/errorReports:search?${reportsQuery(end, days, issueId)}`)); +} + +/** The logs of one App Store diagnostic signature (`--signature `). */ +export async function appleSignatureSample(root: string, bundleId: string, appIdHint: string | undefined, id: string): Promise { + if (!/^[A-Za-z0-9_-]{1,200}$/.test(id)) throw new Error('--signature: a diagnostic signature id'); + const c = await ascClient(root, bundleId, appIdHint); + log('health', `apple: logs of diagnostic signature ${id}`); + return parseDiagnosticLogs(await c.getAs(`/v1/diagnosticSignatures/${encodeURIComponent(id)}/logs?limit=1`, 'application/vnd.apple.diagnostic-logs+json')); +} + /** Both stores (or the chosen one); a store that cannot be read becomes { error } instead of failing the run. */ export async function collectHealth(ctx: Ctx, o: { apple: boolean; play: boolean; days: number }): Promise { const { config, root } = ctx.loaded; @@ -91,10 +109,23 @@ export async function run(ctx: Ctx): Promise { const weekly = a.has('weekly'); const days = a.num('days', 7); if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90'); + const issue = a.get('issue'), signature = a.get('signature'); + if (issue || signature) { + // one issue's sample stack (the desktop's Health detail): --issue or --signature + const { config, root } = ctx.loaded; + if (issue && !config.play) throw new Error('--issue: the config has no play section'); + if (signature && !config.apple) throw new Error('--signature: the config has no apple section'); + const sample = issue ? await playIssueSample(root, config.play!.packageName, issue, Math.max(days, 28)) : await appleSignatureSample(root, config.apple!.bundleId, config.apple!.appId, signature!); + if (a.has('json')) { printJson({ sample }); return; } + console.log(sample ? [`${sample.store} ${sample.type ?? ''} ${sample.version ?? ''} ${sample.device ?? ''} ${sample.os ?? ''}`.replace(/\s+/g, ' ').trim(), ...sample.stack].join('\n') : 'no sample report in the window'); + return; + } const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days }); if (a.has('json')) { printJson(h); return; } console.log(healthTable(h)); for (const [s, x] of [['Google Play', h.play], ['App Store', h.apple]] as const) if (x && 'error' in x) console.log(`\n${s}: ${x.error}`); + const play = h.play && !('error' in h.play) ? h.play : null; + for (const i of play?.issues.filter(x => x.hint) ?? []) console.log(`\nlikely cause of ${i.cause.slice(0, 80)}: ${i.hint!.cause}\nfix: ${i.hint!.fix}`); console.log('\n' + formatFindings(healthFindings(h))); if (weekly) { const dir = ctx.loaded.resolve(a.get('out') ?? '.storebound/health'); diff --git a/cli/lib/crash-hints.ts b/cli/lib/crash-hints.ts new file mode 100644 index 0000000..61420be --- /dev/null +++ b/cli/lib/crash-hints.ts @@ -0,0 +1,22 @@ +// "Likely cause" hints for known crash signatures, shared by `storebound health` and the desktop Health tab. +// Only entries verified in a real app (or documented by the library itself) go here: a wrong hint costs more than none. + +export interface CrashHint { id: string; cause: string; fix: string } + +interface Rule extends CrashHint { match: (text: string) => boolean } + +const RULES: Rule[] = [ + { + id: 'capacitor-permission-states-npe', + match: x => /NullPointerException/.test(x) && /com\.getcapacitor\.Bridge\.getPermissionStates/.test(x), + cause: 'A Capacitor plugin\'s checkPermissions() (for example FirebaseMessaging) ran during an activity transition (focus / visibilitychange while the app resumes or rotates), when the bridge has no activity.', + fix: 'Ask for the permission state only when App.getState() says active, the page is visible and the app has been active for a short delay (e.g. 500 ms); do not call checkPermissions() from focus / visibilitychange handlers directly.', + }, +]; + +/** The hint for an issue's text (cause, location, top frames), or null. */ +export function crashHint(...texts: (string | undefined | null)[]): CrashHint | null { + const text = texts.filter(Boolean).join('\n'); + const r = RULES.find(x => x.match(text)); + return r ? { id: r.id, cause: r.cause, fix: r.fix } : null; +} diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 9c3f70d..edda93f 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -75,6 +75,8 @@ export interface ToolResult { outcome?: Outcome; /** failed only: the command's own error line (stderr's last "error: ..." line, else its last meaningful line). */ error?: string; + /** Store API quota the run saw (App Store Connect X-Rate-Limit, Google 429): the desktop's read scheduler slows down on it. */ + quota?: import('./quota').QuotaInfo; } export type Outcome = 'ok' | 'findings' | 'declined' | 'failed'; diff --git a/cli/lib/health.ts b/cli/lib/health.ts index c14fe6c..c4fe084 100644 --- a/cli/lib/health.ts +++ b/cli/lib/health.ts @@ -16,6 +16,7 @@ // https://developer.apple.com/documentation/appstoreconnectapi/power-and-performance-metrics-and-logs // GET /v1/apps/{id}/perfPowerMetrics (application/vnd.apple.xcode-metrics+json), GET /v1/builds/{id}/diagnosticSignatures // (HANGS, DISK_WRITES, LAUNCHES), GET /v1/apps/{id}/betaFeedbackCrashSubmissions (TestFlight crash reports, API 4.0+). +import { type CrashHint, crashHint } from './crash-hints'; import type { Finding, Level } from './validate-rules'; import { mdTable, pct, textTable } from './table'; import { findingText, type GoogleFinding, parseGoogleError, plainError } from './google-errors'; @@ -89,11 +90,79 @@ export function issuesQuery(end: Ymd, days: number, o: { type?: 'CRASH' | 'ANR'; return p.toString(); } -export interface Issue { type: string; cause: string; location: string; reports: number; users: number; lastVersion?: string; uri?: string } +export interface Issue { + /** Likely cause of a known signature (cli/lib/crash-hints.ts). */ + hint?: CrashHint; + type: string; cause: string; location: string; reports: number; users: number; lastVersion?: string; uri?: string; + /** The issue id (the last part of its resource name "apps//errorIssues/"): `health --issue ` reads a sample report. */ + id?: string; + /** versionCode of the first and last app version with the issue; Android API levels; the last report's time. */ + firstVersion?: string; firstOs?: string; lastOs?: string; lastSeen?: string; +} -export function parseIssues(resp: { errorIssues?: { type?: string; cause?: string; location?: string; errorReportCount?: string; distinctUsers?: string; lastAppVersion?: { versionCode?: string }; issueUri?: string }[] }): Issue[] { - return (resp.errorIssues ?? []).map(i => ({ type: i.type === 'APPLICATION_NOT_RESPONDING' ? 'ANR' : i.type ?? '?', cause: i.cause ?? '', location: i.location ?? '', - reports: Number(i.errorReportCount ?? 0), users: Number(i.distinctUsers ?? 0), lastVersion: i.lastAppVersion?.versionCode, uri: i.issueUri })); +interface ApiIssue { + name?: string; type?: string; cause?: string; location?: string; errorReportCount?: string; distinctUsers?: string; issueUri?: string; lastErrorReportTime?: string; + firstAppVersion?: { versionCode?: string }; lastAppVersion?: { versionCode?: string }; firstOsVersion?: { apiLevel?: string }; lastOsVersion?: { apiLevel?: string }; +} + +export function parseIssues(resp: { errorIssues?: ApiIssue[] }): Issue[] { + return (resp.errorIssues ?? []).map(i => { + const extra: Partial = {}; + const id = i.name?.split('/').pop(); + if (id) extra.id = id; + if (i.firstAppVersion?.versionCode) extra.firstVersion = i.firstAppVersion.versionCode; + if (i.firstOsVersion?.apiLevel) extra.firstOs = i.firstOsVersion.apiLevel; + if (i.lastOsVersion?.apiLevel) extra.lastOs = i.lastOsVersion.apiLevel; + if (i.lastErrorReportTime) extra.lastSeen = i.lastErrorReportTime; + const hint = crashHint(i.cause, i.location); + if (hint) extra.hint = hint; + return { type: i.type === 'APPLICATION_NOT_RESPONDING' ? 'ANR' : i.type ?? '?', cause: i.cause ?? '', location: i.location ?? '', + reports: Number(i.errorReportCount ?? 0), users: Number(i.distinctUsers ?? 0), lastVersion: i.lastAppVersion?.versionCode, uri: i.issueUri, ...extra }; + }); +} + +/** errorReports:search query of one issue (the newest report first), over the same UTC-midnight window as the issues. */ +export function reportsQuery(end: Ymd, days: number, issueId: string): string { + if (!/^[A-Za-z0-9_-]{1,200}$/.test(issueId)) throw new Error(`--issue: an error issue id (letters, digits, - and _), not "${issueId.slice(0, 40)}"`); + const p = new URLSearchParams(issuesQuery(end, days)); + p.delete('orderBy'); + p.set('filter', `errorIssueId = ${issueId}`); + p.set('pageSize', '1'); + return p.toString(); +} + +/** One sample report of an issue (Play errorReports, App Store diagnostic logs): the stack as lines, top frame first. */ +export interface IssueSample { store: 'play' | 'apple'; time?: string; version?: string; os?: string; device?: string; type?: string; stack: string[] } + +const MAX_FRAMES = 60; + +export function parseErrorReports(resp: { errorReports?: { reportText?: string; eventTime?: string; type?: string; appVersion?: { versionCode?: string }; osVersion?: { apiLevel?: string }; + deviceModel?: { marketingName?: string; deviceId?: { buildBrand?: string; buildDevice?: string } } }[] }): IssueSample | null { + const r = resp.errorReports?.[0]; + if (!r) return null; + const stack = (r.reportText ?? '').split('\n').map(l => l.replace(/\s+$/, '')).filter(l => l.trim()).slice(0, MAX_FRAMES); + const dev = r.deviceModel?.marketingName ?? [r.deviceModel?.deviceId?.buildBrand, r.deviceModel?.deviceId?.buildDevice].filter(Boolean).join('/'); + return { store: 'play', stack, ...(r.eventTime ? { time: r.eventTime } : {}), ...(r.appVersion?.versionCode ? { version: r.appVersion.versionCode } : {}), + ...(r.osVersion?.apiLevel ? { os: `API ${r.osVersion.apiLevel}` } : {}), ...(dev ? { device: dev } : {}), ...(r.type ? { type: r.type } : {}) }; +} + +interface ApiFrame { symbolName?: string; binaryName?: string; offsetIntoSymbol?: number; subFrames?: ApiFrame[] } + +/** GET /v1/diagnosticSignatures/{id}/logs (application/vnd.apple.diagnostic-logs+json): the first log's heaviest call + * stack, following the first sub frame down, as "binary symbol + offset" lines. */ +export function parseDiagnosticLogs(resp: { productData?: { diagnosticLogs?: { callStackTree?: { callStacks?: { callStackRootFrames?: ApiFrame[] }[] }[]; + diagnosticMetaData?: { appVersion?: string; buildVersion?: string; osVersion?: string; deviceType?: string; eventTime?: string } }[] }[] }): IssueSample | null { + const log = resp.productData?.flatMap(p => p.diagnosticLogs ?? [])[0]; + if (!log) return null; + const stack: string[] = []; + let f: ApiFrame | undefined = log.callStackTree?.[0]?.callStacks?.[0]?.callStackRootFrames?.[0]; + while (f && stack.length < MAX_FRAMES) { + stack.push(`${f.binaryName ?? '?'} ${f.symbolName ?? '???'}${f.offsetIntoSymbol !== undefined ? ` + ${f.offsetIntoSymbol}` : ''}`); + f = f.subFrames?.[0]; + } + const m = log.diagnosticMetaData ?? {}; + const version = [m.appVersion, m.buildVersion ? `(${m.buildVersion})` : ''].filter(Boolean).join(' '); + return { store: 'apple', stack, ...(version ? { version } : {}), ...(m.osVersion ? { os: m.osVersion } : {}), ...(m.deviceType ? { device: m.deviceType } : {}), ...(m.eventTime ? { time: m.eventTime } : {}) }; } export interface PlayHealth { @@ -111,7 +180,7 @@ export interface AppleHealth { /** Latest values per metric identifier (e.g. hangRate, launchTime) from perfPowerMetrics, with the app version. */ metrics: { category: string; metric: string; unit: string; version: string; value: number; goal?: string }[]; /** Top diagnostic signatures of the latest builds. */ - signatures: { build: string; type: string; signature: string; weight: number }[]; + signatures: { build: string; type: string; signature: string; weight: number; /** `health --signature ` reads its logs. */ id?: string }[]; /** TestFlight crash submissions in the window (count per build). */ betaCrashes: { build: string; count: number }[]; } @@ -262,7 +331,8 @@ export function healthMarkdown(h: HealthSnapshot, o: { appName: string; previous ['user-perceived ANR rate', pct(a), pct(prev ? weightedAverage(prev.anr, 'userPerceivedAnrRate') : null), delta(a, prev ? weightedAverage(prev.anr, 'userPerceivedAnrRate') : null), pct(PLAY_THRESHOLDS.anr)], ]), ''); if (p.issues.length) out.push('### Top issues', '', mdTable(['type', 'cause', 'location', 'reports', 'users', 'last versionCode'], - p.issues.map(i => [i.type, i.cause.slice(0, 80), i.location.slice(0, 80), i.reports, i.users, i.lastVersion ?? ''])), ''); + p.issues.map(i => [i.type, i.cause.slice(0, 80), i.location.slice(0, 80), i.reports, i.users, i.lastVersion ?? ''])), '', + ...p.issues.filter(i => i.hint).map(i => `- ${i.cause.slice(0, 80)}: likely cause: ${i.hint!.cause} Fix: ${i.hint!.fix}`), ...(p.issues.some(i => i.hint) ? [''] : [])); } const ap = h.apple && !('error' in h.apple) ? h.apple : null; if (ap) { diff --git a/cli/lib/quota.ts b/cli/lib/quota.ts new file mode 100644 index 0000000..f61999b --- /dev/null +++ b/cli/lib/quota.ts @@ -0,0 +1,51 @@ +// Store API quota seen by a command, passed to `storebound serve` (the desktop's read scheduler) as one marked stderr +// line per change: App Store Connect's X-Rate-Limit header ("user-hour-lim:3600;user-hour-rem:3412;") and 429 / +// RESOURCE_EXHAUSTED answers of the Google APIs. Outside serve (STOREBOUND_MACHINE unset) nothing is printed. + +/** Prefix of the quota line on stderr; runner.ts takes it out of the output. */ +export const QUOTA_MARK = '\u001estorebound-quota '; + +export interface QuotaInfo { + store: 'apple' | 'play'; + /** Requests per hour of this key (App Store Connect). */ + limit?: number; + /** Requests left in the current hour. */ + remaining?: number; + /** The store answered 429 / RESOURCE_EXHAUSTED at least once in this run. */ + throttled?: boolean; +} + +/** "user-hour-lim:3600;user-hour-rem:3412;" -> { limit: 3600, remaining: 3412 }; null when it is not there. */ +export function parseAscRateLimit(header: string | null | undefined): { limit: number; remaining: number } | null { + if (!header) return null; + const lim = /user-hour-lim:(\d+)/i.exec(header), rem = /user-hour-rem:(\d+)/i.exec(header); + return lim && rem ? { limit: Number(lim[1]), remaining: Number(rem[1]) } : null; +} + +let last = ''; +function emit(q: QuotaInfo): void { + if (process.env.STOREBOUND_MACHINE !== '1') return; + const line = JSON.stringify(q); + if (line === last) return; + last = line; + process.stderr.write(QUOTA_MARK + line + '\n'); +} + +/** After every App Store Connect answer. */ +export function noteAsc(r: { status: number; headers: { get(n: string): string | null } }): void { + const rl = parseAscRateLimit(r.headers.get('x-rate-limit')); + if (rl) emit({ store: 'apple', ...rl, ...(r.status === 429 ? { throttled: true } : {}) }); + else if (r.status === 429) emit({ store: 'apple', throttled: true }); +} + +/** After every Google answer (Play Developer API, Reporting API). */ +export function noteGoogle(status: number): void { + if (status === 429) emit({ store: 'play', throttled: true }); +} + +/** Folds the marked lines of one run into one value (the latest counts; throttled if any line said so). */ +export function mergeQuota(a: QuotaInfo | undefined, b: QuotaInfo): QuotaInfo { + if (!a || a.store !== b.store) return b; + const remaining = b.remaining ?? a.remaining, limit = b.limit ?? a.limit; + return { store: b.store, ...(limit === undefined ? {} : { limit }), ...(remaining === undefined ? {} : { remaining }), ...(a.throttled || b.throttled ? { throttled: true } : {}) }; +} diff --git a/cli/lib/runner.ts b/cli/lib/runner.ts index 51246f7..30dad10 100644 --- a/cli/lib/runner.ts +++ b/cli/lib/runner.ts @@ -4,6 +4,7 @@ import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { RESULT_MARK } from './log'; +import { mergeQuota, QUOTA_MARK, type QuotaInfo } from './quota'; import { toolPath } from './tools'; import * as rt from './rt'; @@ -29,7 +30,7 @@ export interface RunOptions { } /** `err`: the stderr lines only (for the command's own error line). */ -export interface RunResult { code: number; out: string; err?: string; data?: unknown; cancelled: boolean } +export interface RunResult { code: number; out: string; err?: string; data?: unknown; cancelled: boolean; /** Store quota the run saw (cli/lib/quota.ts). */ quota?: QuotaInfo } export interface Running { result: Promise; cancel(): void } @@ -73,11 +74,16 @@ export function runCommand(argv: string[], o: RunOptions): Running { const lines: string[] = []; const errs: string[] = []; let data: unknown; + let quota: QuotaInfo | undefined; const each = (line: string, kind: 'stdout' | 'stderr'): void => { if (kind === 'stdout' && line.startsWith(RESULT_MARK)) { try { data = JSON.parse(line.slice(RESULT_MARK.length)); } catch { lines.push(line); } return; } + if (kind === 'stderr' && line.startsWith(QUOTA_MARK)) { + try { quota = mergeQuota(quota, JSON.parse(line.slice(QUOTA_MARK.length)) as QuotaInfo); } catch { /* a broken quota line is dropped */ } + return; + } lines.push(line); if (kind === 'stderr') errs.push(line); o.onLine?.(line, kind); @@ -85,7 +91,7 @@ export function runCommand(argv: string[], o: RunOptions): Running { const result = (async (): Promise => { await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]); const code = await p.exited; - return { code, out: lines.join('\n').trim(), err: errs.join('\n').trim(), ...(data === undefined ? {} : { data }), cancelled }; + return { code, out: lines.join('\n').trim(), err: errs.join('\n').trim(), ...(data === undefined ? {} : { data }), ...(quota ? { quota } : {}), cancelled }; })(); return { result, cancel: () => { cancelled = true; p.kill(); } }; } diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 64fdcb5..f726dda 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -58,6 +58,10 @@ export const TOOLS: ToolDef[] = [ description: 'Read-only crash / ANR vitals from the Play Developer Reporting API (user-perceived rates vs the bad behavior thresholds 1.09 % / 0.47 %, worst device models, top issues) and App Store power and performance metrics, diagnostic signatures and TestFlight crash reports. Exit 1 when a metric is over a store threshold.', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' }, days: { type: 'integer', minimum: 1, maximum: 90, default: 7 } }, args: i => [...(i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []), ...opt('days', i.days)] }, + { name: 'health_issue', title: 'Crash issue sample', command: ['health'], write: false, network: true, + description: 'Read-only sample report of one crash / ANR issue: a Play error issue (issue: its id from health --json) via errorReports:search, or the logs of an App Store diagnostic signature (signature: its id). The stack trace as lines, with version, device and OS.', + props: { issue: { type: 'string', pattern: '^[A-Za-z0-9_-]{1,200}$', description: 'Play error issue id' }, signature: { type: 'string', pattern: '^[A-Za-z0-9_-]{1,200}$', description: 'App Store diagnostic signature id' } }, + args: i => [...opt('issue', i.issue), ...opt('signature', i.signature)] }, { name: 'health_report', title: 'Weekly health report', command: ['health', '--weekly'], write: true, network: true, idempotent: true, description: 'Weekly health summary as Markdown in .storebound/health/.md (plus .json for the next week-over-week comparison). Local files only; dry_run prints the report.', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, diff --git a/cli/play/client.ts b/cli/play/client.ts index bb5e5a9..219060f 100644 --- a/cli/play/client.ts +++ b/cli/play/client.ts @@ -3,6 +3,7 @@ import { playServiceAccount } from '../lib/credentials'; import { tokenSource } from '../lib/google-auth'; import { log, warn } from '../lib/log'; import { errorBody } from '../lib/http'; +import { noteGoogle } from '../lib/quota'; import { AmbiguousWriteError, isAmbiguous, retrySafe } from '../lib/upsert'; import * as rt from '../lib/rt'; @@ -35,6 +36,7 @@ export async function playClient(root: string, packageName: string) { if (!safe) throw new AmbiguousWriteError(`${method} ${short()} -> no answer (${(e as Error).message})`); throw e; } + noteGoogle(r.status); const text = await r.text(); if (r.ok) return (text ? JSON.parse(text) : {}) as T; if ((r.status === 429 || (r.status >= 500 && safe)) && attempt < 4) { await rt.sleep(2000 * (attempt + 1)); continue; } diff --git a/cli/play/google.ts b/cli/play/google.ts index 2201858..9691763 100644 --- a/cli/play/google.ts +++ b/cli/play/google.ts @@ -3,6 +3,7 @@ import { playServiceAccount } from '../lib/credentials'; import { tokenSource } from '../lib/google-auth'; import { errorBody } from '../lib/http'; +import { noteGoogle } from '../lib/quota'; import * as rt from '../lib/rt'; export const REPORTING_API = 'https://playdeveloperreporting.googleapis.com/v1beta1'; @@ -13,6 +14,7 @@ export function googleClient(root: string, scope: string) { for (let attempt = 0; ; attempt++) { const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, body: body === undefined ? undefined : JSON.stringify(body) }); + noteGoogle(r.status); if ((r.status === 429 || r.status >= 500) && attempt < 4) { await r.body?.cancel(); await rt.sleep(2000 * (attempt + 1)); continue; } return r; } diff --git a/cli/serve.ts b/cli/serve.ts index fdf8acb..2aa1803 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -49,7 +49,7 @@ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_r export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i; /** Read tools whose command prints a structured result with --json. */ -export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', +export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'health_issue', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', 'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff', 'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']); @@ -233,7 +233,7 @@ const SYSTEM: MethodDescriptor[] = [ ]; /** Read methods a store-only app (params.virtual, no app folder) may use: store reads that need only the store ids. */ -export const VIRTUAL_READS = new Set(['apple_status', 'play_status', 'health', 'reviews_list', 'apple_testflight_status', 'apple_ppo_status']); +export const VIRTUAL_READS = new Set(['apple_status', 'play_status', 'health', 'health_issue', 'reviews_list', 'apple_testflight_status', 'apple_ppo_status']); 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}$/; @@ -445,7 +445,7 @@ export class Session { const error = outcome === 'failed' ? errorLine(res.err ?? '', res.out) : ''; return { method, ok: res.code === 0, exitCode: res.code, dryRun: t.write ? dryRun : false, command: `storebound ${argv.join(' ')}`, output: cut(res.out), - ...(res.data === undefined ? {} : { data: res.data }), outcome, ...(error ? { error } : {}), + ...(res.data === undefined ? {} : { data: res.data }), outcome, ...(error ? { error } : {}), ...(res.quota ? { quota: res.quota } : {}), }; } diff --git a/docs/desktop.md b/docs/desktop.md index bc1e63c..427a60e 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -69,10 +69,33 @@ Types of the protocol: `cli/lib/desktop-protocol.ts`; pure portfolio logic: `cli tools, first read. - **Command palette** (Cmd/Ctrl+K): apps, tabs, screens and actions. Cmd/Ctrl+1 Portfolio, +2-5 workspace screens, Cmd/Ctrl+Shift+[ ] app tabs, arrow keys in the tab list. Toasts show background jobs with progress and Cancel. -- **Unknown, never false.** Store reads run on demand (they use the account's API quota) and are saved in app data - (`cache.sqlite`, results only, never keys); a screen opens with the saved read and its time ("Last read 3 h ago, - saved copy"), a failed read keeps the previous one and says so, and nothing that was not read is shown as fine. - Settings clears the saved reads. +- **Unknown, never false.** Every read is saved in app data (`cache.sqlite`, keyed by app + method + arguments, + results only, never keys); a card opens with the saved read at once and "read 3 min ago", a small spinner while it + refreshes, and a failed read keeps the previous one with "couldn't refresh: ". Nothing that was not + read is shown as fine. Settings clears the saved reads. +- **Automatic reading** (`src/lib/scheduler.ts`, `src/lib/freshness.ts`, `store.tsx`). On start, when the window shows + again after a minute hidden, and every N minutes while it is visible (Settings > Store reads: auto-read on by + default, every 15 min; 0 = only on start; paused while hidden), the window reads everything of every app that is past + its TTL: status and submission state 5 min, TestFlight 5 min, reviews 15 min, catalog / prices / listings / checks + 30 min, health / analytics / ASO 6 h. "Refresh all" in the toolbar reads everything now; each card has a refresh + icon. Writes invalidate the app's reads. All reads go through one scheduler: + - lanes `apple`, `play`, `local`, each with at most Settings > parallel (default 4) at once; a read that needs both + stores takes a slot in each; + - starts on one credential (account) at least 250 ms apart; + - App Store Connect's `X-Rate-Limit` header (user-hour-lim / user-hour-rem, about 3600 per key per hour) reaches the + window as the ToolResult's `quota` (`cli/lib/quota.ts`: a marked stderr line under `serve`, taken out of the + output by `runner.ts`). Below 20 % left, starts are spread over the rest of the hour; at 100 left (kept for the + owner's own commands) the key pauses 10 minutes; + - 429 / RESOURCE_EXHAUSTED (Play Developer API, Reporting API; the CLI already retries inside one command): the read + runs again with exponential backoff and equal jitter (5 s base, 5 min cap, 4 attempts), and its key waits too; + - priorities: the app on screen first, then the live portfolio status, then the rest; one in-flight read per key. + The sidebar's status line says "Reading 12 of 48 · App Store limit 3,412/3,600 left this hour". The boot check's + auto-read case (13 apps, cold cache) loads everything without a click and finds no "not read yet" on any tab. +- **Health issue detail.** A top issue (Play) or diagnostic signature (App Store) opens in place: full title and type, + reports / users, first and last versionCode, Android API range, last report, a sample stack (`health.issue` = + `health --issue ` via errorReports:search, or `health --signature ` via the signature's logs; cached like + every read), "Open in Play Console" (issueUri), "Copy for AI" (compact markdown with the top 15 frames) and a likely + cause with its fix for known signatures (`cli/lib/crash-hints.ts`, shared with `storebound health`). - **Jobs.** The window tags a call with a job id; the host maps sidecar request ids to it, so progress lines reach the right toast, and `job_cancel` sends `$/cancelRequest` (or stops a download). Live portfolio reads run up to four apps at a time with their own accounts and report n / total. diff --git a/tests/quota-crash-hints.test.ts b/tests/quota-crash-hints.test.ts new file mode 100644 index 0000000..a437ea9 --- /dev/null +++ b/tests/quota-crash-hints.test.ts @@ -0,0 +1,61 @@ +// Store quota lines for the desktop's read scheduler (cli/lib/quota.ts), crash "likely cause" hints +// (cli/lib/crash-hints.ts) and the sample report parsers of `health --issue / --signature` (cli/lib/health.ts). +import { describe, expect, test } from 'bun:test'; +import { crashHint } from '../cli/lib/crash-hints'; +import { parseDiagnosticLogs, parseErrorReports, parseIssues, reportsQuery } from '../cli/lib/health'; +import { mergeQuota, parseAscRateLimit } from '../cli/lib/quota'; + +describe('quota', () => { + test('X-Rate-Limit header', () => { + expect(parseAscRateLimit('user-hour-lim:3600;user-hour-rem:3412;')).toEqual({ limit: 3600, remaining: 3412 }); + expect(parseAscRateLimit('user-hour-rem:12;user-hour-lim:3500')).toEqual({ limit: 3500, remaining: 12 }); + expect(parseAscRateLimit(null)).toBeNull(); + expect(parseAscRateLimit('something else')).toBeNull(); + }); + test('merging the lines of one run keeps the latest count and any throttling', () => { + const a = mergeQuota(undefined, { store: 'apple', limit: 3600, remaining: 3500 }); + const b = mergeQuota(a, { store: 'apple', throttled: true }); + expect(b).toEqual({ store: 'apple', limit: 3600, remaining: 3500, throttled: true }); + expect(mergeQuota(b, { store: 'apple', limit: 3600, remaining: 3490 })).toEqual({ store: 'apple', limit: 3600, remaining: 3490, throttled: true }); + }); +}); + +describe('crash hints', () => { + test('Capacitor getPermissionStates NPE', () => { + const h = crashHint('java.lang.NullPointerException', 'com.getcapacitor.Bridge.getPermissionStates'); + expect(h?.id).toBe('capacitor-permission-states-npe'); + expect(h?.fix).toContain('App.getState()'); + expect(crashHint('java.lang.NullPointerException: Attempt to invoke virtual method', null, '\tat com.getcapacitor.Bridge.getPermissionStates(Bridge.java:1234)')?.id).toBe('capacitor-permission-states-npe'); + }); + test('no hint for other issues', () => { + expect(crashHint('java.lang.NullPointerException', 'com.example.Main.onCreate')).toBeNull(); + expect(crashHint('java.lang.IllegalStateException', 'com.getcapacitor.Bridge.getPermissionStates')).toBeNull(); + expect(crashHint(undefined, null)).toBeNull(); + }); + test('the issue list carries the hint and the detail fields', () => { + const [i] = parseIssues({ errorIssues: [{ name: 'apps/com.example/errorIssues/abc123', type: 'CRASH', cause: 'java.lang.NullPointerException', location: 'com.getcapacitor.Bridge.getPermissionStates', + errorReportCount: '9', distinctUsers: '7', firstAppVersion: { versionCode: '20' }, lastAppVersion: { versionCode: '24' }, firstOsVersion: { apiLevel: '29' }, lastOsVersion: { apiLevel: '35' }, lastErrorReportTime: '2026-10-12T10:00:00Z', issueUri: 'https://play.google.com/console/x' }] }); + expect(i).toMatchObject({ id: 'abc123', firstVersion: '20', lastVersion: '24', firstOs: '29', lastOs: '35', lastSeen: '2026-10-12T10:00:00Z', uri: 'https://play.google.com/console/x' }); + expect(i!.hint?.id).toBe('capacitor-permission-states-npe'); + }); +}); + +describe('sample reports', () => { + test('errorReports:search query and answer', () => { + const q = new URLSearchParams(reportsQuery({ year: 2026, month: 10, day: 12 }, 28, 'abc123')); + expect(q.get('filter')).toBe('errorIssueId = abc123'); + expect(q.get('pageSize')).toBe('1'); + expect(q.get('orderBy')).toBeNull(); + expect(() => reportsQuery({ year: 2026, month: 10, day: 12 }, 28, 'a b')).toThrow(); + const s = parseErrorReports({ errorReports: [{ reportText: 'java.lang.NullPointerException\n\tat com.getcapacitor.Bridge.getPermissionStates(Bridge.java:1)\n\n', eventTime: '2026-10-12T10:00:00Z', type: 'CRASH', + appVersion: { versionCode: '24' }, osVersion: { apiLevel: '34' }, deviceModel: { marketingName: 'Galaxy A12' } }] }); + expect(s).toEqual({ store: 'play', stack: ['java.lang.NullPointerException', '\tat com.getcapacitor.Bridge.getPermissionStates(Bridge.java:1)'], time: '2026-10-12T10:00:00Z', version: '24', os: 'API 34', device: 'Galaxy A12', type: 'CRASH' }); + expect(parseErrorReports({})).toBeNull(); + }); + test('App Store diagnostic logs: the first call stack, top down', () => { + const s = parseDiagnosticLogs({ productData: [{ diagnosticLogs: [{ diagnosticMetaData: { appVersion: '2.3.0', buildVersion: '48', osVersion: 'iOS 18.6', deviceType: 'iPhone15,2' }, + callStackTree: [{ callStacks: [{ callStackRootFrames: [{ binaryName: 'App', symbolName: 'main', offsetIntoSymbol: 4, subFrames: [{ binaryName: 'App', symbolName: 'Combo.update' }] }] }] }] }] }] }); + expect(s).toEqual({ store: 'apple', stack: ['App main + 4', 'App Combo.update'], version: '2.3.0 (48)', os: 'iOS 18.6', device: 'iPhone15,2' }); + expect(parseDiagnosticLogs({ productData: [] })).toBeNull(); + }); +}); diff --git a/tools/desktop-boot-check.ts b/tools/desktop-boot-check.ts index c55fc94..617db52 100644 --- a/tools/desktop-boot-check.ts +++ b/tools/desktop-boot-check.ts @@ -118,7 +118,8 @@ function host(fx: HostFixture, sidecar: Sidecar, unmocked: Set, logged: case 'app_info': return { version: conf.version, identifier: conf.identifier, platform: 'macos', debug: false, home: HOME }; case 'projects_list': return projects(); case 'accounts_list': return fx.accounts_list; - case 'workspace_get': return fx.workspace_get; + // background store reads are the auto-read case's subject (runAutoReadCase); the saved-state cases check drawing + case 'workspace_get': return withAutoRead(fx.workspace_get, false); case 'store_apps_cached': return fx.store_apps_cached ?? fx.accounts_list.map(x => ({ account: x.id, entry: null })); case 'cache_get': { const st = live && STORE_READS[String(a.method)]; @@ -169,6 +170,12 @@ function host(fx: HostFixture, sidecar: Sidecar, unmocked: Set, logged: }; } +/** The saved workspace with Settings > Reading > auto-read set (older states have no such field: on by default). */ +function withAutoRead(w: HostFixture['workspace_get'], on: boolean): HostFixture['workspace_get'] { + const settings = (w.settings ?? {}) as { refresh?: Record }; + return { ...w, settings: { ...settings, refresh: { ...settings.refresh, autoRead: on } } }; +} + /** Before any page script, as Tauri: the frozen prototype (tauri.conf.json freezePrototype), then the IPC object. */ const initScript = (freeze: boolean) => `(() => { ${freeze ? 'Object.freeze(Object.prototype);' : ''} @@ -582,6 +589,106 @@ async function runReleaseStateCase(browser: Browser, sidecar: Sidecar, page404: return { name, ok: problems.length === 0, problems: [...new Set(problems)], visited, notes }; } +/** Longest wait for the background reader to read everything of every app (a loaded machine). */ +const READ_ALL_MS = 120_000; + +/** + * Auto-read: the dev fixture state (src/dev/fixtures.ts: 2 app folders and the store-only apps of 5 accounts, at least 8 + * apps) with an empty cache. Without any click the background reader must read everything: the status line shows + * "Reading n of m" and the App Store quota, then "Everything read"; then no tab of any app says "not read yet". The + * Health tab's first top issue opens and shows its sample stack. Zero uncaught errors. + */ +async function runAutoReadCase(browser: Browser): Promise { + const name = 'auto-read (fixture state, cold cache)'; + const fx = await import('../apps/desktop/src/dev/fixtures'); + const freeze = conf.app.security.freezePrototype === true; + const server = serve(DIST, cspHeader(conf.app.security.csp), false); + const ctx = await browser.newContext({ viewport: { width: 1360, height: 900 }, reducedMotion: 'reduce' }); + const page = await ctx.newPage(); + const problems: string[] = []; + const notes: string[] = []; + const logged: string[] = []; + let reads = 0; + // fixture art is file: URLs (blocked by the CSP): icons are left out + const clean = (v: unknown): unknown => (v === undefined ? null : JSON.parse(JSON.stringify(v), (_k, x) => (typeof x === 'string' && x.startsWith('file:') ? null : x))); + const answer = async (cmd: string, a: Record): Promise => { + switch (cmd) { + case 'plugin:event|listen': return Math.floor(Math.random() * 1e9); + case 'plugin:event|unlisten': return null; + case 'log_webview': logged.push(`${String(a.level)}: ${String(a.message).slice(0, 300)}`); return null; + case 'cache_get': return null; + case 'sidecar_call': { + const method = String(a.method); + if (method === 'system.tools') return clean(await fx.mockInvoke(cmd, a)); + reads++; + return clean(fx.fixtureRead(method, String(a.projectId), ((a.params as { args?: Record } | null)?.args) ?? {})); + } + default: return clean(await fx.mockInvoke(cmd, a)); + } + }; + await page.exposeFunction('__bootCheckHost', async (cmd: string, args: Record) => { + try { return { ok: (await answer(cmd, args)) ?? null }; } catch (e) { return { err: e }; } + }); + page.on('pageerror', e => problems.push(`uncaught: ${e.stack ?? e.message}`.split('\n').slice(0, 4).join(' | '))); + page.on('console', m => { if (m.type() === 'error') problems.push(`console.error: ${m.text().slice(0, 400)}`); }); + await page.addInitScript(initScript(freeze)); + let visited = 0; + const text = async (sel = '#content') => (await page.locator(sel).first().innerText().catch(() => '')).replace(/\s+/g, ' '); + const crashCheck = async (where: string) => { for (const c of (await state(page)).crash) problems.push(`${where}: error panel ${c}`); }; + try { + await page.goto(`http://127.0.0.1:${server.port}/`, { waitUntil: 'load' }); + await page.waitForFunction(() => document.documentElement.dataset.booted === '1', null, { timeout: WAIT_MS }).catch(() => problems.push('React never drew the window (no data-booted)')); + const wizard = page.locator('.wizard[role="dialog"]'); + if (await wizard.count()) { await wizard.press('Escape').catch(() => {}); await gone(page, '.wizard[role="dialog"]'); } + const apps = await page.locator('nav.side .nav-app').count(); + if (apps < 8) problems.push(`want at least 8 apps in the sidebar, got ${apps}`); + // no click: the status line shows the reader's progress, then that everything is read + const line = '[data-testid="reader-line"]'; + if (!(await page.waitForFunction(s => /Reading \d+ of \d+/.test(document.querySelector(s)?.textContent ?? ''), line, { timeout: WAIT_MS, polling: 20 }).then(() => true, () => false))) + problems.push('status line: no "Reading n of m" while reading'); + else notes.push(`status line while reading: ${await text(line)}`); + if (!(await shows(page, line, 'Everything read', READ_ALL_MS))) problems.push(`status line: not "Everything read" after ${READ_ALL_MS / 1000} s: ${await text(line)}`); + const done = await text(line); + notes.push(`status line after: ${done}; ${reads} reads, ${apps} apps`); + if (!/App Store limit 3,412\/3,600 left this hour/.test(done)) problems.push(`status line: no App Store quota (${done})`); + await settle(page); + // every tab of every app: nothing says "not read yet" (the reads were done in the background) + const shown = await page.locator('nav.side .nav-app:visible').count(); + for (let i = 0; i < shown; i++) { + await page.locator('nav.side .nav-app:visible').nth(i).click({ timeout: WAIT_MS }).catch(e => problems.push(`app ${i}: ${String(e).split('\n')[0]}`)); + await settle(page); + const appName = (await page.locator('nav.side .nav-app:visible').nth(i).innerText().catch(() => `app ${i}`)).split('\n')[0]!.trim(); + const tabs = await page.locator('[role="tab"]').evaluateAll(ts => ts.map(x => x.id)); + for (const id of tabs) { + await page.locator(`[role="tab"]#${id}`).click({ timeout: WAIT_MS }).catch(e => problems.push(`${appName} ${id}: ${String(e).split('\n')[0]}`)); + await settle(page); + await crashCheck(`${appName} ${id}`); + const tx = await text(); + if (/not read yet|Read the stores to see this/i.test(tx)) problems.push(`${appName} ${id}: says "${(/not read yet|Read the stores to see this/i.exec(tx) ?? [''])[0]}" after the background read`); + visited++; + } + } + // Health: the first top issue opens with its full title, the sample stack and Copy for AI + await page.locator('nav.side .nav-app', { hasText: 'Prism Puddle' }).first().click({ timeout: WAIT_MS }); + await settle(page); + await page.locator('[role="tab"]#tab-health').click({ timeout: WAIT_MS }); + await settle(page); + await page.locator('.issue-row').first().click({ timeout: WAIT_MS }).catch(() => problems.push('Health: no issue row to open')); + if (!(await shows(page, '[data-testid="issue-stack"]', 'ComboMeter.update(ComboMeter.kt:88)'))) problems.push('Health: the opened issue shows no sample stack'); + const det = await text('[data-testid="issue-detail"]'); + for (const w of ['ComboMeter.update called after the level ended', 'Copy for AI', 'Open in Play Console', '224 – 231']) if (!det.includes(w)) problems.push(`Health issue detail: missing "${w}"`); + notes.push(`issue detail: ${det.slice(0, 160)}`); + await crashCheck('Health'); + } catch (e) { + problems.push(`case stopped: ${String(e).split('\n')[0]}`); + } finally { + await ctx.close(); + server.stop(true); + } + for (const l of logged) (l.startsWith('error') ? problems : notes).push(`webview.log: ${l}`); + return { name, ok: problems.length === 0, problems: [...new Set(problems)], visited, notes }; +} + /** * Errors the window must say in words (pitfall 57). `api-disabled`: the last health read of the app is Google's live * 403 SERVICE_DISABLED (Reporting API off in Cloud project 123456789000): the portfolio shows it once for the project, @@ -724,6 +831,7 @@ export async function bootCheck(): Promise { if (!ONLY.length || ONLY.includes('submit') || ONLY.includes(`submit-${v}`)) cases.push(() => runSubmitCase(browser, sidecar, base, v)); for (const p404 of [true, false]) if (!ONLY.length || ONLY.includes('release-state')) cases.push(() => runReleaseStateCase(browser, sidecar, p404)); for (const v of ['api-disabled', 'scan-findings', 'scan-failed'] as const) if (!ONLY.length || ONLY.includes('errors') || ONLY.includes(`errors-${v}`)) cases.push(() => runErrorCase(browser, sidecar, v)); + if (!ONLY.length || ONLY.includes('auto-read')) cases.unshift(() => runAutoReadCase(browser)); const results: CaseResult[] = new Array(cases.length); let next = 0; try { From 7b05e4b39615e6e7f7c849708eda5ad1d8d81849 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 13 Oct 2026 23:41:36 +0800 Subject: [PATCH 007/429] auto-read after the rebase: results through usable / failureText, issuesError notice kept, scheduler 'accounts' (no credentials word in the webview), fixtures and generated tables for health_issue --- apps/desktop/src/lib/scheduler.ts | 10 +++++----- apps/desktop/src/store.tsx | 8 ++++---- apps/desktop/tests/scheduler.test.ts | 24 ++++++++++++------------ cli/api/wrapped.gen.ts | 3 ++- cli/data/flags.json | 6 ++++++ docs/api-coverage.md | 6 +++--- tests/store-apps.test.ts | 2 +- tests/store-real-shapes.test.ts | 2 +- 8 files changed, 34 insertions(+), 27 deletions(-) diff --git a/apps/desktop/src/lib/scheduler.ts b/apps/desktop/src/lib/scheduler.ts index 14586de..b2e79e3 100644 --- a/apps/desktop/src/lib/scheduler.ts +++ b/apps/desktop/src/lib/scheduler.ts @@ -42,8 +42,8 @@ export interface Outcome { export interface ReadTask { key: string; lanes: Lane[]; - /** Keys of the store credentials it uses ("apple:", "play:"). */ - credentials: string[]; + /** Keys of the store accounts it uses ("apple:", "play:"). */ + accounts: string[]; priority: Priority; run: () => Promise; } @@ -175,7 +175,7 @@ export class ReadScheduler { private ready(i: Item, now: number): number { // 0 = can start now; otherwise the time it can (Infinity: waits on a lane slot) let at = i.notBefore; - for (const c of i.task.credentials) at = Math.max(at, this.nextAt.get(c) ?? 0); + for (const c of i.task.accounts) at = Math.max(at, this.nextAt.get(c) ?? 0); if (i.task.lanes.some(l => this.busy[l] >= Math.max(1, this.o.limits[l]))) return Infinity; return at <= now ? 0 : at; } @@ -204,7 +204,7 @@ export class ReadScheduler { this.queue = this.queue.filter(x => x !== i); this.running.set(i.task.key, i); for (const l of i.task.lanes) this.busy[l]++; - for (const c of i.task.credentials) this.nextAt.set(c, now + this.gap(c, now)); + for (const c of i.task.accounts) this.nextAt.set(c, now + this.gap(c, now)); i.attempt++; this.emit(); i.task.run().then(r => this.finish(i, r, undefined, true), e => this.finish(i, undefined, e, false)); @@ -227,7 +227,7 @@ export class ReadScheduler { const exp = Math.min(this.o.backoffMaxMs, this.o.backoffBaseMs * 2 ** (i.attempt - 1)); const delay = Math.round(exp / 2 + this.clock.random() * exp / 2); // "equal jitter" i.notBefore = now + delay; - for (const c of i.task.credentials) this.nextAt.set(c, Math.max(this.nextAt.get(c) ?? 0, now + delay)); + for (const c of i.task.accounts) this.nextAt.set(c, Math.max(this.nextAt.get(c) ?? 0, now + delay)); this.queue.push(i); } else { this.done++; diff --git a/apps/desktop/src/store.tsx b/apps/desktop/src/store.tsx index c51239f..5055326 100644 --- a/apps/desktop/src/store.tsx +++ b/apps/desktop/src/store.tsx @@ -46,7 +46,7 @@ export function classifyRead(result: unknown, error: unknown, task: ReadTask c.startsWith('apple:')) ?? 'apple:default', limit: q.limit, remaining: q.remaining }; + out.quota = { credential: task.accounts.find(c => c.startsWith('apple:')) ?? 'apple:default', limit: q.limit, remaining: q.remaining }; if (r && !r.ok && (q?.throttled || looksThrottled(r.output))) out.throttled = true; if (error !== undefined && looksThrottled(errorText(error))) out.throttled = true; return out; @@ -241,7 +241,7 @@ export function DataProvider({ children }: { children: ReactNode }) { const focusRef = useRef(null); const setFocus = useCallback((key: string | null) => { focusRef.current = key; }, []); - const credentialsOf = (a: UnifiedApp | undefined, lanes: string[]): string[] => { + const accountsOf = (a: UnifiedApp | undefined, lanes: string[]): string[] => { const c: string[] = []; if (lanes.includes('apple')) c.push(`apple:${a?.project?.appleAccount ?? a?.ios?.account ?? 'default'}`); if (lanes.includes('play')) c.push(`play:${a?.project?.playAccount ?? a?.android?.account ?? 'default'}`); @@ -254,7 +254,7 @@ export function DataProvider({ children }: { children: ReactNode }) { const app = appsRef.current.find(a => a.target === target); const pf = platformsOf(app, app ? statusRef.current(app) : undefined); const lanes = lanesOf(method, pf); - const p = sched.enqueue({ key, lanes, credentials: credentialsOf(app, lanes), priority, run: () => api.call(method, target, { args }, newJob(method)) }); + const p = sched.enqueue({ key, lanes, accounts: accountsOf(app, lanes), priority, run: () => api.call(method, target, { args }, newJob(method)) }); emitRead(key, { kind: 'start' }); p.then(result => emitRead(key, { kind: 'done', result }), e => emitRead(key, { kind: 'error', error: errorText(e) })); return p; @@ -263,7 +263,7 @@ export function DataProvider({ children }: { children: ReactNode }) { const readAll = useCallback(async (force = false) => { if (!force && !settingsRef.current.refresh.autoRead) return; if (force || isStale('portfolio.status', liveRef.current?.at)) { - sched.enqueue({ key: '*\u001fportfolio.status', lanes: ['apple', 'play'], credentials: [], priority: 1, run: () => refreshPortfolio(true, true) }).catch(() => {}); + sched.enqueue({ key: '*\u001fportfolio.status', lanes: ['apple', 'play'], accounts: [], priority: 1, run: () => refreshPortfolio(true, true) }).catch(() => {}); } const list = [...appsRef.current].filter(a => !a.ignored && !a.project?.missing) .sort((a, b) => Number(b.key === focusRef.current) - Number(a.key === focusRef.current)); diff --git a/apps/desktop/tests/scheduler.test.ts b/apps/desktop/tests/scheduler.test.ts index b2ba8d1..8124e94 100644 --- a/apps/desktop/tests/scheduler.test.ts +++ b/apps/desktop/tests/scheduler.test.ts @@ -36,7 +36,7 @@ const flush = async () => { for (let i = 0; i < 10; i++) await Promise.resolve() function controlled() { const runs: { key: string; done: (v: unknown) => void; fail: (e: unknown) => void }[] = []; const task = (key: string, o: Partial> = {}): ReadTask => ({ - key, lanes: ['apple'], credentials: ['apple:k1'], priority: 2, ...o, + key, lanes: ['apple'], accounts: ['apple:k1'], priority: 2, ...o, run: () => new Promise((done, fail) => { runs.push({ key, done, fail }); }), }); return { runs, task }; @@ -48,8 +48,8 @@ describe('ReadScheduler', () => { const s = new ReadScheduler({ clock, spacingMs: 0, limits: { apple: 2, play: 1 } }); const { runs, task } = controlled(); for (const k of ['a', 'b', 'c', 'd']) s.enqueue(task(k)).catch(() => {}); - s.enqueue(task('p1', { lanes: ['play'], credentials: ['play:k'] })).catch(() => {}); - s.enqueue(task('p2', { lanes: ['play'], credentials: ['play:k'] })).catch(() => {}); + s.enqueue(task('p1', { lanes: ['play'], accounts: ['play:k'] })).catch(() => {}); + s.enqueue(task('p2', { lanes: ['play'], accounts: ['play:k'] })).catch(() => {}); await clock.advance(0); expect(runs.map(r => r.key)).toEqual(['a', 'b', 'p1']); expect(s.stats()).toMatchObject({ running: 3, queued: 3, total: 6 }); @@ -60,8 +60,8 @@ describe('ReadScheduler', () => { const both = new ReadScheduler({ clock, spacingMs: 0, limits: { apple: 1, play: 1 } }); const c2 = controlled(); both.enqueue(c2.task('apple-only')).catch(() => {}); - both.enqueue(c2.task('both', { lanes: ['apple', 'play'], credentials: [] })).catch(() => {}); - both.enqueue(c2.task('play-only', { lanes: ['play'], credentials: [] })).catch(() => {}); + both.enqueue(c2.task('both', { lanes: ['apple', 'play'], accounts: [] })).catch(() => {}); + both.enqueue(c2.task('play-only', { lanes: ['play'], accounts: [] })).catch(() => {}); await clock.advance(0); expect(c2.runs.map(r => r.key)).toEqual(['apple-only', 'play-only']); }); @@ -100,12 +100,12 @@ describe('ReadScheduler', () => { expect(runs).toHaveLength(2); }); - test('starts on one credential are spaced; other credentials are not held up', async () => { + test('starts on one credential are spaced; other accounts are not held up', async () => { const clock = new FakeClock(); const s = new ReadScheduler({ clock, spacingMs: 400, limits: { apple: 8 } }); const { runs, task } = controlled(); for (const k of ['a', 'b', 'c']) s.enqueue(task(k)).catch(() => {}); - s.enqueue(task('other', { credentials: ['apple:k2'] })).catch(() => {}); + s.enqueue(task('other', { accounts: ['apple:k2'] })).catch(() => {}); await clock.advance(0); expect(runs.map(r => r.key)).toEqual(['a', 'other']); await clock.advance(399); @@ -122,10 +122,10 @@ describe('ReadScheduler', () => { const classify = (r: unknown): Outcome => ({ throttled: (r as { status: number }).status === 429 }); const s = new ReadScheduler({ clock, spacingMs: 0, backoffBaseMs: 1000, backoffMaxMs: 60_000, maxAttempts: 4, classify }); const starts: number[] = []; - const p = s.enqueue({ key: 'x', lanes: ['play'], credentials: ['play:k'], priority: 0, run: async () => { starts.push(clock.now()); attempts++; return { status: attempts < 3 ? 429 : 200 }; } }); + const p = s.enqueue({ key: 'x', lanes: ['play'], accounts: ['play:k'], priority: 0, run: async () => { starts.push(clock.now()); attempts++; return { status: attempts < 3 ? 429 : 200 }; } }); let other = false; await clock.advance(0); - s.enqueue({ key: 'y', lanes: ['play'], credentials: ['play:k'], priority: 2, run: async () => { other = true; return { status: 200 }; } }).catch(() => {}); + s.enqueue({ key: 'y', lanes: ['play'], accounts: ['play:k'], priority: 2, run: async () => { other = true; return { status: 200 }; } }).catch(() => {}); await clock.advance(0); // first try at 0; jitter (rand 0.5) -> 0.75 x the exponential step: 750 ms, then 1500 ms expect(starts).toEqual([0]); @@ -143,7 +143,7 @@ describe('ReadScheduler', () => { // always 429: resolved with the last answer after maxAttempts, counted as failed const s2 = new ReadScheduler({ clock, spacingMs: 0, backoffBaseMs: 10, maxAttempts: 3, classify }); let n = 0; - const q = s2.enqueue({ key: 'z', lanes: ['play'], credentials: ['play:k'], priority: 0, run: async () => { n++; return { status: 429 }; } }); + const q = s2.enqueue({ key: 'z', lanes: ['play'], accounts: ['play:k'], priority: 0, run: async () => { n++; return { status: 429 }; } }); await clock.advance(1000); expect(await q).toEqual({ status: 429 }); expect(n).toBe(3); @@ -152,11 +152,11 @@ describe('ReadScheduler', () => { test('App Store Connect quota: spreads the rest of the hour when it runs low, pauses at the reserve', async () => { const clock = new FakeClock(); let remaining = 3412; - const classify = (_r: unknown, _e: unknown, t: ReadTask): Outcome => ({ quota: { credential: t.credentials[0]!, limit: 3600, remaining } }); + const classify = (_r: unknown, _e: unknown, t: ReadTask): Outcome => ({ quota: { credential: t.accounts[0]!, limit: 3600, remaining } }); const s = new ReadScheduler({ clock, spacingMs: 100, reserve: 100, slowBelow: 0.2, pauseMs: 600_000, limits: { apple: 4 }, classify }); const starts: number[] = []; const run = async () => { starts.push(clock.now()); return {}; }; - const add = (k: string) => s.enqueue({ key: k, lanes: ['apple'], credentials: ['apple:k1'], priority: 2, run }).catch(() => {}); + const add = (k: string) => s.enqueue({ key: k, lanes: ['apple'], accounts: ['apple:k1'], priority: 2, run }).catch(() => {}); add('a'); add('b'); await clock.advance(0); await clock.advance(100); diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index 2f2131f..195a688 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -124,6 +124,7 @@ export const WRAPPED: { apple: Record; play: Record; play: Record { const r = await s.call('reviews.list', { virtual: V, args: { days: 30 }, credentials: APPLE }); expect(r.error).toBeUndefined(); expect(existsSync(join(s.calls[0]!.o.cwd, 'storebound.config.json'))).toBe(true); - expect([...VIRTUAL_READS].sort()).toEqual(['apple_ppo_status', 'apple_status', 'apple_testflight_status', 'health', 'play_status', 'reviews_list']); + expect([...VIRTUAL_READS].sort()).toEqual(['apple_ppo_status', 'apple_status', 'apple_testflight_status', 'health', 'health_issue', 'play_status', 'reviews_list']); for (const m of ['play.listing', 'catalog.diff', 'project.listings', 'check', 'reviews.approve']) expect((await s.call(m, { virtual: V, args: m === 'reviews.approve' ? { file: 'apple-1.md' } : {} })).error).toMatchObject({ code: ERR.invalidParams }); expect((await s.call('health', { virtual: V, project: '/tmp' })).error).toMatchObject({ code: ERR.invalidParams }); diff --git a/tests/store-real-shapes.test.ts b/tests/store-real-shapes.test.ts index 66a143d..f608550 100644 --- a/tests/store-real-shapes.test.ts +++ b/tests/store-real-shapes.test.ts @@ -187,7 +187,7 @@ describe('health with no field data yet', () => { }) as typeof fetch; const h = await collectAppleHealth(mkdtempSync(join(tmpdir(), 'sb-real-')), 'com.example.cutter', '6400000401', 7); expect(h.metrics).toEqual([]); - expect(h.signatures).toEqual([{ build: '10', type: 'HANGS', signature: 'main thread', weight: 0.4 }]); + expect(h.signatures).toEqual([{ build: '10', type: 'HANGS', signature: 'main thread', weight: 0.4, id: 's1' }]); }); test('other errors still make the store unreadable', async () => { ascKey(); From e59f439101d363326a7f1d8313d465e47ef714a4 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 14 Oct 2026 00:09:54 +0800 Subject: [PATCH 008/429] docs/console-parity.md: audit of every App Store Connect and Play Console field storebound reads or writes against the desktop (view, edit in place, store write), with the gaps --- docs/console-parity.md | 104 +++++++++++++++++++++++++++++++++++++++++ docs/desktop.md | 2 + 2 files changed, 106 insertions(+) create mode 100644 docs/console-parity.md diff --git a/docs/console-parity.md b/docs/console-parity.md new file mode 100644 index 0000000..7460355 --- /dev/null +++ b/docs/console-parity.md @@ -0,0 +1,104 @@ +# Console parity: App Store Connect and Play Console in the desktop app + +The desktop app (apps/desktop, [desktop.md](desktop.md)) is meant to replace App Store Connect and Play Console for +everything storebound can read or write. This page lists every owner-editable thing in the two consoles that the CLI +covers, and what the desktop does with it. + +Columns: + +- **storebound**: the command that reads or writes it, and where the value lives (the source of truth in the app + folder: `storebound.config.ts`, `store/listing.md`, `store/appstore.md`, `.storebound/`). +- **View**: the desktop shows the current value. +- **Edit**: the desktop edits it in place (validation, unsaved-changes guard, undo) and saves it into the source file. +- **Store write**: the desktop writes it to the store (dry run in the window, native confirm dialog, then the real + run; owner-only steps through the owner-action dialog). +- **Gap**: what is missing, or why a cell stays "no" on purpose. + +Status: **audit before the editors (2026-10-14)**. Every row whose CLI can write the value but the desktop cannot edit +it is a gap. Phase 2 closes them; this table is updated with the result. + +## App Store Connect + +| Console screen | storebound | View | Edit | Store write | Gap | +| --- | --- | --- | --- | --- | --- | +| App Information > Name (per locale) | `apple listing` (`### name`, apple.name, app.name) | counter only | no | yes (`apple.listing`) | no text editor | +| App Information > Subtitle | `apple listing` (`### subtitle`) | counter only | no | yes | no text editor | +| Version > Promotional Text | `apple listing` (`### promotionalText`) | counter only | no | yes | no text editor | +| Version > Description | `apple listing` (`### description`) | counter only | no | yes | no text editor | +| Version > Keywords | `apple listing` (`### keywords`), `check --aso` | counter only | no | yes | no editor, no keyword checks while typing | +| Version > What's New | `apple listing`, `whats-new apply` (`### whatsNew`) | no | no | yes | no editor | +| Version > Support URL | `apple listing` (app.supportUrl) | no | no | yes | not shown, no editor | +| Version > Marketing URL | `apple listing` (app.marketingUrl) | no | no | yes | not shown, no editor | +| App Privacy > Privacy Policy URL | `apple listing` (app.privacyPolicyUrl) | no | no | yes | not shown, no editor | +| Version > Copyright | `apple listing` (app.copyright) | no | no | yes | not shown, no editor | +| Version > version string, build | `apple listing --version --build` | yes | version field | yes | none | +| Version > Screenshots (per device, locale) | `shots render`, `apple screenshots` | renders | no | yes (`apple.screenshots`) | no ordering or replacement of scenes | +| Version > App Previews | `shots video`, `apple previews` | renders | no | yes | no replacement | +| App Information > Category, subcategories | `apple appinfo` (apple.info.categories) | yes | no | yes (`apple.appinfo`) | no editor | +| App Information > Age Rating | `apple appinfo` (apple.info.ageRating), console plan | yes | no | yes | no editor of the answers | +| App Information > Content Rights | `apple appinfo` (apple.info.contentRights) | yes | no | yes | no editor | +| Pricing and Availability > Free, territories | `apple appinfo` (apple.info.free) | yes | no | yes | no editor | +| Pricing and Availability > Pre-orders | `apple preorder` | no | no | terminal (owner) | public step; terminal only | +| App Privacy (data types, purposes) | appPrivacy.types, `console fill apple-app-privacy` | yes | no | no API (console fill) | no editor of the answers | +| App Review Information > Contact | `apple review-details` (.storebound/credentials.json reviewContact) | masked | no | yes (`apple.review_details`) | no editor | +| App Review Information > Notes | `apple review-details` (apple.info.reviewNotes, reviewAccess.instructions) | yes | no | yes | no editor | +| App Review Information > Sign-in required, demo account | reviewAccess.signInRequired, credentials.json reviewDemoAccount | masked | no | yes | no editor of sign-in required | +| Export compliance (encryption) | `apple encryption` (apple.usesNonExemptEncryption) | yes | no | yes | no editor | +| In-App Purchases > reference name, display name, description per locale | `apple iap` (products[]) | parity only | no | yes (`apple.iap`) | no editor | +| In-App Purchases > price | products[].usd, overrides, `prices import` | yes (Prices) | no | yes, owner gate | no editor of the base price | +| In-App Purchases > review note, screenshot | products[].reviewNote / reviewScreenshot, `apple iap-review` | no | no | yes (`apple.iap_review`) | not shown, no editor | +| Subscriptions > group name per locale | `apple subscriptions` (subscriptions[].listings) | no | no | yes | no editor | +| Subscriptions > name, description per locale | `apple subscriptions` (subscriptions[].subscriptions[].listings) | parity only | no | yes | no editor | +| Subscriptions > level, period, price | `apple subscriptions` | parity only | no | yes, owner gate for live prices | no editor | +| Subscriptions > introductory and promotional offers | subscriptions[].subscriptions[].intro / offers | no | no | yes (sync) | no editor | +| Subscriptions > offer codes | `apple subscriptions` (offerCodes), `apple offer-codes` | no | no | terminal (owner) | no editor | +| Subscriptions > win-back offers | `apple win-back` (winBack) | no | no | terminal (owner) | no editor | +| In-App Purchases > promoted purchases | `apple promoted` (apple.promoted) | no | no | terminal (owner) | no editor | +| Custom product pages | `apple cpp list / create / upload` (apple.customProductPages) | no | no | CLI only | not in the window | +| In-app events | `apple events list / create / upload` (apple.events) | no | no | CLI only | not in the window | +| Product Page Optimization | `apple ppo` | yes | create / start / stop | yes (owner start / stop) | none | +| TestFlight > What to Test (per build) | `apple testflight what-to-test` | yes | yes (text) | yes | per-locale text not editable | +| TestFlight > groups | `apple testflight groups sync` (apple.testflight.groups) | yes | no | yes (create missing) | no group editor | +| TestFlight > Test Information (beta description, notes) | `apple testflight info` (apple.testflight.description / reviewNotes) | no | no | CLI only | not in the window | +| TestFlight > testers | `owner.testflight_testers` (.storebound/testers.csv) | count | no | yes (owner) | CSV not editable | +| Ratings and Reviews > reply | `reviews draft / reply / approve / send` | yes | yes | yes (owner send) | none | +| Version > phased release | `owner.ios_phased` | yes | n/a | yes (owner) | none | +| Version > Submit for review | `owner.apple_submit` / `owner.apple_resubmit` | yes | n/a | yes (owner) | none | + +## Google Play Console + +| Console screen | storebound | View | Edit | Store write | Gap | +| --- | --- | --- | --- | --- | --- | +| Main store listing > App name (per language) | `play listing` (`### title`, app.name) | counter only | no | yes (`play.listing`) | no text editor | +| Main store listing > Short description | `play listing` (`### short`) | counter only | no | yes | no text editor | +| Main store listing > Full description | `play listing` (`### full`) | counter only | no | yes | no text editor, no stuffing check while typing | +| Release > Release notes (per language) | `play release`, `whats-new apply` (`### What's new`) | counter only | no | with the release (owner) | no editor | +| Main store listing > Graphics (icon, feature graphic, screenshots) | `icons`, `shots render`, `play images` | renders | no | yes (`play.images`) | no ordering or replacement of scenes | +| Main store listing > Video (YouTube URL) | `play listing` (play.video) | no | no | yes | not shown, no editor | +| Store settings > Contact email | `play listing` app details (app.contactEmail) | no | no | yes | not shown, no editor | +| Store settings > Website | `play listing` app details (app.website) | no | no | yes | not shown, no editor | +| Store settings > App category | play.category, console plan (no API) | yes | no | no API | no editor | +| App content > Privacy policy | app.privacyPolicyUrl, console plan | no | no | no API | not shown, no editor | +| App content > Data safety | `play data-safety` (dataSafety) | yes | no | yes (`play.data_safety`) | no editor of the answers | +| App content > Content rating (IARC) | social, products[].randomRewards, `console fill play-content-rating` | yes | no | no API (console fill) | no editor of the answers | +| App content > Target audience | play.targetAges, `console fill play-target-audience` | plan | no | no API (console fill) | no editor | +| Monetize > In-app products: title, description per language | `play products` (products[].listings) | parity only | no | yes (`play.products`) | no editor | +| Monetize > In-app products: price | products[].usd / overrides, `prices import` | yes (Prices) | no | yes, owner gate | no editor of the base price | +| Monetize > Subscriptions: title, benefits, description per language | `play subscriptions` | parity only | no | yes | no editor | +| Monetize > Subscriptions: base plans, offers, price | `play subscriptions` | parity only | no | yes, owner gate | no editor | +| Pricing > regional prices (price sheet) | `prices export / import` | yes | no | yes (owner) | sheet not editable in place | +| Production > Countries / regions | play.countries, console plan | count | no | no API | no editor | +| Publishing overview > Managed publishing | play.managedPublishing | yes | no | no API | no editor | +| Testing tracks (internal, closed, open) | `play release --track` | status | n/a | terminal (owner) | sends builds to testers: not in the window by design | +| Production > staged rollout | `owner.play_rollout` | yes | n/a | yes (owner) | none | +| Production > Send to production | `owner.play_production` | yes | n/a | yes (owner) | none | +| Ratings and reviews > reply | `reviews draft / reply / approve / send` | yes | yes | yes (owner send) | none | +| Internal app sharing | `play share` | no | n/a | CLI only | not in the window | + +## Both stores + +| What | storebound | View | Edit | Store write | Gap | +| --- | --- | --- | --- | --- | --- | +| Pull the live texts into the files | `apple listing pull`, `play listing pull`, `catalog pull` | no | n/a | n/a (writes local files) | not in the window | +| Store-only app (no folder): listing text | (none) | yes (status) | no | no | store-only apps are read-only in the window | +| Uncommitted changes in the app folder | git | no | n/a | n/a | not shown | diff --git a/docs/desktop.md b/docs/desktop.md index 427a60e..db67603 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -17,6 +17,8 @@ development; this page is for contributors. - **Catalog parity.** Products (and subscriptions, once the config has them) are defined once; `portfolio.status` compares the config with both stores (ids missing on a store, ids on one store only). +Console parity (what the window can view, edit and write for each console screen): [console-parity.md](console-parity.md). + Types of the protocol: `cli/lib/desktop-protocol.ts`; pure portfolio logic: `cli/lib/portfolio.ts`. ## Safety model From 714352ec18e9b0b0105f1b021b05ae3fe2af367b Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 14 Oct 2026 00:14:32 +0800 Subject: [PATCH 009/429] =?UTF-8?q?Play=20edits=20under=20a=20machine-wide?= =?UTF-8?q?=20per-package=20lock=20(parallel=20reads=20of=20one=20app=20no?= =?UTF-8?q?=20longer=20delete=20each=20other's=20edits;=20a=20read=20whose?= =?UTF-8?q?=20edit=20was=20deleted=20is=20redone=20once,=20writes=20are=20?= =?UTF-8?q?not);=20a=20store=20that=20failed=20to=20read=20is=20'Couldn't?= =?UTF-8?q?=20read=20Google=20Play'=20and=20keeps=20its=20last=20good=20re?= =?UTF-8?q?leases=20with=20'couldn't=20refresh';=20stores=20on=20different?= =?UTF-8?q?=20versions:=20neutral=20'Current=20=C2=B7=20Play=20x=20=C2=B7?= =?UTF-8?q?=20App=20Store=20y'=20header=20and=20each=20lane=20its=20own=20?= =?UTF-8?q?state,=20'Not=20on=20this=20store'=20only=20without=20a=20recor?= =?UTF-8?q?d;=20Play=20status=20decided=20from=20the=20public=20store=20pa?= =?UTF-8?q?ge's=20live=20version=20(Live=20/=20In=20review=20/=20In=20revi?= =?UTF-8?q?ew=20(live:=20x)=20/=20managed=20publishing=20/=20Rolling=20out?= =?UTF-8?q?=20/=20Halted=20/=20Draft;=20only=20a=20network=20failure=20say?= =?UTF-8?q?s=20'Couldn't=20check=20the=20store=20page',=20with=20the=20las?= =?UTF-8?q?t=20known=20answer=20and=20its=20time);=20tests/play-edit-lock.?= =?UTF-8?q?test.ts,=20recorded=20page=20fixture,=20boot=20check=20auto-rea?= =?UTF-8?q?d=20cases=20(pitfall=2058)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 14 +++ apps/desktop/src/dev/fixtures.ts | 5 +- apps/desktop/src/dev/submit-fixtures.ts | 4 +- apps/desktop/src/i18n/en.ts | 17 ++- apps/desktop/src/i18n/tr.ts | 17 ++- apps/desktop/src/screens/tabs/Releases.tsx | 49 +++++--- apps/desktop/src/store.tsx | 6 +- apps/desktop/src/ui/kit.tsx | 6 +- cli/lib/desktop-protocol.ts | 14 ++- cli/lib/lock.ts | 65 +++++++++- cli/lib/play-public.ts | 50 ++++++-- cli/lib/portfolio.ts | 46 ++++--- cli/lib/train.ts | 63 ++++++++-- cli/play/client.ts | 23 +++- cli/play/status.ts | 6 +- skills/store-pitfalls/SKILL.md | 23 +++- tests/fixtures/play-page-version.html | 7 ++ tests/helpers/preload.ts | 1 + tests/play-edit-lock.test.ts | 135 +++++++++++++++++++++ tests/play-public-version-match.test.ts | 88 ++++++++++---- tests/portfolio.test.ts | 2 +- tests/release-train.test.ts | 2 +- tests/serve.test.ts | 2 +- tools/desktop-boot-check.ts | 28 ++++- 24 files changed, 570 insertions(+), 103 deletions(-) create mode 100644 tests/fixtures/play-page-version.html create mode 100644 tests/play-edit-lock.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d82704e..0030543 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- **Parallel Play reads no longer break each other.** Google Play keeps one open edit per app, so two reads of one + app at once (the desktop's auto-read) deleted each other's edits ("This Edit has been deleted") and the Releases tab + then said "not on Google Play yet". Every Play edit of a package now runs under a machine-wide per-package lock + (`~/.storebound/locks`, wait with timeout and heartbeat; other packages stay parallel), and a read whose edit was + deleted is redone once with a new edit (writes are not). A store that failed to read shows "Couldn't read Google + Play" and keeps its last good releases with "couldn't refresh". When the stores' current versions differ, the card + header says "Current · Play 4.1.9 · App Store 4.1.2" and each lane shows its own state ("4.1.2 · Live (4.1.9 not + submitted)"); "Not on this store" only for an app with no record there (pitfall 58). +- **Google Play status is decided, never "maybe".** `play status`, the portfolio and the desktop read the live version + from the public store page ("Version" in About this app): the same version = Live, 404 = In review (managed + publishing: In review / ready to publish), an older one = In review (live: 1.0.0), Rolling out N% / Halted / Draft + from the API. Only a network failure says "Couldn't check the store page", and it keeps the last known answer with + its time. "In review or not yet published" and "Google may still be reviewing" are gone. + - **Desktop reads everything by itself.** No more "Not read yet" and a Read button on every page: on start, when the window shows again and every 15 minutes while it is open (Settings: auto-read on / off, interval), every app's status, releases and submission state, TestFlight, catalog, prices, listings, health, reviews, analytics and checks diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 5e1a63a..406b2f4 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -71,7 +71,7 @@ const STORE_APPS: Record = { droid('com.example.nightnotes.free', 'Nightnotes Free', G.night), droid('com.example.moodgrid', 'Mood Grid', G.mood), ], [A1]: [ - ios('6400000001', 'com.example.prismpuddle', 'Prism Puddle', null, ['2.4.0', 'WAITING_FOR_REVIEW']), ios('6400000011', 'com.example.orbithop', 'Orbit Hop', G.orbit, ['3.1.0', 'READY_FOR_SALE']), + ios('6400000001', 'com.example.prismpuddle', 'Prism Puddle', null, ['2.4.0', 'WAITING_FOR_REVIEW']), ios('6400000011', 'com.example.orbithop', 'Orbit Hop', G.orbit, ['3.0.4', 'READY_FOR_SALE']), ios('6400000012', 'com.example.blockgarden.ios', 'Block Garden', G.block, ['1.2.0', 'IN_REVIEW']), ios('6400000013', 'com.example.wordlantern', 'Word Lantern', G.lantern, ['2.0.1', 'READY_FOR_SALE']), ios('6400000014', 'com.example.oldracer', 'Old Racer', G.racer, ['1.9.3', 'REMOVED_FROM_SALE']), ], @@ -166,7 +166,8 @@ function status(id: string, live: boolean): AppStatus { } /** Store-only app releases (fixture), by bundle id / package name. */ const STORE_RELEASES: Record = { - 'com.example.orbithop': [rel('ios', '3.1.0', 'live', { build: '88', state: 'READY_FOR_SALE', date: iso(60 * 24 * 6) }), rel('android', '3.1.0', 'rollout', { build: '310', state: 'inProgress', fraction: 0.5 })], + // the stores do not always move together: Play is on 3.1.0, the App Store still on 3.0.4 + 'com.example.orbithop': [rel('ios', '3.0.4', 'live', { build: '88', state: 'READY_FOR_SALE', date: iso(60 * 24 * 6) }), rel('android', '3.1.0', 'rollout', { build: '310', state: 'inProgress', fraction: 0.5 })], 'com.example.blockgarden.ios': [rel('ios', '1.2.0', 'review', { build: '17', state: 'IN_REVIEW', date: iso(60 * 5) }), rel('ios', '1.1.2', 'live', { build: '15', state: 'READY_FOR_SALE', date: iso(60 * 24 * 40) })], 'com.example.blockgarden': [rel('android', '1.2.0', 'live', { build: '120', state: 'completed' })], 'com.example.wordlantern': [rel('ios', '2.0.1', 'live', { build: '41', state: 'READY_FOR_SALE', date: iso(60 * 24 * 18) })], diff --git a/apps/desktop/src/dev/submit-fixtures.ts b/apps/desktop/src/dev/submit-fixtures.ts index cc7cf1f..9b29a0f 100644 --- a/apps/desktop/src/dev/submit-fixtures.ts +++ b/apps/desktop/src/dev/submit-fixtures.ts @@ -106,7 +106,7 @@ export const PLAY_STATUS = { // A first release in the shapes the stores really answered (pitfall: App Store "1.0" in review while Google Play's // production release of "1.0.0" reads "completed" but the app is not public yet). `play status --json` adds the public -// store page check (publicPage): 404 = not public yet, 200 = published. +// store page check (publicPage): 404 = not public yet, 200 = published with the page's live version. export const APPLE_STATUS_FIRST_REVIEW = { app: { id: '1000000002', attributes: { name: 'Prism Puddle', bundleId: 'com.example.prismpuddle' } }, versions: [version('ver-10', '1.0', 'WAITING_FOR_REVIEW', 'b-3')], @@ -119,7 +119,7 @@ const playFirst = (state: 'public' | 'notPublic') => ({ { track: 'production', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed', userFraction: 1 }] }, { track: 'internal', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed' }] }, ], - publicPage: { state, http: state === 'public' ? 200 : 404, versionName: null, checkedAt: '2026-10-13T08:00:00Z', url: 'https://play.google.com/store/apps/details?id=com.example.prismpuddle&hl=en' }, + publicPage: { state, http: state === 'public' ? 200 : 404, versionName: state === 'public' ? '1.0.0' : null, checkedAt: '2026-10-13T08:00:00Z', url: 'https://play.google.com/store/apps/details?id=com.example.prismpuddle&hl=en' }, }); export const PLAY_STATUS_FIRST_404 = playFirst('notPublic'); export const PLAY_STATUS_FIRST_200 = playFirst('public'); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 9013ee9..3cad6a2 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -118,9 +118,13 @@ export const en = { 'phase.paused': 'Paused', 'phase.approved': 'Approved', 'phase.review': 'In review', - 'phase.sent': 'Sent to Google (in review or not yet published)', - 'phase.released': 'Released to production (Google may still be reviewing)', - 'phase.releasedUnknown': 'Released to production (live state unknown: the store page could not be read)', + 'phase.sent': 'In review', + 'phase.released': "Couldn't check the store page", + 'phase.releasedUnknown': "Couldn't check the store page", + 'phase.pageUnknown': "Couldn't check the store page", + 'phase.pageStale': "couldn't check the store page, as of {when}", + 'phase.reviewLive': 'In review (live: {version})', + 'phase.reviewManaged': 'In review / ready to publish (managed publishing)', 'phase.rejected': 'Rejected', 'phase.testing': 'Testing', 'phase.draft': 'Draft', @@ -236,6 +240,12 @@ export const en = { 'tl.store': 'Store', 'tl.created': 'Created {date}', 'tl.notOnStore': 'Not on this store', + 'tl.unknown': 'Unknown', + 'tl.unreadable': "Couldn't read {store}: state unknown", + 'tl.otherVersion': '{now} · {phase} ({version} not submitted)', + 'tl.notThisVersion': 'Not this version', + 'tl.current': 'Current', + 'tl.bothVersions': 'Play {play} · App Store {ios}', 'tl.noVersion': '{version} is not on {store} yet', 'tl.everyone': 'Everyone', 'tl.day': 'day {day} of 7', @@ -245,6 +255,7 @@ export const en = { 'releases.notReadText': 'The timeline shows each version on both stores: build, TestFlight or internal testing, review, live and the rollout share. Read the stores once to fill it.', 'releases.noAccounts': 'Tip: map store accounts to this app in App folders first.', 'releases.storeUnreadable': '{store} could not be read, so its lane shows as unknown: {error}', + 'releases.storeStale': "Couldn't refresh {store}: showing the read from {when}. {error}", 'releases.noVersions': 'No versions on the stores yet', 'releases.noVersionsText': 'When the first build is uploaded it shows here.', 'releases.history': 'Versions on the stores', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 703ba4a..1efb833 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -120,9 +120,13 @@ export const tr: Record = { 'phase.paused': 'Duraklatıldı', 'phase.approved': 'Onaylandı', 'phase.review': 'İncelemede', - 'phase.sent': 'Google’a gönderildi (incelemede ya da henüz yayınlanmadı)', - 'phase.released': 'Üretime çıktı (Google hâlâ inceliyor olabilir)', - 'phase.releasedUnknown': 'Üretime çıktı (yayın durumu bilinmiyor: mağaza sayfası okunamadı)', + 'phase.sent': 'İncelemede', + 'phase.released': 'Mağaza sayfası kontrol edilemedi', + 'phase.releasedUnknown': 'Mağaza sayfası kontrol edilemedi', + 'phase.pageUnknown': 'Mağaza sayfası kontrol edilemedi', + 'phase.pageStale': 'mağaza sayfası kontrol edilemedi, {when} itibarıyla', + 'phase.reviewLive': 'İncelemede (yayında: {version})', + 'phase.reviewManaged': 'İncelemede / yayına hazır (yönetilen yayınlama)', 'phase.rejected': 'Reddedildi', 'phase.testing': 'Testte', 'phase.draft': 'Taslak', @@ -238,6 +242,12 @@ export const tr: Record = { 'tl.store': 'Mağaza', 'tl.created': 'Oluşturma: {date}', 'tl.notOnStore': 'Bu mağazada yok', + 'tl.unknown': 'Bilinmiyor', + 'tl.unreadable': '{store} okunamadı: durum bilinmiyor', + 'tl.otherVersion': '{now} · {phase} ({version} gönderilmedi)', + 'tl.notThisVersion': 'Bu sürüm değil', + 'tl.current': 'Güncel', + 'tl.bothVersions': 'Play {play} · App Store {ios}', 'tl.noVersion': '{version} henüz {store} mağazasında yok', 'tl.everyone': 'Herkes', 'tl.day': '7 günün {day}. günü', @@ -247,6 +257,7 @@ export const tr: Record = { 'releases.notReadText': 'Zaman çizelgesi her sürümü iki mağazada birlikte gösterir: derleme, TestFlight ya da dahili test, inceleme, yayın ve dağıtım payı. Doldurmak için mağazaları bir kez okuyun.', 'releases.noAccounts': 'İpucu: önce Uygulama klasörleri ekranında bu uygulamaya mağaza hesaplarını bağlayın.', 'releases.storeUnreadable': '{store} okunamadı, bu yüzden şeridi bilinmiyor olarak gösteriliyor: {error}', + 'releases.storeStale': '{store} yenilenemedi: {when} okunan durum gösteriliyor. {error}', 'releases.noVersions': 'Mağazalarda henüz sürüm yok', 'releases.noVersionsText': 'İlk derleme yüklendiğinde burada görünür.', 'releases.history': 'Mağazalardaki sürümler', diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index a480227..29a4c53 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -4,7 +4,8 @@ // as console plans. Releasing an approved version (manual release) stays in App Store Connect. import { plainError } from '../../../../../cli/lib/google-errors'; import { useState } from 'react'; -import type { ReleaseTrain, StoreRelease } from '../../api'; +import type { AppStatus, ReleaseTrain, StoreRelease } from '../../api'; +import { laneGap, storesDiffer } from '../../../../../cli/lib/train'; import type { UnifiedApp } from '../../lib/identity'; import { WriteButton } from '../../ui/WriteButton'; import { type Key, t } from '../../i18n'; @@ -13,7 +14,7 @@ import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } import { useData, useRead, useWrite } from '../../store'; import { Icon, StoreGlyph } from '../../ui/icons'; import { RolloutBar } from '../../ui/charts'; -import { Card, Chip, Empty, Notice, PhaseChip, Skeleton, storeName } from '../../ui/kit'; +import { Card, Chip, Empty, Notice, PhaseChip, phaseLabel, Skeleton, storeName } from '../../ui/kit'; import { AppleSubmitCard, PlayProductionCard } from './Submit'; const STAGE_KEY: Record<(typeof STAGES)[number], Key> = { build: 'stage.build', testing: 'stage.testing', review: 'stage.review', live: 'stage.live', rollout: 'stage.rollout' }; @@ -22,23 +23,35 @@ function stageCaption(l: Lane, i: number): string { if (i !== l.at || !l.release) return ''; const r = l.release; if (i === 1) return r.store === 'ios' ? 'TestFlight' : (r.track ?? t('stage.testing')); - if (i === 2) return t(`phase.${r.phase}` as Key); - if (i === 3 && r.phase === 'released') return t(r.publicPage === 'unknown' ? 'phase.releasedUnknown' : 'phase.released'); + if (i === 2) return r.store === 'android' ? phaseLabel(r).text : t(`phase.${r.phase}` as Key); + if (i === 3 && r.phase === 'released') return phaseLabel(r).text; return ''; } -function LaneRow({ lane, version }: { lane: Lane; version: string }) { +/** The text of a lane that does not carry this version: couldn't read, the store's own current version, not there yet, + * or (only without any record of the app on that store) "Not on this store". */ +function gapText(lane: Lane, version: string, st: AppStatus): { who: string; line: string; kind: string } { + const g = laneGap(lane.store, st.release.all ?? [], st.storeErrors[lane.store]); + const store = storeName(lane.store); + if (g.kind === 'unreadable') return { kind: g.kind, who: t('tl.unknown'), line: t('tl.unreadable', { store }) }; + if (g.kind === 'other') return { kind: g.kind, who: g.now.version, line: t('tl.otherVersion', { now: g.now.version, phase: t(`phase.${g.now.phase}` as Key), version }) }; + if (g.kind === 'missing') return { kind: g.kind, who: t('tl.notThisVersion'), line: t('tl.noVersion', { version, store }) }; + return { kind: g.kind, who: t('tl.notOnStore'), line: t('tl.notOnStore') }; +} + +function LaneRow({ lane, version, st }: { lane: Lane; version: string; st: AppStatus }) { const r = lane.release; + const gap = lane.at < 0 ? gapText(lane, version, st) : null; return (
{storeName(lane.store)}
-
{r ? `${r.version ?? version}${r.build ? ` (${r.build})` : ''}` : t('tl.notOnStore')}
+
{r ? `${r.version ?? version}${r.build ? ` (${r.build})` : ''}` : gap!.who}
- {lane.at < 0 ?
{t('tl.noVersion', { version, store: storeName(lane.store) })}
: STAGES.map((s, i) => { + {gap ?
{gap.line}
: STAGES.map((s, i) => { const cls = i < lane.at ? 'done' : i === lane.at ? `cur ${lane.tone}` : ''; const last = s === 'rollout'; return ( @@ -102,16 +115,19 @@ function RolloutControls({ app, r }: { app: UnifiedApp; r: StoreRelease }) { return null; } -function Train({ title, train, tf, tone, app }: { title: string; train: ReleaseTrain; tf: TestFlightStatus | null; tone: 'accent' | 'ok'; app: UnifiedApp }) { +function Train({ title, train, tf, tone, app, st }: { title: string; train: ReleaseTrain; tf: TestFlightStatus | null; tone: 'accent' | 'ok'; app: UnifiedApp; st: AppStatus }) { const lanes = trainLanes(train, tf); - // "Live" only when a store has it live or rolling out; a Play release Google may still review is "Released" - const label = tone === 'ok' && !lanes.some(l => l.release && ['live', 'rollout', 'halted'].includes(l.release.phase)) ? t('tl.released') : title; + // the stores' current versions differ (normal: they do not always move together): a neutral "Current" header + const differ = tone === 'ok' ? storesDiffer(st.release.all ?? []) : null; + // "Live" only when a store has it live or rolling out; a Play release whose store page could not be checked is not + const label = differ ? t('tl.current') : tone === 'ok' && !lanes.some(l => l.release && ['live', 'rollout', 'halted'].includes(l.release.phase)) ? t('tl.released') : title; + const ver = differ ? t('tl.bothVersions', { play: differ.android, ios: differ.ios }) : train.version; return ( - {train.version}{label}} + {ver}{label}} sub={[train.ios?.date ? t('tl.created', { date: date(train.ios.date) }) : null].filter(Boolean).join(' · ') || undefined}>
{t('tl.store')}{STAGES.map(s => {t(STAGE_KEY[s])})}
- {lanes.map(l => )} + {lanes.map(l => )}
{lanes.some(l => l.release) && app.project && (
@@ -157,9 +173,12 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { const errs = Object.entries(l.storeErrors); return ( <> - {errs.map(([s, msg]) => {t('releases.storeUnreadable', { store: storeName(s as 'ios'), error: plainError(msg) })})} - {l.release.next && } - {l.release.current && } + {errs.map(([s, msg]) => { + const when = l.staleStores?.[s as 'ios']; + return {when ? t('releases.storeStale', { store: storeName(s as 'ios'), when: ago(when), error: plainError(msg) }) : t('releases.storeUnreadable', { store: storeName(s as 'ios'), error: plainError(msg) })}; + })} + {l.release.next && } + {l.release.current && } {!l.release.next && !l.release.current && {t('releases.noVersionsText')}} diff --git a/apps/desktop/src/store.tsx b/apps/desktop/src/store.tsx index 5055326..38c8bbd 100644 --- a/apps/desktop/src/store.tsx +++ b/apps/desktop/src/store.tsx @@ -16,6 +16,7 @@ import { keepLines, progressOf } from './lib/progress'; import { isStale, lanesOf, looksThrottled, oneLine, readKey, readsFor } from './lib/freshness'; import { type Outcome, type Priority, ReadScheduler, type ReadTask, type SchedulerStats } from './lib/scheduler'; import { fixHint } from './lib/views'; +import { withLastGood } from '../../../cli/lib/train'; import { failureText, usable } from './lib/results'; export type ToastKind = 'job' | 'ok' | 'bad' | 'info'; @@ -201,7 +202,10 @@ export function DataProvider({ children }: { children: ReactNode }) { const tid = liveRead && !quiet ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; try { const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : []; - const r = await api.portfolio(liveRead, job, stores); + let r = await api.portfolio(liveRead, job, stores); + // a store that failed this time keeps its last good releases ("couldn't refresh"), never turns empty + const prevLive = liveRef.current; + if (liveRead && prevLive) r = { ...r, apps: r.apps.map(a => withLastGood(prevLive.value.apps.find(x => x.project === a.project), a, prevLive.at)) }; setPortfolio(r); if (liveRead) { const changes = releaseChanges(liveRef.current?.value, r); diff --git a/apps/desktop/src/ui/kit.tsx b/apps/desktop/src/ui/kit.tsx index f65ea4e..62c5106 100644 --- a/apps/desktop/src/ui/kit.tsx +++ b/apps/desktop/src/ui/kit.tsx @@ -22,7 +22,11 @@ export function phaseLabel(r: StoreRelease | null | undefined): { text: string; const pct = r.fraction !== null && r.fraction !== undefined && r.fraction < 1 ? ` ${share(r.fraction)}` : ''; if (r.phase === 'rollout') return { text: (r.store === 'ios' ? t('phase.phased') : t('phase.rollout')) + pct, tone: 'accent' }; if (r.phase === 'halted') return { text: (r.store === 'ios' ? t('phase.paused') : t('phase.halted')) + pct, tone: 'bad' }; - if (r.phase === 'released' && r.publicPage === 'unknown') return { text: t('phase.releasedUnknown'), tone: 'neutral' }; + const stale = r.pageStaleAt ? ` · ${t('phase.pageStale', { when: ago(r.pageStaleAt) })}` : ''; + if (r.store === 'android' && r.phase === 'released') return { text: t('phase.pageUnknown') + stale, tone: 'neutral' }; + if (r.store === 'android' && (r.phase === 'review' || r.phase === 'sent')) + return { text: (r.managed ? t('phase.reviewManaged') : r.liveVersion ? t('phase.reviewLive', { version: r.liveVersion }) : t('phase.review')) + stale, tone: 'warn' }; + if (r.store === 'android' && r.phase === 'live' && stale) return { text: t('phase.live') + stale, tone: 'ok' }; if (r.phase === 'testing' && r.track) return { text: `${t('phase.testing')} · ${r.track}`, tone: 'info' }; return { text: t(`phase.${r.phase}`), tone: PHASE_TONE[r.phase] }; } diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index edda93f..7f824a2 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -159,9 +159,9 @@ export interface AppIdentity { } /** Where a version is on one store. */ -/** `sent`: a Google Play production release that is completed in the API while the public store page is 404 (sent to - * Google, in review or not yet published). `released`: completed in production and the app is public, but this - * version is not proven live (an update Google may still be reviewing, or the public page could not be read). */ +/** Google Play production (completed in the API) is decided by the public store page: its version = `live`, 404 or an + * older live version = `review` (with `liveVersion` / `managed`), page never read (network) = `released` with + * publicPage unknown ("Couldn't check the store page"). `sent` is no longer produced (older cached reads). */ export type ReleasePhase = 'live' | 'rollout' | 'halted' | 'released' | 'approved' | 'review' | 'sent' | 'rejected' | 'testing' | 'draft' | 'other'; export interface StoreRelease { @@ -180,6 +180,12 @@ export interface StoreRelease { phased?: { state: string; day: number | null } | null; /** Google Play production: the public store page (public = 200, notPublic = 404, unknown = not read). */ publicPage?: 'public' | 'notPublic' | 'unknown'; + /** Google Play production in review while the store page shows an older live version: that version. */ + liveVersion?: string | null; + /** Google Play production in review with managed publishing on (play.managedPublishing): approval is not readable. */ + managed?: boolean; + /** The store page could not be read now: the phase is from the last known page read at this time. */ + pageStaleAt?: string | null; /** When the store record was made (iOS version createdDate), if the store says. */ date?: string | null; } @@ -216,6 +222,8 @@ export interface AppStatus { virtual?: boolean; /** live only: per-platform read errors ("unknown, never false"). */ storeErrors: { ios?: string; android?: string }; + /** A store that could not be read this time, shown from the last good read (its time): couldn't refresh. */ + staleStores?: { ios?: string; android?: string }; errors: string[]; } diff --git a/cli/lib/lock.ts b/cli/lib/lock.ts index a3a1970..a51031c 100644 --- a/cli/lib/lock.ts +++ b/cli/lib/lock.ts @@ -3,9 +3,10 @@ // same app at once and race each other into duplicates. Dry runs and reads take no lock. // A lock whose process is gone (same machine) is taken over; a live one stops the run with who holds it. A lock // left by a crash on another machine (shared folder) stays until --force-unlock or 12 hours. -import { hostname } from 'node:os'; -import { mkdirSync, openSync, readFileSync, rmSync, writeSync, closeSync } from 'node:fs'; +import { homedir, hostname } from 'node:os'; +import { mkdirSync, openSync, readFileSync, rmSync, statSync, utimesSync, writeSync, closeSync } from 'node:fs'; import { join } from 'node:path'; +import { AsyncLocalStorage } from 'node:async_hooks'; import type { ShipConfig } from './config'; import type { Args } from './args'; @@ -58,6 +59,66 @@ export function acquireLock(root: string, key: string, command: string, o: { for return () => { rmSync(path, { force: true }); held.delete(path); }; } +// ---- Machine-wide short locks (Play edits) ---- +// Google Play keeps one open edit per app: a second edits.insert for the same package invalidates the first ("This +// Edit has been deleted"). Every storebound process that opens an edit (reads included) takes +// ~/.storebound/locks/.lock first, so parallel reads of one package wait for each other; other packages run in +// parallel. The holder touches the file every few seconds (heartbeat); a file whose process is gone or that was not +// touched for STALE_SHORT_MS is taken over. Waiting has a timeout and logs who it waits for. + +export const machineLockDir = (): string => process.env.STOREBOUND_LOCK_DIR || join(homedir(), '.storebound', 'locks'); +const STALE_SHORT_MS = 60_000; + +/** Whether a short lock may be taken over: unreadable, its process gone (same host) or not touched for a minute. */ +export function staleShortLock(l: LockInfo | null, touchedAt: number, now = Date.now(), host = hostname(), isAlive = alive): boolean { + if (!l) return now - touchedAt > 2000; // half written: give the writer a moment + if (now - touchedAt > STALE_SHORT_MS) return true; + return l.host === host && !isAlive(l.pid); +} + +const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); +/** The machine locks held by the current async call chain: a nested take of the same key runs inside the outer one + * (it would otherwise wait for itself), while a parallel caller in the same process still waits. */ +const inside = new AsyncLocalStorage>(); + +/** + * Runs fn while holding the machine-wide lock `key` (e.g. `play-edit-`). Waits up to `timeoutMs` for another + * holder (polling, a heartbeat line every `heartbeatMs` through `onWait`), then throws with the holder. + */ +export async function withMachineLock(key: string, command: string, fn: () => Promise, + o: { timeoutMs?: number; pollMs?: number; heartbeatMs?: number; onWait?: (msg: string) => void } = {}): Promise { + if (inside.getStore()?.has(key)) return fn(); + const dir = machineLockDir(); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const path = join(dir, `${key.replace(/[^A-Za-z0-9._-]+/g, '_')}.lock`); + const timeout = o.timeoutMs ?? 90_000, poll = o.pollMs ?? 100, beat = o.heartbeatMs ?? 10_000; + const start = Date.now(); + let lastBeat = start; + for (;;) { + try { + const fd = openSync(path, 'wx', 0o600); + writeSync(fd, JSON.stringify({ pid: process.pid, host: hostname(), command, startedAt: new Date().toISOString() } satisfies LockInfo) + '\n'); + closeSync(fd); + break; + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e; + let cur: LockInfo | null = null, touched = Date.now(); + try { touched = statSync(path).mtimeMs; cur = JSON.parse(readFileSync(path, 'utf8')) as LockInfo; } catch { /* gone or half written */ } + if (staleShortLock(cur, touched)) { rmSync(path, { force: true }); continue; } + const waited = Date.now() - start; + const who = cur ? `\`storebound ${cur.command}\` (pid ${cur.pid})` : 'another storebound run'; + if (waited > timeout) throw new Error(`timed out after ${Math.round(waited / 1000)} s waiting for ${key}: ${who} still holds it (Google Play allows one open edit per app). Try again when it is done.`); + if (Date.now() - lastBeat >= beat) { lastBeat = Date.now(); o.onWait?.(`waiting ${Math.round(waited / 1000)} s for ${key}, held by ${who}`); } + await sleep(poll); + } + } + held.add(path); + if (!hooked) { hooked = true; process.on('exit', () => { for (const p of held) rmSync(p, { force: true }); }); } + const hb = setInterval(() => { try { const t = new Date(); utimesSync(path, t, t); } catch { /* removed */ } }, 5000); + (hb as { unref?: () => void }).unref?.(); + try { return await inside.run(new Set([...(inside.getStore() ?? []), key]), fn); } finally { clearInterval(hb); rmSync(path, { force: true }); held.delete(path); } +} + /** Read-only subcommands and flags: no lock. */ const READ_SUBS = new Set(['status', 'list', 'devices', 'diff', 'export', 'pull', 'wait', 'options', 'coverage', 'report', 'campaigns', 'check', 'help']); diff --git a/cli/lib/play-public.ts b/cli/lib/play-public.ts index 36f0440..3f8efe2 100644 --- a/cli/lib/play-public.ts +++ b/cli/lib/play-public.ts @@ -1,7 +1,9 @@ // Is the app public on Google Play? The Play Developer API has no review state: a production release reads -// "completed" from the moment it is sent, while Google may still be reviewing it (a first release is not public -// until then). The public store page answers it: 200 = published, 404 = not public yet. No auth, a fast timeout, -// cached for a few minutes (in memory and in the temp folder, so short CLI runs share it), "unknown" when offline. +// "completed" from the moment it is sent, also while Google reviews it. The public store page answers it: 404 = not +// public yet (a first release in review), 200 = published, and the page's "Version" (About this app) is the live +// versionName, so a completed release whose versionName is not the page's is in review. No auth, a fast timeout, +// cached for a few minutes (in memory and in the temp folder, so short CLI runs share it). Only a network failure +// gives "unknown"; it then returns the last known answer (any age) marked `stale` with the time it was read. import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -11,25 +13,45 @@ export interface PlayPublicPage { state: PublicState; /** HTTP status of the store page (null when it could not be read). */ http: number | null; - /** The versionName the page shows, when it shows one (usually it does not). */ + /** The live versionName the page shows ("Version" in About this app); null when it shows none. */ versionName: string | null; + /** The page says "Varies with device" instead of a version (several APKs): the version cannot be compared. */ + varies?: boolean; + /** A network failure: this is the last known answer from `checkedAt`, not a fresh one. */ + stale?: boolean; checkedAt: string; url: string; error?: string; } -export const playPageUrl = (pkg: string): string => `https://play.google.com/store/apps/details?id=${encodeURIComponent(pkg)}&hl=en`; +export const playPageUrl = (pkg: string): string => `https://play.google.com/store/apps/details?id=${encodeURIComponent(pkg)}&hl=en&gl=US`; const TTL_MS = 5 * 60_000; const mem = new Map(); const cacheFile = (pkg: string): string => join(tmpdir(), 'storebound-play-public', `${pkg.replace(/[^\w.-]/g, '_')}.json`); +const lastFile = (pkg: string): string => join(tmpdir(), 'storebound-play-public', `${pkg.replace(/[^\w.-]/g, '_')}.last.json`); const fresh = (p: PlayPublicPage | undefined | null): p is PlayPublicPage => !!p && p.state !== 'unknown' && Date.now() - Date.parse(p.checkedAt) < TTL_MS; -/** The versionName in the page's structured data, when it has one ("softwareVersion"). */ -export function pageVersion(html: string): string | null { - const m = html.match(/"softwareVersion"\s*:\s*"([^"]{1,40})"/); - return m && /\d/.test(m[1]!) ? m[1]! : null; +/** + * The live versionName of a Play store page. The page embeds "About this app" in its AF_initDataCallback data blobs + * (ds:5 in 2026-10) as `[[["0.8.1"]],[[[36]],[[[24,"7.0"]]]]]`: the version, then the target and minimum SDK with the + * Android version. "Varies with device" stands in for the version when the app ships several APKs. Older pages had + * schema.org "softwareVersion". Recorded shape: tests/fixtures/play-page-version.html. + */ +export function pageVersionInfo(html: string): { versionName: string | null; varies: boolean } { + const blobs = [...html.matchAll(/AF_initDataCallback\(\{key: '(ds:\d+)'[\s\S]*?<\/script>/g)].map(m => m[0]); + const about = /\[\[\["([^"\\]{1,60})"\]\],\[\[\[\d+\]\],\[\[\[\d+,"[^"\\]{0,20}"\]\]\]\]/; + for (const b of blobs.length ? blobs : [html]) { + const m = about.exec(b); + if (!m) continue; + if (/varies with device/i.test(m[1]!)) return { versionName: null, varies: true }; + if (/\d/.test(m[1]!)) return { versionName: m[1]!, varies: false }; + } + const ld = html.match(/"softwareVersion"\s*:\s*"([^"]{1,40})"/); + if (ld && /varies with device/i.test(ld[1]!)) return { versionName: null, varies: true }; + return { versionName: ld && /\d/.test(ld[1]!) ? ld[1]! : null, varies: false }; } +export const pageVersion = (html: string): string | null => pageVersionInfo(html).versionName; /** Reads the public page (cached 5 minutes; STOREBOUND_PLAY_PUBLIC=public|notPublic|unknown overrides it for tests). */ export async function playPublicPage(pkg: string, o: { timeoutMs?: number; noCache?: boolean } = {}): Promise { @@ -46,7 +68,7 @@ export async function playPublicPage(pkg: string, o: { timeoutMs?: number; noCac try { const r = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(o.timeoutMs ?? 4000), headers: { 'User-Agent': 'Mozilla/5.0 storebound', 'Accept-Language': 'en' } }); const http = r.status; - if (http === 200) out = { state: 'public', http, versionName: pageVersion(await r.text()), checkedAt: new Date().toISOString(), url }; + if (http === 200) { const v = pageVersionInfo(await r.text()); out = { state: 'public', http, versionName: v.versionName, ...(v.varies ? { varies: true } : {}), checkedAt: new Date().toISOString(), url }; } else if (http === 404) out = { state: 'notPublic', http, versionName: null, checkedAt: new Date().toISOString(), url }; else out = { state: 'unknown', http, versionName: null, checkedAt: new Date().toISOString(), url, error: `HTTP ${http}` }; } catch (e) { @@ -54,8 +76,14 @@ export async function playPublicPage(pkg: string, o: { timeoutMs?: number; noCac } if (out.state !== 'unknown') { mem.set(pkg, out); - try { mkdirSync(join(tmpdir(), 'storebound-play-public'), { recursive: true }); writeFileSync(cacheFile(pkg), JSON.stringify(out)); } catch { /* cache is optional */ } + try { mkdirSync(join(tmpdir(), 'storebound-play-public'), { recursive: true }); writeFileSync(cacheFile(pkg), JSON.stringify(out)); writeFileSync(lastFile(pkg), JSON.stringify(out)); } catch { /* cache is optional */ } + return out; } + // a network failure: the last known answer with its time, never a guess + try { + const last = JSON.parse(readFileSync(lastFile(pkg), 'utf8')) as PlayPublicPage; + if (last.url === url && last.state !== 'unknown') return { ...last, stale: true, error: out.error }; + } catch { /* none known */ } return out; } diff --git a/cli/lib/portfolio.ts b/cli/lib/portfolio.ts index 5995344..38bf4a1 100644 --- a/cli/lib/portfolio.ts +++ b/cli/lib/portfolio.ts @@ -105,20 +105,22 @@ export function testflightReleases(builds: J[], buildVersions: Record (typeof name === 'string' ? name.match(/\d+(?:\.\d+){0,3}/)?.[0] ?? null : null); /** - * Play tracks (`play status --json`) -> releases. The Developer API has no review state: a completed production release - * is only "live" when the public store page proves it (`publicPage` in the status JSON): 404 = sent to Google (in - * review or not yet published); 200 = live for the first release or when the page shows this versionName, otherwise - * "released" (an update Google may still be reviewing); page not read = "released" with publicPage unknown. + * Play tracks (`play status --json`) -> releases. The Developer API has no review state, so a completed production + * release is decided by the public store page (`publicPage` in the status JSON): the page's version is this versionName + * (or newer, or "Varies with device") = live; 404 = in review (with managed publishing: in review or ready to publish); + * an older version on the page = in review, with the live one named. Only a network failure without any earlier page + * read leaves it undecided ("released", publicPage unknown: "Couldn't check the store page"); with an earlier read the + * phase comes from that read and `pageStaleAt` says when. */ export function playReleases(data: unknown): StoreRelease[] { const out: StoreRelease[] = []; - const page = (data as J)?.publicPage as { state?: string; versionName?: string | null } | undefined; + const page = (data as J)?.publicPage as { state?: string; versionName?: string | null; varies?: boolean; stale?: boolean; checkedAt?: string } | undefined; + const managed = (data as J)?.managedPublishing === true; const pageState = page?.state === 'public' || page?.state === 'notPublic' ? page.state : 'unknown'; const raw = (data as J)?.tracks; const tracks: J[] = Array.isArray(raw) ? raw : []; const codesOf = (r: J): number[] => (Array.isArray(r?.versionCodes) ? (r.versionCodes as unknown[]) : []).map(Number).filter(Number.isFinite); const rels = (t: J): J[] => (Array.isArray(t?.releases) ? t.releases : []); - const allCodes = tracks.flatMap(t => rels(t).flatMap(codesOf)); for (const t of tracks) { for (const r of rels(t)) { const codes = codesOf(r); @@ -129,12 +131,17 @@ export function playReleases(data: unknown): StoreRelease[] { rel.phase = !production ? (status === 'draft' ? 'draft' : 'testing') : status === 'inProgress' ? 'rollout' : status === 'halted' ? 'halted' : status === 'draft' ? 'draft' : 'other'; if (production && status === 'completed') { - const low = codes.length ? Math.min(...codes) : Infinity; - const first = !allCodes.some(c => c < low); // nothing older on any track: the app's first release - rel.phase = pageState === 'notPublic' ? 'sent' - : pageState === 'public' && (first || sameVersion(page?.versionName, version)) ? 'live' - : 'released'; + const pv = page?.versionName ?? null; + if (pageState === 'notPublic') { rel.phase = 'review'; if (managed) rel.managed = true; } + else if (pageState === 'public') { + // its version (or newer: this is an earlier one), or "Varies with device" (nothing to compare) = live; no + // version found on a public page means the page changed shape: not checked, never guessed + if (page?.varies || (pv && version && cmpVersion(pv, version) >= 0)) rel.phase = 'live'; + else if (!pv || !version) rel.phase = 'released'; + else { rel.phase = 'review'; rel.liveVersion = pv; if (managed) rel.managed = true; } + } else rel.phase = 'released'; rel.publicPage = pageState; + if (page?.stale && pageState !== 'unknown') rel.pageStaleAt = page.checkedAt ?? null; } out.push(rel); } @@ -142,12 +149,19 @@ export function playReleases(data: unknown): StoreRelease[] { return out; } -/** Plain words for a Play production release's phase (CLI text; the desktop has the same words in i18n). */ +/** Plain words for a Play release's phase, decided from the store page (CLI text; the desktop has the same words in + * i18n, apps/desktop/src/ui/kit.tsx phaseLabel). */ export function playReleaseLabel(r: StoreRelease): string { - if (r.phase === 'sent') return 'Sent to Google (in review or not yet published)'; - if (r.phase === 'released') return r.publicPage === 'unknown' ? 'Released to production (public store page not readable: live state unknown)' : 'Released to production (Google may still be reviewing)'; - if (r.phase === 'live') return 'Live'; - return r.state; + const base = ((): string => { + if (r.phase === 'review' || r.phase === 'sent') return r.managed ? 'In review / ready to publish (managed publishing)' : r.liveVersion ? `In review (live: ${r.liveVersion})` : 'In review'; + if (r.phase === 'released') return "Couldn't check the store page"; + if (r.phase === 'live') return 'Live'; + if (r.phase === 'rollout') return `Rolling out ${Math.round((r.fraction ?? 0) * 1000) / 10}%`; + if (r.phase === 'halted') return 'Halted'; + if (r.phase === 'draft') return 'Draft'; + return r.state; + })(); + return r.pageStaleAt ? `${base} (couldn't check the store page now; as of ${r.pageStaleAt.slice(0, 16).replace('T', ' ')} UTC)` : base; } export const PHASE_RANK: Record = { live: 0, rollout: 1, halted: 2, released: 3, approved: 4, review: 5, sent: 6, rejected: 7, testing: 8, draft: 9, other: 10 }; diff --git a/cli/lib/train.ts b/cli/lib/train.ts index 0cb0f3b..7ed5bae 100644 --- a/cli/lib/train.ts +++ b/cli/lib/train.ts @@ -3,8 +3,8 @@ // re-exports these) and `storebound release status | plan` (cli/release.ts) share this file, so both show the same // stage for the same store state. Pure; the store reads are `apple status --json` / `play status --json`, turned into // StoreRelease rows by cli/lib/portfolio.ts. -import type { ReleaseTrain, StoreRelease } from './desktop-protocol'; -import { cmpVersion, displayVersion, PHASE_RANK, REACHING, sameVersion, versionKey } from './portfolio'; +import type { AppStatus, ReleaseTrain, StoreRelease } from './desktop-protocol'; +import { cmpVersion, displayVersion, PHASE_RANK, playReleaseLabel, REACHING, releaseTrains, sameVersion, versionKey } from './portfolio'; import type { Finding } from './validate-rules'; export { cmpVersion, displayVersion, sameVersion, versionKey }; @@ -75,6 +75,54 @@ export function storeNow(all: StoreRelease[], store: 'ios' | 'android'): { now: return { now, next }; } +/** + * What a lane without this version shows, so a store is never called empty when it was not read or carries another + * version: `unreadable` (the read failed and nothing is known: "couldn't read Google Play"), `other` (the store's own + * current release is a different version: "4.1.2 · Live (4.1.9 not submitted)"), `missing` (the app is on the store, + * this version is not yet) and `none` (no record of the app on that store at all: "Not on this store"). Pure. + */ +export type LaneGap = { kind: 'unreadable' } | { kind: 'other'; now: StoreRelease & { version: string } } | { kind: 'missing' } | { kind: 'none' }; +export function laneGap(store: 'ios' | 'android', all: StoreRelease[], storeError?: string | null): LaneGap { + const mine = all.filter(r => r.store === store); + if (!mine.length) return storeError ? { kind: 'unreadable' } : { kind: 'none' }; + const { now } = storeNow(all, store); + if (now) return { kind: 'other', now: now as StoreRelease & { version: string } }; + return { kind: 'missing' }; +} + +/** The stores' current (reaching users) versions when they differ: "Play 4.1.9 · App Store 4.1.2" for a neutral + * header. Null when only one store has one or both have the same version. Pure. */ +export function storesDiffer(all: StoreRelease[]): { ios: string; android: string } | null { + const i = storeNow(all, 'ios').now?.version, a = storeNow(all, 'android').now?.version; + return i && a && !sameVersion(i, a) ? { ios: i, android: a } : null; +} + +/** + * After a refresh in which a store could not be read, keep the store's releases from the previous good read (marked + * by `staleStores`), so the lanes show the last known state with "couldn't refresh" instead of turning empty. Pure. + */ +export function keepLastGood(prev: StoreRelease[] | undefined, next: StoreRelease[], errors: { ios?: string; android?: string }): { all: StoreRelease[]; stale: ('ios' | 'android')[] } { + const stale: ('ios' | 'android')[] = []; + let all = next; + for (const s of ['ios', 'android'] as const) { + if (!errors[s] || next.some(r => r.store === s)) continue; + const old = (prev ?? []).filter(r => r.store === s); + if (old.length) { all = [...all, ...old]; stale.push(s); } + } + return { all, stale }; +} + +/** keepLastGood over a whole status: the app's trains are rebuilt from the merged releases and `staleStores` names + * each store shown from the earlier read (with that read's time). Returns `next` itself when nothing is kept. */ +export function withLastGood(prev: AppStatus | undefined, next: AppStatus, prevAt: string): AppStatus { + if (next.release.source !== 'live' || !prev?.release.all?.length) return next; + const { all, stale } = keepLastGood(prev.release.all, next.release.all ?? [], next.storeErrors); + if (!stale.length) return next; + const staleStores = { ...next.staleStores }; + for (const s of stale) staleStores[s] = prev.staleStores?.[s] ?? prevAt; + return { ...next, release: { source: 'live', ...releaseTrains(all.filter(r => r.store === 'ios'), all.filter(r => r.store === 'android')), all }, staleStores }; +} + // ---- Terminal view of a lane (release status) ---- const pctText = (x: number | null): string => (x === null ? '' : `${Math.round(x * 1000) / 10}%`); @@ -85,8 +133,7 @@ export function laneText(l: Lane): string { const stage = STAGES[l.at] ?? 'build'; const p = l.release.phase; if (p === 'live') return 'live'; // the whole track filled: everyone has it - if (p === 'sent') return 'review (sent to Google: in review or not yet published)'; - if (p === 'released') return l.release.publicPage === 'unknown' ? 'released to production (public page not readable: live unknown)' : 'released to production (Google may still be reviewing)'; + if (l.release.store === 'android' && (p === 'sent' || p === 'released' || (p === 'review' && l.release.track === 'production'))) return playReleaseLabel(l.release).replace(/^\w/, c => c.toLowerCase()); const word = p === stage || (p === 'draft' && stage === 'build') || (p === 'other' && stage === 'build') ? stage : `${stage} (${p})`; if (p === 'rollout' || p === 'halted') return `${word} ${pctText(l.share)}`.trim(); return word; @@ -184,12 +231,14 @@ function storeSteps(store: 'ios' | 'android', v: string, r: StoreRelease | null, steps.push({ kind: 'owner', text: `resubmit ${v} after the fix (owner)`, fix: store === 'ios' ? 'App Store Connect > App Review > reply / resubmit' : 'Play Console > Publishing overview' }); break; case 'sent': - steps.push({ kind: 'wait', text: `${v} is sent to Google (production completed, the store page is not public yet): in review or not yet published`, fix: 'storebound play status (checks the public store page)' }); - break; case 'released': - steps.push({ kind: 'wait', text: r!.publicPage === 'unknown' ? `${v} is released to production; the public store page could not be read, so live is unknown` : `${v} is released to production; Google may still be reviewing it (the app is public, this version is not proven live)`, fix: 'storebound play status' }); + steps.push({ kind: 'wait', text: `${v}: ${playReleaseLabel(r!)}`, fix: 'storebound play status (reads the public store page)' }); break; case 'review': + if (store === 'android' && r!.track === 'production') { + steps.push({ kind: r!.managed ? 'owner' : 'wait', text: `${v}: ${playReleaseLabel(r!)}`, fix: r!.managed ? 'Play Console > Publishing overview (publish once approved)' : 'storebound play status' }); + break; + } steps.push({ kind: 'wait', text: `${v} is in review (${r!.state}); nothing to do until the store answers`, fix: store === 'ios' ? 'storebound apple status --wait-review' : 'storebound play status' }); break; case 'approved': diff --git a/cli/play/client.ts b/cli/play/client.ts index 219060f..2b4fae7 100644 --- a/cli/play/client.ts +++ b/cli/play/client.ts @@ -6,6 +6,10 @@ import { errorBody } from '../lib/http'; import { noteGoogle } from '../lib/quota'; import { AmbiguousWriteError, isAmbiguous, retrySafe } from '../lib/upsert'; import * as rt from '../lib/rt'; +import { withMachineLock } from '../lib/lock'; + +/** A read's edit is gone: replaced by a newer edit of the app, committed elsewhere or expired. */ +export const EDIT_GONE = /Edit has been deleted|editAlreadyCommitted|already been committed|edit.*(expired|not found)|outside of this Edit/i; export type PlayClient = Awaited>; @@ -101,6 +105,11 @@ export async function playClient(root: string, packageName: string) { } } + /** Google keeps one open edit per app; every edit (read or write) of this package, in any storebound process on + * this machine, runs under one lock (cli/lib/lock.ts), so parallel reads never delete each other's edits. */ + const locked = (what: string, fn: () => Promise, timeoutMs: number): Promise => + withMachineLock(`play-edit-${packageName}`, `play ${what} ${packageName}`, fn, { timeoutMs, onWait: m => log('play', m) }); + return { API, UPLOAD, packageName, call, /** @@ -108,8 +117,16 @@ export async function playClient(root: string, packageName: string) { * A failed delete is reported (Play drops an unused edit on its own after a while, but it should not linger). */ async read(fn: (id: string) => Promise): Promise { - const id = await openOne(); - try { return await fn(id); } finally { await closeOne(id, 'read-only'); } + return locked('read', async () => { + for (let attempt = 0; ; attempt++) { + const id = await openOne(); + try { return await fn(id); } catch (err) { + // the edit was replaced by another writer (Console, another tool) or expired: a read is safe to redo once + if (attempt === 0 && EDIT_GONE.test(String(err))) { log('play', `read edit ${id} was invalidated, reading again with a new edit`); continue; } + throw err; + } finally { await closeOne(id, 'read-only'); } + } + }, 90_000); }, /** * Opens an edit, runs fn, then commits (or validates and discards when dry). Any Console save or other edit commit @@ -117,6 +134,7 @@ export async function playClient(root: string, packageName: string) { * redone, up to `retries` times. Keep edits small (e.g. one per language for images) so a retry is cheap. */ async edit(fn: (id: string, ctl: EditCtl) => Promise, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise { + return locked(o.dry ? 'dry edit' : 'edit', async () => { for (let left = o.retries ?? 3; ; left--) { try { return await editOnce(fn, o); } catch (err) { // redo only what never went live: an edit invalidated before or at its commit, or a request inside the edit @@ -127,6 +145,7 @@ export async function playClient(root: string, packageName: string) { log('play', `${outside ? 'app changed outside the edit (Console?)' : 'a request got no clear answer; the edit was discarded'}, redoing it (${left} retries left)`); } } + }, 10 * 60_000); }, }; } diff --git a/cli/play/status.ts b/cli/play/status.ts index cfba96d..435c1f4 100644 --- a/cli/play/status.ts +++ b/cli/play/status.ts @@ -22,7 +22,7 @@ export async function run(ctx: Ctx): Promise { // the App category is not in the API (edits.details has no category field): a console step const cat = playCategoryOf(config); const category = { config: cat?.category ?? null, source: cat?.source ?? null, api: false, plan: 'storebound console plan play-store-settings' }; - if (ctx.args.has('json')) { printJson({ details, category, tracks, listings, products, publicPage }); return; } + if (ctx.args.has('json')) { printJson({ details, category, tracks, listings, products, publicPage, managedPublishing: config.play?.managedPublishing ?? null }); return; } console.log(`${play.packageName}\n details: ${details.defaultLanguage} · ${details.contactEmail ?? '-'} · ${details.contactWebsite ?? '-'}`); console.log(` category: ${cat ? `${cat.category} (${cat.source})` : 'not in the config (play.category)'} · not readable by the API: Store settings is a console step (${category.plan})`); console.log(` listings (${listings.length}): ${listings.map(l => l.language).join(', ') || '-'}`); @@ -30,8 +30,8 @@ export async function run(ctx: Ctx): Promise { const rs = (t.releases ?? []).map(r => `${r.name ?? '?'} [${r.versionCodes?.join(',') ?? '-'}] ${r.status}${r.userFraction ? ' ' + r.userFraction * 100 + '%' : ''}`); console.log(` track ${t.track.padEnd(11)} ${rs.join(' | ') || '-'}`); } - console.log(` public store page: ${publicPage.state === 'public' ? 'published (200)' : publicPage.state === 'notPublic' ? 'not public yet (404)' : `unknown (${publicPage.error ?? 'not read'})`}`); - for (const r of playReleases({ tracks, publicPage }).filter(x => x.track === 'production' && x.state === 'completed')) console.log(` production ${r.version ?? '?'} (${r.build ?? '?'}): ${playReleaseLabel(r)}`); + console.log(` public store page: ${publicPage.state === 'public' ? `published (200), live version ${publicPage.versionName ?? (publicPage.varies ? 'varies with device' : 'not shown')}` : publicPage.state === 'notPublic' ? 'not public yet (404)' : `couldn't check it (${publicPage.error ?? 'not read'})`}${publicPage.stale ? ` (last known, ${publicPage.checkedAt.slice(0, 16).replace('T', ' ')} UTC)` : ''}`); + for (const r of playReleases({ tracks, publicPage, managedPublishing: config.play?.managedPublishing ?? null }).filter(x => x.track === 'production')) console.log(` production ${r.version ?? '?'} (${r.build ?? '?'}): ${playReleaseLabel(r)}`); console.log(` products (${products.length}):`); for (const p of products) console.log(` ${p.productId.padEnd(40)} ${(p.purchaseOptions ?? []).map(o => `${o.purchaseOptionId}:${o.state ?? '?'}`).join(' ')}`); }); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index aceceb3..8c42949 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -653,9 +653,11 @@ that fails without the fix (see CONTRIBUTING.md). ## 56. "Live on Play" while Google was still reviewing, and 1.0 / 1.0.0 shown as two versions - **Do:** never call a Google Play production release live from the Developer API alone: a release reads `completed` (userFraction 1) from the moment it is sent, also while Google reviews the first release. `play status` checks the - public store page (no auth, 4 s timeout, cached 5 minutes): 404 = "Sent to Google (in review or not yet - published)"; 200 = live for the first release (or when the page shows the same versionName), otherwise "Released to - production (Google may still be reviewing)"; offline = unknown, shown as unknown. Match versions across the stores + public store page (no auth, 4 s timeout, cached 5 minutes) and decides, never "maybe": the page's "Version" (About + this app, read from its AF_initDataCallback data) equals the release's versionName = "Live"; 404 = "In review" (with + play.managedPublishing: "In review / ready to publish (managed publishing)"); an older version on the page = "In + review (live: )"; "Varies with device" = live. Only a network failure gives "Couldn't check the store page", + and then the last known page answer is used with its time. Match versions across the stores by `versionKey` (trailing .0 parts dropped: 1 == 1.0 == 1.0.0); show each store's own string. - **Guard:** `playPublicPage` (`cli/lib/play-public.ts`), `playReleases` / `versionKey` / `sameVersion` (`cli/lib/portfolio.ts`), `versionHistory` (`cli/lib/train.ts`), `tests/play-public-version-match.test.ts`, the @@ -671,3 +673,18 @@ that fails without the fix (see CONTRIBUTING.md). findings; a real failure shows the command's own error line, never a bare exit code. - **Guard:** `cli/lib/google-errors.ts`, `outcomeOf` / `errorLine` (`cli/lib/desktop-protocol.ts`), `tests/google-errors.test.ts`, the desktop boot check's `errors` cases (api-disabled, scan-findings, scan-failed). + +## 58. Parallel Play reads deleted each other's edits, and a failed read said "not on Google Play yet" +- **Do:** Google Play keeps one open edit per app: a second `edits.insert` for the same package deletes the first, so a + read in it answers 400 "This Edit has been deleted". Every edit (read or write) of a package takes the machine-wide + lock `~/.storebound/locks/play-edit-.lock` (short wait with a heartbeat log, 90 s timeout for reads, 10 min + for writes; stale when its process is gone or untouched for a minute); other packages stay parallel. A read whose + edit was deleted, committed elsewhere or expired is redone once with a new edit; a write is never redone that way + (it keeps its own invalidation retry). A store that could not be read is "couldn't read Google Play" (unknown), + never "not on Google Play yet"; its last good releases stay with "couldn't refresh". When the stores' current + versions differ (normal), each lane shows its own ("4.1.2 · Live (4.1.9 not submitted)") under a neutral "Current" + header; "Not on this store" only when the store has no record of the app. +- **Guard:** `withMachineLock` (`cli/lib/lock.ts`), `read()` / `edit()` (`cli/play/client.ts`), + `laneGap` / `storesDiffer` / `withLastGood` (`cli/lib/train.ts`), `tests/play-edit-lock.test.ts` (a fake Play where a + second insert invalidates the first), the desktop boot check's auto-read case (two Play reads of one app at once, + Orbit Hop on different versions per store). diff --git a/tests/fixtures/play-page-version.html b/tests/fixtures/play-page-version.html new file mode 100644 index 0000000..e659a0c --- /dev/null +++ b/tests/fixtures/play-page-version.html @@ -0,0 +1,7 @@ +Example Game - Apps on Google Play + + + + + diff --git a/tests/helpers/preload.ts b/tests/helpers/preload.ts index 63e4f07..9fe5d67 100644 --- a/tests/helpers/preload.ts +++ b/tests/helpers/preload.ts @@ -13,6 +13,7 @@ process.env.STOREBOUND_LIST_SETTLE_MS ??= '0'; const machine = mkdtempSync(join(tmpdir(), 'storebound-machine-')); process.env.STOREBOUND_CREDENTIALS_DIR = join(machine, 'credentials'); process.env.STOREBOUND_REGISTRY = join(machine, 'projects.json'); +process.env.STOREBOUND_LOCK_DIR = join(machine, 'locks'); // Commands run in-process set process.exitCode on purpose (a check with problems, a declined confirmation: // DECLINED_EXIT in cli/lib/ctx.ts). Tests assert it where it matters; it must not leak into bun test's own exit code. diff --git a/tests/play-edit-lock.test.ts b/tests/play-edit-lock.test.ts new file mode 100644 index 0000000..bd6653b --- /dev/null +++ b/tests/play-edit-lock.test.ts @@ -0,0 +1,135 @@ +// Google Play keeps one open edit per app: a second edits.insert for the same package deletes the first, and a read in +// the first edit then answers 400 "This Edit has been deleted." (seen live when the desktop's auto-read ran several Play +// reads of one app at once). The fake below does exactly that; parallel reads of one package must all succeed, other +// packages must still run in parallel, and a read whose edit was replaced is redone once with a new edit. +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { generateKeyPairSync } from 'node:crypto'; +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { playClient } from '../cli/play/client'; +import { withMachineLock } from '../cli/lib/lock'; +import { laneGap, storesDiffer, withLastGood } from '../cli/lib/train'; +import type { AppStatus, StoreRelease } from '../cli/lib/desktop-protocol'; + +const realFetch = globalThis.fetch; +const saved = process.env.PLAY_SERVICE_ACCOUNT; +afterEach(() => { globalThis.fetch = realFetch; if (saved === undefined) delete process.env.PLAY_SERVICE_ACCOUNT; else process.env.PLAY_SERVICE_ACCOUNT = saved; }); +const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); +const KEY = JSON.stringify({ client_email: 'sb@example.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' }); + +beforeEach(() => { process.env.PLAY_SERVICE_ACCOUNT = KEY; }); +const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } }); +const DELETED = { error: { code: 400, message: 'This Edit has been deleted.', status: 'INVALID_ARGUMENT' } }; +const wait = (ms: number) => new Promise(r => setTimeout(r, ms)); + +/** Fake androidpublisher: one open edit per package; an insert replaces it. Counts the edits open at once per package. */ +function fakePlay(o: { delay?: number; replaceOnce?: string } = {}) { + const open = new Map(); + let n = 0; + const peak = { total: 0, now: 0 }; + let replaced = false; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input); + const method = init?.method ?? 'GET'; + if (url.includes('oauth2')) return json({ access_token: 't', expires_in: 3600 }); + const m = /applications\/([^/]+)\/edits(?:\/([^/:]+))?(\/.*)?$/.exec(url); + if (!m) return json({}, 404); + const [, pkg, id, rest] = m as unknown as [string, string, string | undefined, string | undefined]; + if (method === 'POST' && !id) { + const e = `e${++n}`; open.set(pkg, e); + peak.now++; peak.total = Math.max(peak.total, peak.now); + return json({ id: e }); + } + if (method === 'DELETE') { peak.now--; if (open.get(pkg) === id) open.delete(pkg); return json({}); } + await wait(o.delay ?? 15); + if (o.replaceOnce === pkg && !replaced) { replaced = true; open.set(pkg, `e${++n}`); } // e.g. a Console save + if (open.get(pkg) !== id) return json(DELETED, 400); + return json({ ok: rest ?? '' }); + }) as typeof fetch; + return peak; +} + +describe('Play edits: one open edit per package', () => { + test('the fake is faithful: two edits of one package without the lock kill the first', async () => { + fakePlay(); + const ids: string[] = []; + const call = async (pkg: string) => { const r = await realFetchless(pkg); ids.push(r); }; + async function realFetchless(pkg: string): Promise { + const e = await (await fetch(`https://x/applications/${pkg}/edits`, { method: 'POST' })).json() as { id: string }; + await wait(5); + const r = await fetch(`https://x/applications/${pkg}/edits/${e.id}/details`); + return String(r.status); + } + await Promise.all([call('com.example.a'), call('com.example.a')]); + expect(ids.sort()).toEqual(['200', '400']); + }); + + test('parallel reads of one package all succeed (serialized)', async () => { + const peak = fakePlay(); + const play = [await playClient('/nonexistent', 'com.example.demo'), await playClient('/nonexistent', 'com.example.demo'), await playClient('/nonexistent', 'com.example.demo'), await playClient('/nonexistent', 'com.example.demo')]; + const out = await Promise.all(play.map(p => p.read(async id => { + const a = await p.call<{ ok: string }>('GET', `${p.API}/edits/${id}/details`); + const b = await p.call<{ ok: string }>('GET', `${p.API}/edits/${id}/tracks`); + return [a.ok, b.ok]; + }))); + expect(out).toEqual(Array(4).fill(['/details', '/tracks'])); + expect(peak.total).toBe(1); + }); + + test('different packages still read in parallel', async () => { + const peak = fakePlay({ delay: 40 }); + const pkgs = ['com.example.a', 'com.example.b', 'com.example.c']; + const started = Date.now(); + const out = await Promise.all(pkgs.map(async pkg => { const p = await playClient('/nonexistent', pkg); return p.read(id => p.call<{ ok: string }>('GET', `${p.API}/edits/${id}/details`)); })); + expect(out.map(o => o.ok)).toEqual(['/details', '/details', '/details']); + expect(peak.total).toBe(3); + expect(Date.now() - started).toBeLessThan(40 * 3); + }); + + test('a read whose edit was deleted is redone once with a new edit', async () => { + fakePlay({ replaceOnce: 'com.example.demo' }); + const p = await playClient('/nonexistent', 'com.example.demo'); + const seen: string[] = []; + const r = await p.read(async id => { seen.push(id); return p.call<{ ok: string }>('GET', `${p.API}/edits/${id}/details`); }); + expect(r.ok).toBe('/details'); + expect(seen.length).toBe(2); + expect(seen[0]).not.toBe(seen[1]); + }); + + test('a lock held by another holder times out with who holds it', async () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-lock-')); + const prev = process.env.STOREBOUND_LOCK_DIR; + process.env.STOREBOUND_LOCK_DIR = dir; + try { + const beats: string[] = []; + let release!: () => void; + const first = withMachineLock('play-edit-x', 'play read x', () => new Promise(r => { release = r; })); + await wait(10); + await expect(withMachineLock('play-edit-x', 'play read x', async () => 1, { timeoutMs: 60, pollMs: 10, heartbeatMs: 20, onWait: m => beats.push(m) })).rejects.toThrow(/timed out .*play read x/); + expect(beats.length).toBeGreaterThan(0); + release(); await first; + expect(await withMachineLock('play-edit-x', 'play read x', async () => 2, { timeoutMs: 100 })).toBe(2); + } finally { if (prev === undefined) delete process.env.STOREBOUND_LOCK_DIR; else process.env.STOREBOUND_LOCK_DIR = prev; } + }); +}); + +describe('a store that could not be read is unknown, never empty', () => { + const r = (store: 'ios' | 'android', version: string, phase: StoreRelease['phase']): StoreRelease => ({ store, version, build: '1', state: 's', phase, fraction: null, track: store === 'android' ? 'production' : null }); + test("laneGap: unreadable, the store's own other version, missing, none", () => { + expect(laneGap('android', [r('ios', '0.8.1', 'live')], '400 This Edit has been deleted.').kind).toBe('unreadable'); + expect(laneGap('ios', [r('ios', '4.1.2', 'live'), r('android', '4.1.9', 'live')])).toMatchObject({ kind: 'other', now: { version: '4.1.2' } }); + expect(laneGap('ios', [r('ios', '1.0', 'review')]).kind).toBe('missing'); + expect(laneGap('ios', [r('android', '1.0', 'live')]).kind).toBe('none'); + expect(storesDiffer([r('ios', '4.1.2', 'live'), r('android', '4.1.9', 'live')])).toEqual({ ios: '4.1.2', android: '4.1.9' }); + expect(storesDiffer([r('ios', '4.1', 'live'), r('android', '4.1.0', 'live')])).toBeNull(); + }); + test('withLastGood keeps the last good Play releases with their time after a failed refresh', () => { + const prev = { release: { source: 'live', current: null, next: null, all: [r('ios', '0.8.1', 'live'), r('android', '0.8.1', 'live')] }, storeErrors: {} } as unknown as AppStatus; + const next = { release: { source: 'live', current: null, next: null, all: [r('ios', '0.8.1', 'live')] }, storeErrors: { android: 'GET /edits/x/details -> 400 This Edit has been deleted.' } } as unknown as AppStatus; + const m = withLastGood(prev, next, '2026-10-13T10:00:00Z'); + expect(m.staleStores).toEqual({ android: '2026-10-13T10:00:00Z' }); + expect(m.release.current).toMatchObject({ version: '0.8.1', android: { phase: 'live' } }); + expect(withLastGood(undefined, next, 'x')).toBe(next); + }); +}); diff --git a/tests/play-public-version-match.test.ts b/tests/play-public-version-match.test.ts index 7321826..647850e 100644 --- a/tests/play-public-version-match.test.ts +++ b/tests/play-public-version-match.test.ts @@ -4,7 +4,9 @@ import { afterEach, describe, expect, test } from 'bun:test'; import { APPLE_STATUS_FIRST_REVIEW, PLAY_STATUS_FIRST_200, PLAY_STATUS_FIRST_404 } from '../apps/desktop/src/dev/submit-fixtures'; import { trainsOf } from '../cli/release'; -import { clearPlayPublicCache, pageVersion, playPublicPage } from '../cli/lib/play-public'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { clearPlayPublicCache, pageVersion, pageVersionInfo, playPublicPage } from '../cli/lib/play-public'; import { appleReleases, playReleaseLabel, playReleases, releaseTrains, sameVersion, versionKey } from '../cli/lib/portfolio'; import { laneOf, laneText, releasePlan, storeNow, versionHistory } from '../cli/lib/train'; @@ -31,10 +33,10 @@ describe('version matching across the stores', () => { expect(h).toHaveLength(1); expect(h[0]!.version).toBe('1.0.0'); expect(h[0]!.ios).toMatchObject({ version: '1.0', build: '3', phase: 'review' }); - expect(h[0]!.android).toMatchObject({ version: '1.0.0', build: '3', phase: 'sent', track: 'production' }); + expect(h[0]!.android).toMatchObject({ version: '1.0.0', build: '3', phase: 'review', track: 'production' }); const t = releaseTrains(ios, android); expect(t.current).toBeNull(); // nothing reaches users yet - expect(t.next).toMatchObject({ version: '1.0.0', ios: { version: '1.0', phase: 'review' }, android: { version: '1.0.0', phase: 'sent' } }); + expect(t.next).toMatchObject({ version: '1.0.0', ios: { version: '1.0', phase: 'review' }, android: { version: '1.0.0', phase: 'review' } }); // release status --versions: the one row is the next train const s = { release: { source: 'live' as const, ...t, all }, storeErrors: {}, summary: null } as never; expect(trainsOf(s, true).map(x => [x.which, x.train.version])).toEqual([['next', '1.0.0']]); @@ -43,15 +45,15 @@ describe('version matching across the stores', () => { expect(p.ios?.release?.version).toBe('1.0'); expect(p.android?.release?.version).toBe('1.0.0'); expect(p.done).toBe(false); - expect(p.android!.steps.map(x => x.text).join(' ')).toContain('sent to Google'); + expect(p.android!.steps.map(x => x.text).join(' ')).toContain('1.0: In review'); }); }); describe('Google Play "Live" needs the public store page', () => { - test('completed production + page 404 = sent to Google, never live', () => { + test('completed production + page 404 = in review, never live', () => { const [prod] = playReleases(PLAY_STATUS_FIRST_404); - expect(prod).toMatchObject({ phase: 'sent', state: 'completed', publicPage: 'notPublic', fraction: 1 }); - expect(playReleaseLabel(prod!)).toBe('Sent to Google (in review or not yet published)'); + expect(prod).toMatchObject({ phase: 'review', state: 'completed', publicPage: 'notPublic', fraction: 1 }); + expect(playReleaseLabel(prod!)).toBe('In review'); const lane = laneOf('android', prod!); expect(lane.at).toBe(2); // the review stage, not live / rollout expect(lane.share).toBeNull(); @@ -65,22 +67,46 @@ describe('Google Play "Live" needs the public store page', () => { const t = releaseTrains(appleReleases(APPLE_STATUS_FIRST_REVIEW), playReleases(PLAY_STATUS_FIRST_200)); expect(t.current).toMatchObject({ version: '1.0.0', android: { phase: 'live' }, ios: { phase: 'review' } }); }); - test('an update after the first release: page 200 is not proof for the new versionCode unless the page shows it', () => { - const update = { publicPage: { state: 'public', versionName: null }, tracks: [ - { track: 'production', releases: [{ name: '1.1.0', versionCodes: ['5'], status: 'completed' }] }, - { track: 'internal', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed' }] }, - ] }; - const [prod] = playReleases(update); - expect(prod!.phase).toBe('released'); - expect(playReleaseLabel(prod!)).toBe('Released to production (Google may still be reviewing)'); - expect(laneText(laneOf('android', prod!))).toContain('Google may still be reviewing'); - expect(playReleases({ ...update, publicPage: { state: 'public', versionName: '1.1' } })[0]!.phase).toBe('live'); + const prodRel = (page: Record | undefined, name = '1.1.0', status = 'completed', extra: Record = {}) => playReleases({ ...extra, publicPage: page, tracks: [ + { track: 'production', releases: [{ name, versionCodes: ['5'], status, userFraction: status === 'completed' ? undefined : 0.2 }] }, + { track: 'internal', releases: [{ name: '1.0.0', versionCodes: ['3'], status: 'completed' }] }, + ] })[0]!; + test('rule: page version = the release version: Live', () => { + const r = prodRel({ state: 'public', versionName: '1.1' }); + expect(r.phase).toBe('live'); + expect(playReleaseLabel(r)).toBe('Live'); }); - test('page not read = unknown, shown as unknown', () => { - const [prod] = playReleases({ tracks: PLAY_STATUS_FIRST_404.tracks }); - expect(prod).toMatchObject({ phase: 'released', publicPage: 'unknown' }); - expect(playReleaseLabel(prod!)).toContain('unknown'); - expect(laneOf('android', prod!).tone).toBe('neutral'); + test('rule: page 404, managed publishing off: In review; on: In review / ready to publish', () => { + expect(playReleaseLabel(prodRel({ state: 'notPublic', versionName: null }))).toBe('In review'); + expect(playReleaseLabel(prodRel({ state: 'notPublic', versionName: null }, '1.1.0', 'completed', { managedPublishing: true }))).toBe('In review / ready to publish (managed publishing)'); + }); + test('rule: page live with an older version: In review (live: )', () => { + const r = prodRel({ state: 'public', versionName: '1.0.0' }); + expect(r).toMatchObject({ phase: 'review', liveVersion: '1.0.0' }); + expect(playReleaseLabel(r)).toBe('In review (live: 1.0.0)'); + expect(laneText(laneOf('android', r))).toBe('in review (live: 1.0.0)'); + expect(storeNow([r], 'android').now).toBeNull(); + }); + test('rule: rollout, halted, draft', () => { + expect(playReleaseLabel(prodRel({ state: 'public', versionName: '1.0.0' }, '1.1.0', 'inProgress'))).toBe('Rolling out 20%'); + expect(playReleaseLabel(prodRel({ state: 'public', versionName: '1.0.0' }, '1.1.0', 'halted'))).toBe('Halted'); + expect(playReleaseLabel(prodRel({ state: 'public', versionName: '1.0.0' }, '1.1.0', 'draft'))).toBe('Draft'); + }); + test('rule: "Varies with device" = live (nothing to compare)', () => { + expect(prodRel({ state: 'public', versionName: null, varies: true }).phase).toBe('live'); + }); + test('rule: only a network failure is "Couldn\'t check the store page"; with a last known read it keeps that state and its time', () => { + const r = prodRel(undefined); + expect(r).toMatchObject({ phase: 'released', publicPage: 'unknown' }); + expect(playReleaseLabel(r)).toBe("Couldn't check the store page"); + expect(laneOf('android', r).tone).toBe('neutral'); + const s = prodRel({ state: 'public', versionName: '1.1.0', stale: true, checkedAt: '2026-10-12T09:30:00Z' }); + expect(s).toMatchObject({ phase: 'live', pageStaleAt: '2026-10-12T09:30:00Z' }); + expect(playReleaseLabel(s)).toBe("Live (couldn't check the store page now; as of 2026-10-12 09:30 UTC)"); + }); + test('no uncertain wording is left', () => { + for (const r of [prodRel(undefined), prodRel({ state: 'notPublic' }), prodRel({ state: 'public', versionName: '1.0' })]) + expect(`${playReleaseLabel(r)} ${laneText(laneOf('android', r))}`).not.toMatch(/not yet published|may still be reviewing|Sent to Google/); }); }); @@ -89,10 +115,19 @@ describe('public store page read', () => { test('404 = not public yet, 200 = public, the url has no auth and asks for English', async () => { const urls = answer(404); expect((await playPublicPage('com.example.first404', { noCache: true })).state).toBe('notPublic'); - expect(urls[0]).toBe('https://play.google.com/store/apps/details?id=com.example.first404&hl=en'); + expect(urls[0]).toBe('https://play.google.com/store/apps/details?id=com.example.first404&hl=en&gl=US'); answer(200, ''); expect(await playPublicPage('com.example.first200', { noCache: true })).toMatchObject({ state: 'public', http: 200, versionName: '1.0.0' }); }); + test('a network failure returns the last known answer with its time', async () => { + const pkg = `com.example.lastknown${Date.now()}`; + answer(200, readFileSync(join(import.meta.dir, 'fixtures/play-page-version.html'), 'utf8')); + const ok = await playPublicPage(pkg, { noCache: true }); + expect(ok).toMatchObject({ state: 'public', versionName: '0.8.1' }); + globalThis.fetch = (async () => { throw new Error('getaddrinfo ENOTFOUND play.google.com'); }) as unknown as typeof fetch; + const r = await playPublicPage(pkg, { noCache: true }); + expect(r).toMatchObject({ state: 'public', versionName: '0.8.1', stale: true, checkedAt: ok.checkedAt }); + }); test('offline or a server error = unknown; unknown is never cached', async () => { const off = `com.example.offline${Date.now()}`; globalThis.fetch = (async () => { throw new Error('getaddrinfo ENOTFOUND play.google.com'); }) as unknown as typeof fetch; @@ -112,9 +147,12 @@ describe('public store page read', () => { expect((await playPublicPage(pkg)).state).toBe('notPublic'); expect(urls).toHaveLength(1); }); - test('the page version is read only from structured data', () => { + test('the page version is read from the recorded live page shape (About this app in the ds blobs)', () => { + const html = readFileSync(join(import.meta.dir, 'fixtures/play-page-version.html'), 'utf8'); + expect(pageVersionInfo(html)).toEqual({ versionName: '0.8.1', varies: false }); + expect(pageVersionInfo(html.replace('[[["0.8.1"]]', '[[["Varies with device"]]'))).toEqual({ versionName: null, varies: true }); expect(pageVersion('{"softwareVersion": "2.3.1"}')).toBe('2.3.1'); - expect(pageVersion('{"softwareVersion":"Varies with device"}')).toBeNull(); + expect(pageVersionInfo('{"softwareVersion":"Varies with device"}')).toEqual({ versionName: null, varies: true }); expect(pageVersion('
Version 1.0
')).toBeNull(); }); }); diff --git a/tests/portfolio.test.ts b/tests/portfolio.test.ts index c0a52d6..1bb045c 100644 --- a/tests/portfolio.test.ts +++ b/tests/portfolio.test.ts @@ -24,7 +24,7 @@ const play = { { track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] }, ], products: [{ productId: 'coins' }, { productId: 'no_ads' }, { sku: 'android_only' }], - publicPage: { state: 'public' }, + publicPage: { state: 'public', versionName: '2.2.1' }, }; describe('portfolio (apps, release trains, catalog parity)', () => { diff --git a/tests/release-train.test.ts b/tests/release-train.test.ts index b10a034..09caee0 100644 --- a/tests/release-train.test.ts +++ b/tests/release-train.test.ts @@ -22,7 +22,7 @@ const play = { { track: 'production', releases: [{ name: '2.3.0', versionCodes: ['230'], status: 'inProgress', userFraction: 0.1 }, { name: '2.2.0', versionCodes: ['220'], status: 'completed' }] }, { track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] }, ], - publicPage: { state: 'public' }, + publicPage: { state: 'public', versionName: '2.2.0' }, }; const all: StoreRelease[] = [...appleReleases(apple), ...playReleases(play)]; diff --git a/tests/serve.test.ts b/tests/serve.test.ts index 319d5bf..14e6d29 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -254,7 +254,7 @@ describe('serve --stdio: session', () => { const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary } : argv[0] === 'check' ? { data: { ok: true, problems: [], warnings: ['w'] } } : argv[0] === 'apple' ? { code: 1, out: 'error: ASC_KEY_ID and ASC_ISSUER_ID are not set' } - : argv[0] === 'play' ? { data: { tracks: [{ track: 'production', releases: [{ name: '1.2.0 (12)', versionCodes: ['12'], status: 'completed' }] }, { track: 'beta', releases: [{ name: '1.3.0', versionCodes: ['13'], status: 'completed' }] }], products: [{ productId: 'coins' }], publicPage: { state: 'public' } } } : {}); + : argv[0] === 'play' ? { data: { tracks: [{ track: 'production', releases: [{ name: '1.2.0 (12)', versionCodes: ['12'], status: 'completed' }] }, { track: 'beta', releases: [{ name: '1.3.0', versionCodes: ['13'], status: 'completed' }] }], products: [{ productId: 'coins' }], publicPage: { state: 'public', versionName: '1.2.0' } } } : {}); const r = resOf(await call('portfolio.status', { projects: [DEMO, '/nope/game'], live: true })) as { apps: J[] }; expect(r.apps[0]).toMatchObject({ project: DEMO, app: { id: DEMO, name: 'Demo', platforms: { ios: { bundleId: 'com.example.demo' }, android: { packageName: 'com.example.demo' } } }, check: { ok: true, warnings: ['w'] }, storeErrors: { ios: 'ASC_KEY_ID and ASC_ISSUER_ID are not set' }, ok: false }); diff --git a/tools/desktop-boot-check.ts b/tools/desktop-boot-check.ts index 617db52..6e90829 100644 --- a/tools/desktop-boot-check.ts +++ b/tools/desktop-boot-check.ts @@ -541,7 +541,7 @@ async function runReleaseStateCase(browser: Browser, sidecar: Sidecar, page404: let visited = 0; const text = async (sel = '#content') => (await page.locator(sel).first().innerText().catch(() => '')).replace(/\s+/g, ' '); const crashCheck = async (where: string) => { for (const c of (await state(page)).crash) problems.push(`${where}: error panel ${c}`); }; - const SENT = 'Sent to Google (in review or not yet published)'; + const SENT = 'In review'; // decided from the store page: 404 = in review (no uncertain wording) try { await page.goto(`http://127.0.0.1:${server.port}/`, { waitUntil: 'load' }); await page.waitForFunction(() => document.documentElement.dataset.booted === '1', null, { timeout: WAIT_MS }).catch(() => problems.push('React never drew the window (no data-booted)')); @@ -568,6 +568,7 @@ async function runReleaseStateCase(browser: Browser, sidecar: Sidecar, page404: if (row[1] !== 'In review') problems.push(`Releases: App Store cell "${row[1]}" (want "In review")`); if (row[3] !== (page404 ? SENT : 'Live')) problems.push(`Releases: Google Play cell "${row[3]}" (want "${page404 ? SENT : 'Live'}")`); const rel = await text(); + if (/not yet published|may still be reviewing|Sent to Google/.test(rel + pf)) problems.push('uncertain Play wording on screen'); if (/is not on (App Store|Google Play) yet/.test(rel)) problems.push('Releases: a lane says the version is not on a store (1.0 and 1.0.0 not joined)'); for (const w of ['1.0 (3)', '1.0.0 (3)']) if (!rel.includes(w)) problems.push(`Releases: the lane does not show the store's own "${w}"`); if (page404) { @@ -609,6 +610,8 @@ async function runAutoReadCase(browser: Browser): Promise { const notes: string[] = []; const logged: string[] = []; let reads = 0; + const playOpen = new Map(); + let playPeak = 0; // fixture art is file: URLs (blocked by the CSP): icons are left out const clean = (v: unknown): unknown => (v === undefined ? null : JSON.parse(JSON.stringify(v), (_k, x) => (typeof x === 'string' && x.startsWith('file:') ? null : x))); const answer = async (cmd: string, a: Record): Promise => { @@ -621,6 +624,15 @@ async function runAutoReadCase(browser: Browser): Promise { const method = String(a.method); if (method === 'system.tools') return clean(await fx.mockInvoke(cmd, a)); reads++; + if (method.startsWith('play.') || ['health', 'reviews.list', 'catalog.diff', 'prices.current', 'validate'].includes(method)) { + // Play reads of one app may run at once (the scheduler's 4 per store, starts 250 ms apart per key): count the + // overlap and hold each read long enough for it to happen + const k = String(a.projectId); + const n = (playOpen.get(k) ?? 0) + 1; + playOpen.set(k, n); playPeak = Math.max(playPeak, n); + await new Promise(r => setTimeout(r, 400)); + playOpen.set(k, playOpen.get(k)! - 1); + } return clean(fx.fixtureRead(method, String(a.projectId), ((a.params as { args?: Record } | null)?.args) ?? {})); } default: return clean(await fx.mockInvoke(cmd, a)); @@ -664,10 +676,24 @@ async function runAutoReadCase(browser: Browser): Promise { await settle(page); await crashCheck(`${appName} ${id}`); const tx = await text(); + // a Play read that lost its edit to a parallel read (pitfall), or a store that failed called empty + for (const bad of [/Edit has been deleted/i, /is not on Google Play yet/i]) if (bad.test(tx)) problems.push(`${appName} ${id}: says "${(bad.exec(tx) ?? [''])[0]}"`); if (/not read yet|Read the stores to see this/i.test(tx)) problems.push(`${appName} ${id}: says "${(/not read yet|Read the stores to see this/i.exec(tx) ?? [''])[0]}" after the background read`); visited++; } } + notes.push(`Play reads of one app at once: up to ${playPeak}`); + if (playPeak < 2) problems.push(`no two Play reads of one app ran at once (peak ${playPeak}): the case does not exercise parallel reads`); + // the stores' current versions differ (Play 3.1.0, App Store 3.0.4): a neutral header, each store its own state + await page.locator('nav.side .nav-app', { hasText: 'Orbit Hop' }).first().click({ timeout: WAIT_MS }); + await settle(page); + await page.locator('[role="tab"]#tab-releases').click({ timeout: WAIT_MS }); + await settle(page); + const rel = await text(); + for (const w of ['Current', 'Play 3.1.0 · App Store 3.0.4', '3.0.4 · Live (3.1.0 not submitted)']) if (!rel.includes(w)) problems.push(`Orbit Hop Releases: missing "${w}"`); + for (const w of ['Not on this store', 'is not on App Store yet', '3.1.0 Released']) if (rel.includes(w)) problems.push(`Orbit Hop Releases: says "${w}"`); + notes.push(`Orbit Hop releases: ${rel.slice(0, 200)}`); + await crashCheck('Orbit Hop Releases'); // Health: the first top issue opens with its full title, the sample stack and Copy for AI await page.locator('nav.side .nav-app', { hasText: 'Prism Puddle' }).first().click({ timeout: WAIT_MS }); await settle(page); From 3cea2af4e19b21bf11d41915c3dab47b375a15c0 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 14 Oct 2026 00:35:29 +0800 Subject: [PATCH 010/429] desktop editors: edit in place what App Store Connect and Play Console let the owner edit (listings per language for both stores with live counters and the check / scan rules, store details, App info, age rating, App Review, Play store settings, Data safety and App Privacy answers, promotion blocks, catalog names / prices / offers, TestFlight information, scene order); storebound edit (project.edit) saves into the config by path keeping comments and formatting, the listing files and the review contact, dry run with the diff and the checks first; Apply shows each store's dry run in the window; unsaved edits survive tab switches with undo / redo; tests/edit.test.ts, apps/desktop/tests/edits.test.ts, boot check editor case --- apps/desktop/src/api.ts | 1 + apps/desktop/src/i18n/en.ts | 178 ++++++++++ apps/desktop/src/i18n/tr.ts | 178 ++++++++++ apps/desktop/src/lib/edits.ts | 107 +++++++ apps/desktop/src/lib/freshness.ts | 3 +- apps/desktop/src/screens/AppView.tsx | 8 +- .../src/screens/editors/AppInfoEditor.tsx | 152 +++++++++ .../desktop/src/screens/editors/ArtEditor.tsx | 57 ++++ .../src/screens/editors/CatalogEditor.tsx | 148 +++++++++ .../src/screens/editors/ListingEditor.tsx | 163 ++++++++++ .../desktop/src/screens/editors/TabEditor.tsx | 47 +++ .../src/screens/editors/TestFlightEditor.tsx | 48 +++ apps/desktop/src/screens/tabs/Listings.tsx | 13 +- apps/desktop/src/styles.css | 49 +++ apps/desktop/src/ui/Editor.tsx | 298 +++++++++++++++++ apps/desktop/tests/edits.test.ts | 67 ++++ cli/apple/appinfo.ts | 11 +- cli/commands.ts | 1 + cli/data/flags.json | 10 + cli/edit.ts | 118 +++++++ cli/lib/aso-intel.ts | 12 +- cli/lib/config-path.ts | 297 +++++++++++++++++ cli/lib/config.ts | 11 +- cli/lib/desktop-protocol.ts | 41 +++ cli/lib/edit-values.ts | 83 +++++ cli/lib/edit.ts | 188 +++++++++++ cli/lib/listing-edit.ts | 119 +++++++ cli/lib/listing-rules.ts | 114 +++++++ cli/lib/scan/config-edit.ts | 2 +- cli/lib/scan/rules.ts | 14 +- cli/lib/store-catalogs.ts | 44 +++ cli/serve.ts | 10 +- docs/commands.md | 1 + docs/desktop.md | 34 ++ tests/desktop-d3.test.ts | 3 + tests/edit.test.ts | 303 ++++++++++++++++++ tools/desktop-boot-check.ts | 141 +++++++- 37 files changed, 3020 insertions(+), 54 deletions(-) create mode 100644 apps/desktop/src/lib/edits.ts create mode 100644 apps/desktop/src/screens/editors/AppInfoEditor.tsx create mode 100644 apps/desktop/src/screens/editors/ArtEditor.tsx create mode 100644 apps/desktop/src/screens/editors/CatalogEditor.tsx create mode 100644 apps/desktop/src/screens/editors/ListingEditor.tsx create mode 100644 apps/desktop/src/screens/editors/TabEditor.tsx create mode 100644 apps/desktop/src/screens/editors/TestFlightEditor.tsx create mode 100644 apps/desktop/src/ui/Editor.tsx create mode 100644 apps/desktop/tests/edits.test.ts create mode 100644 cli/edit.ts create mode 100644 cli/lib/config-path.ts create mode 100644 cli/lib/edit-values.ts create mode 100644 cli/lib/edit.ts create mode 100644 cli/lib/listing-edit.ts create mode 100644 cli/lib/listing-rules.ts create mode 100644 cli/lib/store-catalogs.ts create mode 100644 tests/edit.test.ts diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 31a5b1f..b58bf3f 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -10,6 +10,7 @@ import type { Overrides } from './lib/identity'; export type { AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, + EditableListing, EditableResult, EditResult, AnalyticsCompare, AsoAuditView, AsoTrendRow, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult, } from '../../../cli/lib/desktop-protocol'; diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 3cad6a2..7e0da5c 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1545,4 +1545,182 @@ export const en = { 'deps.sdkFrom': 'Found through', 'deps.sdkNone': 'Not found. play build needs it (install Android Studio, or set ANDROID_HOME). Checked:', 'ai.dsFrom': 'from {source}', + 'ed.countAria': '{n} of {limit} characters', + 'ed.unsavedField': 'Unsaved change', + 'ed.was': 'Saved:', + 'ed.empty': '(empty)', + 'ed.removed': '(removed)', + 'ed.reset': 'Reset', + 'ed.notSet': 'Not set', + 'ed.none': 'none', + 'ed.notNumber': 'Not a number', + 'ed.notJson': 'Not valid JSON: {error}', + 'ed.noGit': 'Not a git folder', + 'ed.gitClean': 'No uncommitted changes in these files', + 'ed.gitDirty': 'Uncommitted in git: {files}. storebound never commits.', + 'ed.also': 'the same section also serves {codes}', + 'ed.newFile': 'new file', + 'ed.masked': 'Personal data: not shown.', + 'ed.unsaved': '{count} unsaved changes', + 'ed.unsaved_one': '1 unsaved change', + 'ed.noChanges': 'No unsaved changes', + 'ed.undo': 'Undo', + 'ed.redo': 'Redo', + 'ed.discard': 'Discard', + 'ed.review': 'Review and save', + 'ed.close': 'Close', + 'ed.fixFirst': 'Fix the errors first', + 'ed.save': 'Save to the app folder', + 'ed.saved': 'Saved to the app folder', + 'ed.nothingToApply': 'Nothing to change on the store.', + 'ed.applyNow': 'Apply to the store', + 'ed.saveFirst': 'Save your edits first: the store gets what the files hold.', + 'ed.statusDraft': 'Machine draft, not reviewed', + 'ed.statusTranslate': 'Not translated yet', + 'ed.alsoServes': 'also {codes}', + 'ed.newSection': '{lang} has no section in the listing file yet. Fill in the required fields; saving adds the section.', + 'ed.keywordsHint': 'Comma separated, no spaces after commas; do not repeat words from the name or subtitle.', + 'ed.whatsNewApple': 'Not allowed on the first version.', + 'ed.nameHint': 'Empty: the app name from the config.', + 'ed.supportUrl': 'Support URL', + 'ed.marketingUrl': 'Marketing URL', + 'ed.privacyUrl': 'Privacy policy URL', + 'ed.termsUrl': 'Terms of Use URL', + 'ed.termsHint': 'Needed with subscriptions (Apple 3.1.2).', + 'ed.website': 'Website', + 'ed.websiteHint': 'Google Play: the domain that serves app-ads.txt.', + 'ed.contactEmail': 'Contact email', + 'ed.copyright': 'Copyright', + 'ed.video': 'Promo video (YouTube URL)', + 'ed.videoHint': 'Public or unlisted, ads off, embeddable. Play takes no video upload.', + 'ed.listingTitle': 'Edit the listing', + 'ed.listingSub': 'Per language, both stores side by side. Counters use the store limits; the checks of check and scan run as you type.', + 'ed.pullPlay': 'Pull from Google Play', + 'ed.pullApple': 'Pull from the App Store', + 'ed.pulled': 'The listing file now matches the store', + 'ed.pullHint': 'Reads the live texts and shows the diff before anything in the files changes.', + 'ed.pullDirty': 'You have unsaved edits: they stay pending on top of the pulled text.', + 'ed.pullNote': 'Pulling rewrites the listing files after a diff; your unsaved edits stay pending on top.', + 'ed.playCode': 'Play language', + 'ed.rtl': 'Right-to-left language.', + 'ed.noStoreForLang': '{lang} is on neither store in the config.', + 'ed.detailsTitle': 'Store details', + 'ed.detailsSub': 'URLs, contact and copyright, shared by both stores (storebound.config.ts).', + 'ed.applyTitle': 'Apply to the stores', + 'ed.applySub': 'Each store: the dry run (old to new per language) in the window, then the confirm dialog, then the real run.', + 'ed.applyPlay': 'Google Play listing: preview', + 'ed.applyApple': 'App Store {version}: preview', + 'ed.applyNote': 'Nothing goes to review: the texts wait in the store until you send the version or changes for review.', + 'ed.appleInfoTitle': 'App Store app information', + 'ed.appleInfoSub': 'Categories, content rights, price, export compliance and the App Store name.', + 'ed.catPrimary': 'Primary category', + 'ed.catSub1': 'Game subcategory 1', + 'ed.catSub2': 'Game subcategory 2', + 'ed.catSecondary': 'Secondary category', + 'ed.free': 'Price', + 'ed.freeHint': 'Free: available in every territory and new ones.', + 'ed.encHint': 'Only you can answer this: export compliance skill.', + 'ed.appleName': 'App Store name', + 'ed.appleNameHint': 'When the app name is taken on the App Store.', + 'ed.ageTitle': 'Age rating', + 'ed.ageSub': 'Every question of the App Store declaration. Not set: the "nothing" answer.', + 'ed.ageDefault': 'Default: {value}', + 'ed.reviewSub': 'Sign-in, notes and contact for App Review. The demo account password is never shown.', + 'ed.notesHint': 'App Store Connect takes at most {max} bytes.', + 'ed.signInSteps': 'Sign-in steps for reviewers', + 'ed.contact_firstName': 'Contact first name', + 'ed.contact_lastName': 'Contact last name', + 'ed.contact_phone': 'Contact phone', + 'ed.contact_email': 'Contact email', + 'ed.contactHint': 'Personal data: kept in the private .storebound/ folder (gitignored), shown masked. Type to replace.', + 'ed.demoHint': 'The demo account lives only in the private .storebound/ folder; the window never reads the password.', + 'ed.game': 'Game', + 'ed.app': 'App', + 'ed.playSettingsTitle': 'Google Play store settings', + 'ed.playSettingsSub': 'Category, countries, managed publishing, target audience, delete-account page.', + 'ed.playCategory': 'App category', + 'ed.noApiHint': 'No API: the console plan step uses this value.', + 'ed.managed': 'Managed publishing', + 'ed.countries': 'Production countries', + 'ed.countriesHint': 'Two-letter codes (US, GB, TR). Empty: all countries.', + 'ed.targetAges': 'Target age groups', + 'ed.targetAgesHint': 'Of {groups}.', + 'ed.deletionUrl': 'Delete-account page', + 'ed.declTitle': 'Data safety and App Privacy answers', + 'ed.declSub': 'The answers both forms are filled from. Only you know them: change what the app and its SDKs really do.', + 'ed.dsTypes': 'Data types (Play)', + 'ed.dsTypesHint': 'Play data type id to usage: { "PSL_EMAIL": { "shared": false, "collect": ["account"] } }. Not listed: not collected.', + 'ed.apAnswers': 'App Privacy (App Store)', + 'ed.apHint': 'Checked with the whole config when you save; App Privacy has no API (console fill).', + 'ed.promoTitle': 'App Store promotion', + 'ed.promoSub': 'Promoted purchases, custom product pages and in-app events.', + 'ed.promoted': 'Promoted in-app purchases', + 'ed.promotedHint': 'Turning them on stays a terminal step (apple promoted --enable).', + 'ed.cpp': 'Custom product pages', + 'ed.cppHint': 'Submitting a page and making it visible stay terminal steps.', + 'ed.events': 'In-app events', + 'ed.eventsHint': 'Name 30, short 50, long 120 characters per locale. Sending to review stays a terminal step.', + 'ed.applyCpp': 'Custom product pages: preview', + 'ed.applyEvents': 'In-app events: preview', + 'ed.applyInfoSub': 'App information, App Review, export compliance, Data safety and the Play app details.', + 'ed.applyPlayDetails': 'Play contact email and website: preview', + 'ed.playConsoleOnly': 'Category, countries and managed publishing have no API: App info > Console steps.', + 'ed.itemName': 'Name', + 'ed.itemDescription': 'Description', + 'ed.benefits': 'Benefits (Play)', + 'ed.benefitsHint': 'Comma separated, up to 4, 40 characters each.', + 'ed.usd': 'Base price (USD)', + 'ed.usdHint': 'A live product\'s new price waits for your decision (Apply the price changes).', + 'ed.refName': 'Reference name', + 'ed.reviewNote': 'Review note', + 'ed.reviewShot': 'Review screenshot', + 'ed.family': 'Family Sharing', + 'ed.offerCodes': 'Offer codes', + 'ed.offerCodesHint': 'Creating codes stays a terminal step (they work like vouchers).', + 'ed.level': 'Level in the group', + 'ed.levelHint': '1 = highest level of service.', + 'ed.period': 'Period', + 'ed.periodHint': 'Cannot change after the subscription is approved.', + 'ed.intro': 'Introductory offer', + 'ed.introHint': 'For example { "type": "free", "duration": "P1W" }.', + 'ed.offers': 'Promotional offers', + 'ed.winBack': 'Win-back offers', + 'ed.winBackHint': 'Creating one stays a terminal step: it goes live by itself on its start date.', + 'ed.catalogTitle': 'Edit the catalog', + 'ed.catalogEmpty': 'No products or subscriptions in the config', + 'ed.catalogEmptyText': 'Add them with the store-iap-setup or store-subscriptions skill.', + 'ed.productsTitle': 'In-app products', + 'ed.productsSub': 'Names, descriptions per language, price and review details.', + 'ed.groupTitle': 'Subscription group {name}', + 'ed.groupSub': 'Group display name per language and each subscription.', + 'ed.groupName': 'Group display name', + 'ed.applyCatalogSub': 'Each store: the dry run per product in the window, then the confirm dialog.', + 'ed.applyPlayProducts': 'Play products: preview', + 'ed.applyPlaySubs': 'Play subscriptions: preview', + 'ed.applyAppleIap': 'App Store in-app purchases: preview', + 'ed.applyAppleSubs': 'App Store subscriptions: preview', + 'ed.applyIapReview': 'Review screenshots: preview', + 'ed.priceGate': 'Price changes of live products are never applied here: they wait for your decision in the owner action.', + 'ed.tfTitle': 'Edit TestFlight information', + 'ed.tfSub': 'What to Test per locale, the beta description, notes for Beta App Review and the groups.', + 'ed.whatToTest': 'What to Test', + 'ed.whatToTestHint': 'Empty: the What\'s new text is used.', + 'ed.betaDescription': 'Beta App Description', + 'ed.betaDescriptionAll': 'Beta App Description (every locale)', + 'ed.betaNotes': 'Notes for Beta App Review', + 'ed.tfGroups': 'Beta groups', + 'ed.tfGroupsHint': '[{ "name": "Studio team", "internal": true }]. Existing groups are never changed or deleted.', + 'ed.applyTfSub': 'Test information and the missing groups. External testing and Beta App Review stay terminal steps.', + 'ed.applyTfInfo': 'Test information: preview', + 'ed.artTitle': 'Screenshot order and frames', + 'ed.artSub': 'The stores show the screenshots in this order. Point a scene at another frame to replace its screenshot.', + 'ed.artEmpty': 'No screenshot scenes in the config', + 'ed.artEmptyText': 'Set up shots with the store-screenshots skill.', + 'ed.frame': 'Frame', + 'ed.up': 'Up', + 'ed.down': 'Down', + 'ed.moveUp': 'Move {id} up', + 'ed.moveDown': 'Move {id} down', + 'ed.applyArtSub': 'Render, then upload: an upload replaces the store\'s screenshot set (dry run first).', + 'ed.loadFailed': 'Could not read the app folder\'s files: {error}', } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 1efb833..40b3d3d 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1547,4 +1547,182 @@ export const tr: Record = { 'deps.sdkFrom': 'Bulunduğu yer', 'deps.sdkNone': 'Bulunamadı. play build buna ihtiyaç duyar (Android Studio\'yu kurun veya ANDROID_HOME ayarlayın). Bakılan yerler:', 'ai.dsFrom': 'kaynak: {source}', + 'ed.countAria': '{limit} karakterin {n} tanesi', + 'ed.unsavedField': 'Kaydedilmemiş değişiklik', + 'ed.was': 'Kayıtlı:', + 'ed.empty': '(boş)', + 'ed.removed': '(kaldırıldı)', + 'ed.reset': 'Geri al', + 'ed.notSet': 'Ayarlanmadı', + 'ed.none': 'yok', + 'ed.notNumber': 'Sayı değil', + 'ed.notJson': 'Geçerli JSON değil: {error}', + 'ed.noGit': 'Git klasörü değil', + 'ed.gitClean': 'Bu dosyalarda commit edilmemiş değişiklik yok', + 'ed.gitDirty': 'Git\'te commit edilmemiş: {files}. storebound asla commit etmez.', + 'ed.also': 'aynı bölüm {codes} için de geçerli', + 'ed.newFile': 'yeni dosya', + 'ed.masked': 'Kişisel veri: gösterilmiyor.', + 'ed.unsaved': '{count} kaydedilmemiş değişiklik', + 'ed.unsaved_one': '1 kaydedilmemiş değişiklik', + 'ed.noChanges': 'Kaydedilmemiş değişiklik yok', + 'ed.undo': 'Geri al', + 'ed.redo': 'Yinele', + 'ed.discard': 'Vazgeç', + 'ed.review': 'Gözden geçir ve kaydet', + 'ed.close': 'Kapat', + 'ed.fixFirst': 'Önce hataları düzeltin', + 'ed.save': 'Uygulama klasörüne kaydet', + 'ed.saved': 'Uygulama klasörüne kaydedildi', + 'ed.nothingToApply': 'Mağazada değişecek bir şey yok.', + 'ed.applyNow': 'Mağazaya uygula', + 'ed.saveFirst': 'Önce düzenlemeleri kaydedin: mağazaya dosyalardaki gönderilir.', + 'ed.statusDraft': 'Makine taslağı, gözden geçirilmedi', + 'ed.statusTranslate': 'Henüz çevrilmedi', + 'ed.alsoServes': 'ayrıca {codes}', + 'ed.newSection': '{lang} için listeleme dosyasında henüz bölüm yok. Zorunlu alanları doldurun; kaydetmek bölümü ekler.', + 'ed.keywordsHint': 'Virgülle ayrılmış, virgülden sonra boşluk yok; ad veya alt başlıktaki kelimeleri tekrarlamayın.', + 'ed.whatsNewApple': 'İlk sürümde kullanılamaz.', + 'ed.nameHint': 'Boş: yapılandırmadaki uygulama adı.', + 'ed.supportUrl': 'Destek URL\'si', + 'ed.marketingUrl': 'Pazarlama URL\'si', + 'ed.privacyUrl': 'Gizlilik politikası URL\'si', + 'ed.termsUrl': 'Kullanım koşulları URL\'si', + 'ed.termsHint': 'Aboneliklerde gerekli (Apple 3.1.2).', + 'ed.website': 'Web sitesi', + 'ed.websiteHint': 'Google Play: app-ads.txt dosyasını sunan alan adı.', + 'ed.contactEmail': 'İletişim e-postası', + 'ed.copyright': 'Telif hakkı', + 'ed.video': 'Tanıtım videosu (YouTube URL\'si)', + 'ed.videoHint': 'Herkese açık veya liste dışı, reklamsız, yerleştirilebilir. Play video yüklemesi almaz.', + 'ed.listingTitle': 'Listelemeyi düzenle', + 'ed.listingSub': 'Dil başına, iki mağaza yan yana. Sayaçlar mağaza sınırlarını kullanır; check ve scan denetimleri yazarken çalışır.', + 'ed.pullPlay': 'Google Play\'den çek', + 'ed.pullApple': 'App Store\'dan çek', + 'ed.pulled': 'Listeleme dosyası artık mağazayla aynı', + 'ed.pullHint': 'Canlı metinleri okur ve dosyalarda bir şey değişmeden önce farkı gösterir.', + 'ed.pullDirty': 'Kaydedilmemiş düzenlemeleriniz var: çekilen metnin üzerinde bekler.', + 'ed.pullNote': 'Çekme, farkı gösterdikten sonra listeleme dosyalarını yeniden yazar; kaydedilmemiş düzenlemeler üstte bekler.', + 'ed.playCode': 'Play dili', + 'ed.rtl': 'Sağdan sola yazılan dil.', + 'ed.noStoreForLang': '{lang} yapılandırmada iki mağazada da yok.', + 'ed.detailsTitle': 'Mağaza ayrıntıları', + 'ed.detailsSub': 'URL\'ler, iletişim ve telif hakkı, iki mağazada ortak (storebound.config.ts).', + 'ed.applyTitle': 'Mağazalara uygula', + 'ed.applySub': 'Her mağaza: pencerede deneme çalıştırması (dil başına eskiden yeniye), sonra onay penceresi, sonra gerçek çalıştırma.', + 'ed.applyPlay': 'Google Play listelemesi: önizle', + 'ed.applyApple': 'App Store {version}: önizle', + 'ed.applyNote': 'Hiçbir şey incelemeye gitmez: metinler sürümü veya değişiklikleri incelemeye gönderene kadar mağazada bekler.', + 'ed.appleInfoTitle': 'App Store uygulama bilgileri', + 'ed.appleInfoSub': 'Kategoriler, içerik hakları, fiyat, ihracat uyumluluğu ve App Store adı.', + 'ed.catPrimary': 'Birincil kategori', + 'ed.catSub1': 'Oyun alt kategorisi 1', + 'ed.catSub2': 'Oyun alt kategorisi 2', + 'ed.catSecondary': 'İkincil kategori', + 'ed.free': 'Fiyat', + 'ed.freeHint': 'Ücretsiz: her bölgede ve yenilerinde sunulur.', + 'ed.encHint': 'Bunu yalnızca siz yanıtlayabilirsiniz: export-compliance becerisi.', + 'ed.appleName': 'App Store adı', + 'ed.appleNameHint': 'Uygulama adı App Store\'da alınmışsa.', + 'ed.ageTitle': 'Yaş derecelendirmesi', + 'ed.ageSub': 'App Store beyanının her sorusu. Ayarlanmadı: "hiç" yanıtı.', + 'ed.ageDefault': 'Varsayılan: {value}', + 'ed.reviewSub': 'App Review için oturum açma, notlar ve iletişim. Demo hesap parolası asla gösterilmez.', + 'ed.notesHint': 'App Store Connect en fazla {max} bayt alır.', + 'ed.signInSteps': 'İnceleyiciler için oturum açma adımları', + 'ed.contact_firstName': 'İletişim adı', + 'ed.contact_lastName': 'İletişim soyadı', + 'ed.contact_phone': 'İletişim telefonu', + 'ed.contact_email': 'İletişim e-postası', + 'ed.contactHint': 'Kişisel veri: gizli .storebound/ klasöründe (gitignore) tutulur, maskeli gösterilir. Değiştirmek için yazın.', + 'ed.demoHint': 'Demo hesap yalnızca gizli .storebound/ klasöründe; pencere parolayı asla okumaz.', + 'ed.game': 'Oyun', + 'ed.app': 'Uygulama', + 'ed.playSettingsTitle': 'Google Play mağaza ayarları', + 'ed.playSettingsSub': 'Kategori, ülkeler, yönetilen yayınlama, hedef kitle, hesap silme sayfası.', + 'ed.playCategory': 'Uygulama kategorisi', + 'ed.noApiHint': 'API yok: konsol planı adımı bu değeri kullanır.', + 'ed.managed': 'Yönetilen yayınlama', + 'ed.countries': 'Üretim ülkeleri', + 'ed.countriesHint': 'İki harfli kodlar (US, GB, TR). Boş: tüm ülkeler.', + 'ed.targetAges': 'Hedef yaş grupları', + 'ed.targetAgesHint': 'Şunlardan: {groups}.', + 'ed.deletionUrl': 'Hesap silme sayfası', + 'ed.declTitle': 'Veri güvenliği ve App Privacy yanıtları', + 'ed.declSub': 'İki formun doldurulduğu yanıtlar. Bunları yalnızca siz bilirsiniz: uygulamanın ve SDK\'larının gerçekte yaptığını yazın.', + 'ed.dsTypes': 'Veri türleri (Play)', + 'ed.dsTypesHint': 'Play veri türü kimliğinden kullanıma: { "PSL_EMAIL": { "shared": false, "collect": ["account"] } }. Listede olmayan: toplanmıyor.', + 'ed.apAnswers': 'App Privacy (App Store)', + 'ed.apHint': 'Kaydederken tüm yapılandırmayla denetlenir; App Privacy\'nin API\'si yok (konsolda doldurma).', + 'ed.promoTitle': 'App Store tanıtımı', + 'ed.promoSub': 'Öne çıkan satın almalar, özel ürün sayfaları ve uygulama içi etkinlikler.', + 'ed.promoted': 'Öne çıkan uygulama içi satın almalar', + 'ed.promotedHint': 'Etkinleştirme terminal adımı olarak kalır (apple promoted --enable).', + 'ed.cpp': 'Özel ürün sayfaları', + 'ed.cppHint': 'Sayfayı gönderme ve görünür yapma terminal adımları olarak kalır.', + 'ed.events': 'Uygulama içi etkinlikler', + 'ed.eventsHint': 'Yerel ayar başına ad 30, kısa 50, uzun 120 karakter. İncelemeye gönderme terminal adımı olarak kalır.', + 'ed.applyCpp': 'Özel ürün sayfaları: önizle', + 'ed.applyEvents': 'Uygulama içi etkinlikler: önizle', + 'ed.applyInfoSub': 'Uygulama bilgileri, App Review, ihracat uyumluluğu, Veri güvenliği ve Play uygulama ayrıntıları.', + 'ed.applyPlayDetails': 'Play iletişim e-postası ve web sitesi: önizle', + 'ed.playConsoleOnly': 'Kategori, ülkeler ve yönetilen yayınlamanın API\'si yok: Uygulama bilgileri > Konsol adımları.', + 'ed.itemName': 'Ad', + 'ed.itemDescription': 'Açıklama', + 'ed.benefits': 'Avantajlar (Play)', + 'ed.benefitsHint': 'Virgülle ayrılmış, en fazla 4, her biri 40 karakter.', + 'ed.usd': 'Taban fiyat (USD)', + 'ed.usdHint': 'Canlı bir ürünün yeni fiyatı kararınızı bekler (Fiyat değişikliklerini uygula).', + 'ed.refName': 'Referans adı', + 'ed.reviewNote': 'İnceleme notu', + 'ed.reviewShot': 'İnceleme ekran görüntüsü', + 'ed.family': 'Aile Paylaşımı', + 'ed.offerCodes': 'Teklif kodları', + 'ed.offerCodesHint': 'Kod oluşturma terminal adımı olarak kalır (kupon gibi çalışırlar).', + 'ed.level': 'Gruptaki düzey', + 'ed.levelHint': '1 = en yüksek hizmet düzeyi.', + 'ed.period': 'Dönem', + 'ed.periodHint': 'Abonelik onaylandıktan sonra değiştirilemez.', + 'ed.intro': 'Tanıtım teklifi', + 'ed.introHint': 'Örneğin { "type": "free", "duration": "P1W" }.', + 'ed.offers': 'Promosyon teklifleri', + 'ed.winBack': 'Geri kazanma teklifleri', + 'ed.winBackHint': 'Oluşturma terminal adımı olarak kalır: başlangıç tarihinde kendiliğinden yayına girer.', + 'ed.catalogTitle': 'Kataloğu düzenle', + 'ed.catalogEmpty': 'Yapılandırmada ürün veya abonelik yok', + 'ed.catalogEmptyText': 'store-iap-setup veya store-subscriptions becerisiyle ekleyin.', + 'ed.productsTitle': 'Uygulama içi ürünler', + 'ed.productsSub': 'Dil başına adlar, açıklamalar, fiyat ve inceleme ayrıntıları.', + 'ed.groupTitle': 'Abonelik grubu {name}', + 'ed.groupSub': 'Dil başına grup görünen adı ve her abonelik.', + 'ed.groupName': 'Grup görünen adı', + 'ed.applyCatalogSub': 'Her mağaza: pencerede ürün başına deneme çalıştırması, sonra onay penceresi.', + 'ed.applyPlayProducts': 'Play ürünleri: önizle', + 'ed.applyPlaySubs': 'Play abonelikleri: önizle', + 'ed.applyAppleIap': 'App Store uygulama içi satın almalar: önizle', + 'ed.applyAppleSubs': 'App Store abonelikleri: önizle', + 'ed.applyIapReview': 'İnceleme ekran görüntüleri: önizle', + 'ed.priceGate': 'Canlı ürünlerin fiyat değişiklikleri burada asla uygulanmaz: sahip eyleminde kararınızı bekler.', + 'ed.tfTitle': 'TestFlight bilgilerini düzenle', + 'ed.tfSub': 'Yerel ayar başına Neyi Test Etmeli, beta açıklaması, Beta App Review notları ve gruplar.', + 'ed.whatToTest': 'Neyi Test Etmeli', + 'ed.whatToTestHint': 'Boş: Yenilikler metni kullanılır.', + 'ed.betaDescription': 'Beta Uygulama Açıklaması', + 'ed.betaDescriptionAll': 'Beta Uygulama Açıklaması (tüm yerel ayarlar)', + 'ed.betaNotes': 'Beta App Review notları', + 'ed.tfGroups': 'Beta grupları', + 'ed.tfGroupsHint': '[{ "name": "Stüdyo ekibi", "internal": true }]. Mevcut gruplar asla değiştirilmez veya silinmez.', + 'ed.applyTfSub': 'Test bilgileri ve eksik gruplar. Harici test ve Beta App Review terminal adımları olarak kalır.', + 'ed.applyTfInfo': 'Test bilgileri: önizle', + 'ed.artTitle': 'Ekran görüntüsü sırası ve kareler', + 'ed.artSub': 'Mağazalar ekran görüntülerini bu sırayla gösterir. Görüntüsünü değiştirmek için bir sahneyi başka bir kareye yönlendirin.', + 'ed.artEmpty': 'Yapılandırmada ekran görüntüsü sahnesi yok', + 'ed.artEmptyText': 'shots ayarını store-screenshots becerisiyle yapın.', + 'ed.frame': 'Kare', + 'ed.up': 'Yukarı', + 'ed.down': 'Aşağı', + 'ed.moveUp': '{id} sahnesini yukarı taşı', + 'ed.moveDown': '{id} sahnesini aşağı taşı', + 'ed.applyArtSub': 'Oluştur, sonra yükle: yükleme mağazadaki ekran görüntüsü setinin yerini alır (önce deneme çalıştırması).', + 'ed.loadFailed': 'Uygulama klasörünün dosyaları okunamadı: {error}', }; diff --git a/apps/desktop/src/lib/edits.ts b/apps/desktop/src/lib/edits.ts new file mode 100644 index 0000000..72ddb1d --- /dev/null +++ b/apps/desktop/src/lib/edits.ts @@ -0,0 +1,107 @@ +// Unsaved edits of the window's editors, per app: one pending value per field (a config path, a listing field of one +// store and language, an App Review contact field), with undo / redo. Kept for the whole session, outside the tabs, +// so switching tabs or apps never loses them; the tab bar marks apps and tabs with unsaved edits, and closing the +// window asks first (beforeunload). Saving turns them into the ops of `storebound edit` (project.edit). Pure apart +// from the subscriber list (tests/edits.test.ts). + +export type EditOp = + | { kind: 'config'; path: string; value?: unknown; remove?: boolean } + | { kind: 'listing'; store: 'play' | 'apple'; lang: string; field: string; value: string } + | { kind: 'contact'; field: 'firstName' | 'lastName' | 'phone' | 'email'; value: string }; + +/** Which editor (tab) a pending edit belongs to, for the unsaved marks. */ +export type EditArea = 'listings' | 'appinfo' | 'catalog' | 'testflight' | 'art'; + +export interface Pending { key: string; op: EditOp; area: EditArea; /** The saved value, to show "was" and to drop an edit typed back to it. */ saved: unknown } + +export const keyOf = (op: EditOp): string => + op.kind === 'config' ? `config:${op.path}` : op.kind === 'listing' ? `listing:${op.store}:${op.lang}:${op.field}` : `contact:${op.field}`; + +const valueOf = (op: EditOp): unknown => (op.kind === 'config' ? (op.remove ? undefined : op.value) : op.value); + +const same = (a: unknown, b: unknown): boolean => { + const n = (v: unknown) => (v === undefined || v === null || v === '' ? null : v); + return JSON.stringify(n(a)) === JSON.stringify(n(b)); +}; + +interface ProjectEdits { pending: Map; undo: Map[]; redo: Map[]; lastKey: string | null; lastAt: number } + +/** Typing into one field within this time is one undo step. */ +export const COALESCE_MS = 1200; + +export class EditStore { + private byProject = new Map(); + private subs = new Set<() => void>(); + private version = 0; + + constructor(private now: () => number = () => Date.now()) {} + + private of(project: string): ProjectEdits { + let p = this.byProject.get(project); + if (!p) { p = { pending: new Map(), undo: [], redo: [], lastKey: null, lastAt: 0 }; this.byProject.set(project, p); } + return p; + } + private emit(): void { this.version++; for (const s of this.subs) s(); } + + subscribe = (fn: () => void): (() => void) => { this.subs.add(fn); return () => { this.subs.delete(fn); }; }; + snapshot = (): number => this.version; + + /** Sets a field; a value equal to the saved one drops the pending edit. */ + set(project: string, op: EditOp, area: EditArea, saved: unknown): void { + const p = this.of(project); + const key = keyOf(op); + const t = this.now(); + if (!(p.lastKey === key && t - p.lastAt < COALESCE_MS)) { p.undo.push(new Map(p.pending)); if (p.undo.length > 200) p.undo.shift(); } + p.redo = []; + p.lastKey = key; p.lastAt = t; + if (same(valueOf(op), saved)) p.pending.delete(key); + else p.pending.set(key, { key, op, area, saved }); + this.emit(); + } + + /** The pending value of a field, or `undefined` when it has none (use the saved value). */ + get(project: string, key: string): Pending | undefined { return this.byProject.get(project)?.pending.get(key); } + + list(project: string, area?: EditArea): Pending[] { + const all = [...(this.byProject.get(project)?.pending.values() ?? [])]; + return area ? all.filter(p => p.area === area) : all; + } + count(project: string, area?: EditArea): number { return this.list(project, area).length; } + /** Every app with unsaved edits. */ + dirtyProjects(): string[] { return [...this.byProject].filter(([, p]) => p.pending.size > 0).map(([k]) => k); } + + canUndo(project: string): boolean { return (this.byProject.get(project)?.undo.length ?? 0) > 0; } + canRedo(project: string): boolean { return (this.byProject.get(project)?.redo.length ?? 0) > 0; } + undo(project: string): void { + const p = this.of(project); + const prev = p.undo.pop(); + if (!prev) return; + p.redo.push(new Map(p.pending)); + p.pending = prev; p.lastKey = null; + this.emit(); + } + redo(project: string): void { + const p = this.of(project); + const next = p.redo.pop(); + if (!next) return; + p.undo.push(new Map(p.pending)); + p.pending = next; p.lastKey = null; + this.emit(); + } + + /** Drops the pending edits of one area (or all): after a save, or "Discard". Discard can be undone. */ + clear(project: string, area?: EditArea, o: { undoable?: boolean } = {}): void { + const p = this.of(project); + if (o.undoable) p.undo.push(new Map(p.pending)); + for (const [k, v] of p.pending) if (!area || v.area === area) p.pending.delete(k); + p.lastKey = null; + if (!o.undoable) { p.undo = []; p.redo = []; } + this.emit(); + } + + /** The ops of `storebound edit` for one area (or all), in a stable order. */ + ops(project: string, area?: EditArea): EditOp[] { return this.list(project, area).sort((a, b) => a.key.localeCompare(b.key)).map(p => p.op); } +} + +/** The window's one store of unsaved edits. */ +export const edits = new EditStore(); diff --git a/apps/desktop/src/lib/freshness.ts b/apps/desktop/src/lib/freshness.ts index 1866caa..7f68546 100644 --- a/apps/desktop/src/lib/freshness.ts +++ b/apps/desktop/src/lib/freshness.ts @@ -15,6 +15,7 @@ export const TTL: Record = { 'catalog.diff': 30 * MIN, 'prices.current': 30 * MIN, 'project.listings': 30 * MIN, + 'project.editable': 30 * MIN, 'apple.ppo_status': 30 * MIN, validate: 30 * MIN, scan: 30 * MIN, @@ -38,7 +39,7 @@ export function isStale(method: string, at: string | null | undefined, now = Dat export function lanesOf(method: string, o: { ios: boolean; android: boolean }): Lane[] { if (method.startsWith('apple.')) return ['apple']; if (method.startsWith('play.')) return ['play']; - if (['project.listings', 'scan', 'analytics.compare', 'aso.audit', 'reviews.drafts', 'project.declarations', 'project.renders', 'project.icon'].includes(method)) return ['local']; + if (['project.listings', 'project.editable', 'scan', 'analytics.compare', 'aso.audit', 'reviews.drafts', 'project.declarations', 'project.renders', 'project.icon'].includes(method)) return ['local']; const l: Lane[] = []; if (o.ios) l.push('apple'); if (o.android) l.push('play'); diff --git a/apps/desktop/src/screens/AppView.tsx b/apps/desktop/src/screens/AppView.tsx index 818ed46..6c528c0 100644 --- a/apps/desktop/src/screens/AppView.tsx +++ b/apps/desktop/src/screens/AppView.tsx @@ -23,6 +23,8 @@ import { PricesTab } from './tabs/Prices'; import { ReleasesTab } from './tabs/Releases'; import { ReviewsTab } from './tabs/Reviews'; import { TestFlightTab } from './tabs/TestFlight'; +import { EDIT_TABS, TabEditor, useUnsavedGuard } from './editors/TabEditor'; +import { useEdits } from '../ui/Editor'; export const ascUrl = (appId: string | null | undefined): string => (appId ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(appId)}/distribution` : 'https://appstoreconnect.apple.com/apps'); export const PLAY_CONSOLE = 'https://play.google.com/console/'; @@ -99,6 +101,8 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) { const android = e?.app?.platforms.android ?? (app.android ? { packageName: app.android.app.id } : null); const name = (app.project && e?.app?.name) || app.name; const tabs = tabsFor(!!app.project); + const ed = useEdits(); + useUnsavedGuard(); const tabRefs = useRef<(HTMLButtonElement | null)[]>([]); const studio = d.studios.find(s => s.id === app.studio) ?? null; const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: app.key, tab: x }); @@ -146,6 +150,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) { {tabs.map((x, i) => ( ))}
@@ -154,7 +159,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) { {tab === 'releases' && } {tab === 'catalog' && app.project && } {tab === 'prices' && app.project && } - {tab === 'listings' && app.project && } + {tab === 'listings' && app.project && <>} {tab === 'art' && app.project && } {tab === 'health' && } {tab === 'reviews' && } @@ -162,6 +167,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) { {tab === 'growth' && } {tab === 'appinfo' && app.project && } {tab === 'checks' && app.project && } + {tab !== 'listings' && app.project && !app.project.missing && EDIT_TABS[tab] && }
} diff --git a/apps/desktop/src/screens/editors/AppInfoEditor.tsx b/apps/desktop/src/screens/editors/AppInfoEditor.tsx new file mode 100644 index 0000000..cc2b320 --- /dev/null +++ b/apps/desktop/src/screens/editors/AppInfoEditor.tsx @@ -0,0 +1,152 @@ +// App info editors (App info tab): App Store categories, age rating answers, content rights, price, export +// compliance, App Review (sign-in, notes, contact; the demo account stays masked and is never read out); Google Play +// store settings (category, countries, managed publishing, target ages, delete-account page); Data safety and App +// Privacy answers; the App Store promotion blocks (promoted purchases, custom product pages, in-app events). Saved +// into the config (and the review contact into the private file in .storebound/), then applied per store with the dry run first. +import type { EditableResult, Project } from '../../api'; +import { type Key, t } from '../../i18n'; +import { AGE_FREQUENCY, AGE_RATING_NONE, APPLE_CATEGORIES, APPLE_GAME_SUBCATEGORIES, KIDS_AGE_BANDS, PLAY_AGE_GROUPS, PLAY_APP_CATEGORIES, PLAY_GAME_CATEGORIES } from '../../../../../cli/lib/store-catalogs'; +import { ApplyPanel, ChoiceField, EditBar, JsonField, ListField, TextField, useEdits } from '../../ui/Editor'; +import { StoreGlyph } from '../../ui/icons'; +import { Card } from '../../ui/kit'; + +type O = Record; +const obj = (v: unknown): O => (v && typeof v === 'object' && !Array.isArray(v) ? (v as O) : {}); +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); +const label = (id: string): string => id.replace(/^GAMES_/, '').toLowerCase().replace(/_/g, ' ').replace(/^\w/, c => c.toUpperCase()); +/** "alcoholTobaccoOrDrugUseOrReferences" -> "Alcohol tobacco or drug use or references". */ +const question = (q: string): string => q.replace(/([A-Z])/g, ' $1').toLowerCase().replace(/^\w/, c => c.toUpperCase()); +const yesNo = (): [string, string][] => [['true', t('common.yes')], ['false', t('common.no')]]; + +function AppleInfo({ project, data }: { project: Project; data: EditableResult }) { + const apple = obj(data.config.apple); + const info = obj(apple.info); + const cats = obj(info.categories); + const age = obj(info.ageRating); + const ra = obj(data.config.reviewAccess); + const games = cats.primary === 'GAMES'; + const catOpts = APPLE_CATEGORIES.map(c => [c, label(c)] as [string, string]); + const subOpts = APPLE_GAME_SUBCATEGORIES.map(c => [c, label(c)] as [string, string]); + const contact = data.contact; + return ( + <> + {t('ed.appleInfoSub')}}> +
+ + {games && } + {games && } + + + + + +
+
+ +
+ {Object.entries(AGE_RATING_NONE).map(([q, none]) => ( + [b, label(b)] as [string, string]) : typeof none === 'boolean' ? yesNo() : AGE_FREQUENCY.map(f => [f, label(f)] as [string, string])} + hint={age[q] === undefined ? t('ed.ageDefault', { value: none === null ? t('ed.none') : typeof none === 'boolean' ? t('common.no') : label(String(none)) }) : undefined} /> + ))} +
+
+ +
+ + + + {(['firstName', 'lastName', 'phone', 'email'] as const).map(f => ( + + ))} +
{data.demoAccount ? `${data.demoAccount} · ••••••••` : t('ed.notSet')}
{t('ed.demoHint')}
+
+
+ + ); +} + +function PlaySettings({ project, data }: { project: Project; data: EditableResult }) { + const play = obj(data.config.play); + const acc = obj(data.config.accounts); + const cats: [string, string][] = [...PLAY_GAME_CATEGORIES.map(c => [c, `${t('ed.game')}: ${c}`] as [string, string]), ...PLAY_APP_CATEGORIES.map(c => [c, `${t('ed.app')}: ${c}`] as [string, string])]; + return ( + {t('ed.playSettingsSub')}}> +
+ + + + + +
+
+ ); +} + +function Declarations({ project, data }: { project: Project; data: EditableResult }) { + const ds = obj(data.config.dataSafety); + return ( + +
+ {data.play && } + {data.play && } + {data.play && } +
+ {data.play && } + {data.apple && } +
+ ); +} + +function Promotion({ project, data }: { project: Project; data: EditableResult }) { + const apple = obj(data.config.apple); + return ( + {t('ed.promoSub')}}> + + + +
+ + +
+
+ ); +} + +export function AppInfoEditor({ project, data, onSaved }: { project: Project; data: EditableResult; onSaved: () => void }) { + const e = useEdits(); + const unsaved = e.count(project.id, 'appinfo') ? t('ed.saveFirst') : null; + return ( +
+ {data.apple && } + {data.play && } + + {data.apple && } + + +
+ {data.apple && ( +
+
App Store
+ + + +
+ )} + {data.play && ( +
+
Google Play
+ + + {t('ed.playConsoleOnly')} +
+ )} +
+
+
+ ); +} diff --git a/apps/desktop/src/screens/editors/ArtEditor.tsx b/apps/desktop/src/screens/editors/ArtEditor.tsx new file mode 100644 index 0000000..4829e24 --- /dev/null +++ b/apps/desktop/src/screens/editors/ArtEditor.tsx @@ -0,0 +1,57 @@ +// Store art editor (Store art tab): the order of the screenshot scenes (the store shows them in this order) and the +// raw frame each scene shows (replace a screenshot by pointing the scene at another frame). Saved into the config; +// then render, and upload to each store with the dry run in the window (uploads replace the store's sets). +import type { EditableResult, Project } from '../../api'; +import { t } from '../../i18n'; +import { ApplyPanel, EditBar, TextField, useEdits } from '../../ui/Editor'; +import { Icon, StoreGlyph } from '../../ui/icons'; +import { Card, Empty } from '../../ui/kit'; +import { keyOf } from '../../lib/edits'; + +type Scene = { id: string; palette?: unknown; frames?: { src: string }[] } & Record; + +export function ArtEditor({ project, data, onSaved }: { project: Project; data: EditableResult; onSaved: () => void }) { + const e = useEdits(); + const saved = ((data.config as unknown as { shots?: { scenes?: Scene[] } | null }).shots?.scenes ?? []) as Scene[]; + const op = { kind: 'config' as const, path: 'shots.scenes' }; + const p = e.get(project.id, keyOf(op)); + const scenes = (p && p.op.kind === 'config' ? p.op.value : saved) as Scene[]; + const unsaved = e.count(project.id, 'art') ? t('ed.saveFirst') : null; + if (!saved.length) return {t('ed.artEmptyText')}; + const move = (i: number, d: -1 | 1) => { + const next = [...scenes]; + const j = i + d; + if (j < 0 || j >= next.length) return; + [next[i], next[j]] = [next[j]!, next[i]!]; + e.set(project.id, { ...op, value: next }, 'art', saved); + }; + return ( +
+ +
    + {scenes.map((s, i) => ( +
  1. + {i + 1} + {s.id} +
    + x.id === s.id)?.frames?.[0]?.src ?? ''} label={t('ed.frame')} mono /> +
    +
    + + +
    +
  2. + ))} +
+
+ + +
+
{t('act.render')}
+ {data.play &&
Google Play
} + {data.apple &&
App Store
} +
+
+
+ ); +} diff --git a/apps/desktop/src/screens/editors/CatalogEditor.tsx b/apps/desktop/src/screens/editors/CatalogEditor.tsx new file mode 100644 index 0000000..27380c4 --- /dev/null +++ b/apps/desktop/src/screens/editors/CatalogEditor.tsx @@ -0,0 +1,148 @@ +// Catalog editor (Catalog tab): every in-app product and subscription of the config with its names and descriptions +// per language (live counters against the store limits), base price in USD, reference name, review note, and the +// offer blocks (introductory and promotional offers, offer codes, win-back) as checked JSON. Saved into the config, +// then applied per store with the dry run in the window. A price change of a product that is already live goes +// through the owner's price decision (the Catalog tab's "Apply the price changes" owner actions). +import { useState } from 'react'; +import type { EditableResult, Project } from '../../api'; +import { t } from '../../i18n'; +import { ApplyPanel, ChoiceField, EditBar, JsonField, ListField, NumberField, TextField, useEdits } from '../../ui/Editor'; +import { Icon, StoreGlyph } from '../../ui/icons'; +import { Card, Chip, Empty } from '../../ui/kit'; + +type O = Record; +const obj = (v: unknown): O => (v && typeof v === 'object' && !Array.isArray(v) ? (v as O) : {}); +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); +const PERIODS: [string, string][] = [['P1W', '1 week'], ['P1M', '1 month'], ['P2M', '2 months'], ['P3M', '3 months'], ['P6M', '6 months'], ['P1Y', '1 year']]; + +function Listings({ project, data, base, listings, limits, benefits }: { project: Project; data: EditableResult; base: string; listings: O; limits: { title: number; description: number }; benefits?: boolean }) { + return ( +
+ {data.languages.map(l => { + const x = obj(listings[l.id]); + return ( +
+
{l.id}
+
+ + + {benefits && } +
+
+ ); + })} +
+ ); +} + +function ProductCard({ project, data, p }: { project: Project; data: EditableResult; p: O }) { + const [open, setOpen] = useState(false); + const base = `products[id=${String(p.id)}]`; + const lim = data.limits.iap as Record; + const e = useEdits(); + const n = e.list(project.id, 'catalog').filter(x => x.key.startsWith(`config:${base}`)).length; + return ( +
+ + {open && ( +
+
+ + + + + +
+ + +
+ )} +
+ ); +} + +function SubCard({ project, data, group, s }: { project: Project; data: EditableResult; group: string; s: O }) { + const [open, setOpen] = useState(false); + const base = `subscriptions[name=${group}].subscriptions[id=${String(s.id)}]`; + const lim = data.limits.appleSub as Record; + return ( +
+ + {open && ( +
+
+ + + + + +
+ + + + + +
+ )} +
+ ); +} + +export function CatalogEditor({ project, data, onSaved }: { project: Project; data: EditableResult; onSaved: () => void }) { + const e = useEdits(); + const products = data.config.products as O[]; + const groups = data.config.subscriptions as O[]; + const unsaved = e.count(project.id, 'catalog') ? t('ed.saveFirst') : null; + if (!products.length && !groups.length) { + return {t('ed.catalogEmptyText')}; + } + return ( +
+ {products.length > 0 && ( + +
{products.map(p => )}
+
+ )} + {groups.map(g => ( + +
+
+ {data.languages.map(l => ( +
{l.id}
+ +
+ ))} +
+
+
{(g.subscriptions as O[]).map(s => )}
+
+ ))} + + +
+ {data.play && ( +
+
Google Play
+ {products.length > 0 && } + {groups.length > 0 && } +
+ )} + {data.apple && ( +
+
App Store
+ {products.length > 0 && } + {groups.length > 0 && } + {products.length > 0 && } +
+ )} +
+

{t('ed.priceGate')}

+
+
+ ); +} diff --git a/apps/desktop/src/screens/editors/ListingEditor.tsx b/apps/desktop/src/screens/editors/ListingEditor.tsx new file mode 100644 index 0000000..ae322a6 --- /dev/null +++ b/apps/desktop/src/screens/editors/ListingEditor.tsx @@ -0,0 +1,163 @@ +// The listing editor (Listings tab): per language, the Google Play and App Store texts side by side with live +// counters against the store limits and the checks of `check --aso` / `scan` as the owner types; the shared store +// details (URLs, contact, copyright, promo video); Save into store/listing.md, store/appstore.md and the config +// (project.edit), Pull the live texts into the files (diff first), and Apply to each store (dry run in the window). +import { useState } from 'react'; +import type { EditableListing, EditableResult, Project } from '../../api'; +import { type Key, t } from '../../i18n'; +import { appleLocaleIssues, playLangIssues, type FieldIssue } from '../../../../../cli/lib/listing-rules'; +import { keyOf } from '../../lib/edits'; +import { useData, useWrite } from '../../store'; +import { ApplyPanel, EditBar, type FieldIssueView, TextField, useEdits } from '../../ui/Editor'; +import { Icon, StoreGlyph } from '../../ui/icons'; +import { Card, Chip, Notice } from '../../ui/kit'; +import { WriteButton } from '../../ui/WriteButton'; + +const PLAY: { f: string; label: Key; multiline?: boolean; rows?: number; mono?: boolean }[] = [ + { f: 'title', label: 'lst.title' }, { f: 'short', label: 'lst.short' }, { f: 'full', label: 'lst.full', multiline: true, rows: 10 }, { f: 'whatsNew', label: 'lst.whatsNew', multiline: true, rows: 4 }, +]; +const APPLE: { f: string; label: Key; multiline?: boolean; rows?: number; mono?: boolean }[] = [ + { f: 'name', label: 'lst.name' }, { f: 'subtitle', label: 'lst.subtitle' }, { f: 'promotionalText', label: 'lst.promo', multiline: true, rows: 3 }, + { f: 'keywords', label: 'lst.keywords', mono: true }, { f: 'description', label: 'lst.description', multiline: true, rows: 10 }, { f: 'whatsNew', label: 'lst.whatsNew', multiline: true, rows: 4 }, +]; + +/** The values of one listing language with the unsaved edits on top. */ +function current(e: ReturnType, project: Project, store: 'play' | 'apple', l: EditableListing, fields: string[]): Record { + const out: Record = {}; + for (const f of fields) { + const p = e.get(project.id, keyOf({ kind: 'listing', store, lang: l.lang, field: f, value: '' })); + out[f] = p && p.op.kind === 'listing' ? p.op.value : l.values[f] ?? ''; + } + return out; +} +const byField = (issues: FieldIssue[], f: string): FieldIssueView[] => issues.filter(i => i.field === f).map(i => ({ level: i.level, msg: i.msg })); + +function StoreColumn({ project, data, store, l }: { project: Project; data: EditableResult; store: 'play' | 'apple'; l: EditableListing }) { + const e = useEdits(); + const defs = store === 'play' ? PLAY : APPLE; + const lim = (data.limits[store] ?? {}) as Record; + const vals = current(e, project, store, l, defs.map(d => d.f)); + const issues = store === 'play' + ? playLangIssues(l.lang, { title: vals.title || undefined, short: vals.short, full: vals.full, whatsNew: vals.whatsNew }, data.appName) + : appleLocaleIssues(l.lang, Object.fromEntries(Object.entries(vals).filter(([, v]) => v)), data.appleName); + // a new section starts empty: say what is required instead of a wall of errors + const fresh = !l.exists && Object.values(vals).every(v => !v); + return ( +
+
{store === 'play' ? 'Google Play' : 'App Store'}{l.lang} + {l.status && {l.status === 'draft' ? t('ed.statusDraft') : t('ed.statusTranslate')}} + {(l.codes?.length ?? 0) > 1 && {t('ed.alsoServes', { codes: l.codes!.filter(c => c !== l.lang).join(', ') })}} +
+ {fresh && {t('ed.newSection', { lang: l.lang })}} + {defs.map(d => ( + + ))} +
+ ); +} + +const DETAILS: { path: string; label: Key; kind?: 'url' | 'email'; store?: 'play' | 'apple'; hint?: Key }[] = [ + { path: 'app.supportUrl', label: 'ed.supportUrl', kind: 'url' }, { path: 'app.marketingUrl', label: 'ed.marketingUrl', kind: 'url' }, + { path: 'app.privacyPolicyUrl', label: 'ed.privacyUrl', kind: 'url' }, { path: 'app.termsUrl', label: 'ed.termsUrl', kind: 'url', hint: 'ed.termsHint' }, + { path: 'app.website', label: 'ed.website', kind: 'url', hint: 'ed.websiteHint' }, { path: 'app.contactEmail', label: 'ed.contactEmail', kind: 'email' }, + { path: 'app.copyright', label: 'ed.copyright' }, { path: 'play.video', label: 'ed.video', kind: 'url', store: 'play', hint: 'ed.videoHint' }, +]; + +export function StoreDetails({ project, data }: { project: Project; data: EditableResult }) { + const c = data.config; + const get = (p: string): string => { + const [a, b] = p.split('.') as [string, string]; + const o = (c as unknown as Record | null>)[a]; + return o && typeof o[b] === 'string' ? (o[b] as string) : ''; + }; + return ( +
+ {DETAILS.filter(d => !d.store || (d.store === 'play' ? !!data.play : !!data.apple)).map(d => { + const v = get(d.path); + return ; + })} +
+ ); +} + +export function ListingEditor({ project, data, onSaved }: { project: Project; data: EditableResult; onSaved: () => void }) { + const d = useData(); + const e = useEdits(); + const w = useWrite(project.id); + const live = d.liveOf(project); + const [lang, setLang] = useState(data.languages[0]?.id ?? ''); + const [code, setCode] = useState(null); + const [version, setVersion] = useState(live?.release.next?.ios?.version ?? live?.release.next?.version ?? ''); + const L = data.languages.find(x => x.id === lang) ?? data.languages[0]; + const playL = data.play?.filter(x => x.language === L?.id) ?? []; + const pl = playL.find(x => x.lang === code) ?? playL[0]; + const al = data.apple?.find(x => x.language === L?.id); + const unsaved = e.count(project.id, 'listings'); + const okVersion = /^\d+(\.\d+){0,2}$/.test(version); + const files = [data.files.play, data.files.apple, data.files.config]; + return ( + <> + + {data.play && {t('ed.pullPlay')}} + {data.apple && {t('ed.pullApple')}} + }> +
+ {unsaved > 0 && {t('ed.pullNote')}} +
+ {data.languages.map(x => { + const n = e.list(project.id, 'listings').filter(p => p.op.kind === 'listing' && (p.op.lang === x.apple || x.play.includes(p.op.lang))).length; + return ( + + ); + })} +
+ {playL.length > 1 && ( +
+ {t('ed.playCode')} + {playL.map(x => )} +
+ )} + {L?.rtl && {t('ed.rtl')}} +
+ {pl && } + {al && } + {!pl && !al && {t('ed.noStoreForLang', { lang: L?.id ?? '' })}} +
+
+
+ + + + + +
+ {data.play && ( +
+
Google Play
+ +
+ )} + {data.apple && ( +
+
App Store
+
+ + setVersion(ev.target.value.trim())} placeholder="2.4.0" /> +
+ +
+ )} +
+

{t('ed.applyNote')}

+
+ + ); +} diff --git a/apps/desktop/src/screens/editors/TabEditor.tsx b/apps/desktop/src/screens/editors/TabEditor.tsx new file mode 100644 index 0000000..462fae0 --- /dev/null +++ b/apps/desktop/src/screens/editors/TabEditor.tsx @@ -0,0 +1,47 @@ +// The editor of an app tab (console parity: every value the stores' consoles let the owner edit and storebound can +// write is edited here): loads what the files hold once (project.editable) and shows the tab's editor. +import { useEffect } from 'react'; +import type { Project } from '../../api'; +import { t } from '../../i18n'; +import { edits } from '../../lib/edits'; +import type { AppTab } from '../../nav'; +import { useEditable } from '../../ui/Editor'; +import { Card, ErrorNotice, Skeleton } from '../../ui/kit'; +import { AppInfoEditor } from './AppInfoEditor'; +import { ArtEditor } from './ArtEditor'; +import { CatalogEditor } from './CatalogEditor'; +import { ListingEditor } from './ListingEditor'; +import { TestFlightEditor } from './TestFlightEditor'; + +/** Tabs with an editor, and the edit area each one keeps its unsaved edits in. */ +export const EDIT_TABS: Partial> = { + listings: 'listings', appinfo: 'appinfo', catalog: 'catalog', testflight: 'testflight', art: 'art', +}; + +export function TabEditor({ tab, project }: { tab: AppTab; project: Project }) { + const r = useEditable(project); + if (!EDIT_TABS[tab]) return null; + if (!r.data) return r.error ? : ; + const p = { project, data: r.data, onSaved: () => { r.refresh(); } }; + switch (tab) { + case 'listings': return ; + case 'appinfo': return ; + case 'catalog': return ; + case 'testflight': return ; + case 'art': return ; + default: return null; + } +} + +/** Closing or reloading the window with unsaved edits asks first. */ +export function useUnsavedGuard(): void { + useEffect(() => { + const on = (ev: BeforeUnloadEvent) => { + if (!edits.dirtyProjects().length) return; + ev.preventDefault(); + ev.returnValue = ''; + }; + window.addEventListener('beforeunload', on); + return () => window.removeEventListener('beforeunload', on); + }, []); +} diff --git a/apps/desktop/src/screens/editors/TestFlightEditor.tsx b/apps/desktop/src/screens/editors/TestFlightEditor.tsx new file mode 100644 index 0000000..9507aab --- /dev/null +++ b/apps/desktop/src/screens/editors/TestFlightEditor.tsx @@ -0,0 +1,48 @@ +// TestFlight editor (TestFlight tab): What to Test per locale (### whatToTest in the App Store listing file), the +// Beta App Description per language, notes for Beta App Review, and the beta groups (checked JSON). Saved into the +// files, then applied with the dry run in the window: test information, and creating the missing groups. Sending a +// build to external testers and Beta App Review stay the owner's terminal steps. +import type { EditableResult, Project } from '../../api'; +import { t } from '../../i18n'; +import { ApplyPanel, EditBar, JsonField, TextField, useEdits } from '../../ui/Editor'; +import { Card } from '../../ui/kit'; + +type O = Record; +const obj = (v: unknown): O => (v && typeof v === 'object' && !Array.isArray(v) ? (v as O) : {}); + +export function TestFlightEditor({ project, data, onSaved }: { project: Project; data: EditableResult; onSaved: () => void }) { + const e = useEdits(); + const tf = obj(obj(data.config.apple).testflight); + const desc = tf.description; + const unsaved = e.count(project.id, 'testflight') ? t('ed.saveFirst') : null; + if (!data.apple) return null; + return ( +
+ +
+ {data.apple.map(l => ( +
+
{l.lang}
+ + {typeof desc !== 'string' && ( + + )} +
+ ))} +
+ {typeof desc === 'string' && } + + +
+ + +
+ + +
+
+
+ ); +} diff --git a/apps/desktop/src/screens/tabs/Listings.tsx b/apps/desktop/src/screens/tabs/Listings.tsx index a171b1a..44753b1 100644 --- a/apps/desktop/src/screens/tabs/Listings.tsx +++ b/apps/desktop/src/screens/tabs/Listings.tsx @@ -61,17 +61,14 @@ 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). */ +/** Upload the art and render it (each a dry run, a native dialog, then the real run). The listing text is edited and + * applied in the listing editor above (screens/editors/ListingEditor.tsx). */ 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 ( @@ -79,18 +76,12 @@ function StoreActions({ project, langs }: { project: Project; langs: string[] }) {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')}
diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index 8685ddd..07aeeda 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -957,3 +957,52 @@ button.ck.ck-pick[aria-checked="true"] { border-color: var(--accent-solid); box- .crash-msg, .crash-detail { margin: 0; padding: 10px 12px; border-radius: 8px; background: var(--bg-sunken); color: var(--ink); font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 320px; overflow: auto; } .crash-box summary { cursor: pointer; color: var(--ink-2); font-size: 13px; } .crash-box .actions { display: flex; gap: 8px; flex-wrap: wrap; } + +/* ---- editors (ui/Editor.tsx, screens/editors) ---- */ +.btn-xs { height: 22px; padding: 0 7px; font-size: var(--t-micro); border-radius: 6px; gap: 4px; } +.btn-xs svg { width: 12px; height: 12px; } +.ed-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 18px; align-items: start; } +.ed-col { display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.ed-col .act-head { flex-wrap: wrap; } +.ed-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px 16px; align-items: start; } +.ed-grid.three { grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); } +.ed-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.ed-field .input { width: 100%; max-width: none; } +.ed-field textarea.input { min-height: 0; } +.ed-field.dirty .input { border-color: var(--accent-line); background: color-mix(in srgb, var(--accent-soft) 45%, var(--surface)); } +.ed-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; font-size: var(--t-meta); color: var(--muted); } +.ed-head label { display: inline-flex; align-items: center; gap: 6px; font-weight: 600; color: var(--ink-2, var(--ink)); } +.ed-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent-solid); margin-left: 6px; flex: none; } +.ed-count { font-size: var(--t-micro); color: var(--muted); font-variant-numeric: tabular-nums; } +.ed-count.warn { color: var(--warn-ink); font-weight: 600; } +.ed-count.bad { color: var(--bad-ink); font-weight: 700; } +.ed-was { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.ed-was-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.ed-issues { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; font-size: var(--t-meta); } +.ed-issues li { display: flex; gap: 6px; align-items: flex-start; line-height: 1.4; } +.ed-issues li svg { flex: none; margin-top: 2px; } +.ed-issues li.error { color: var(--bad-ink); } +.ed-issues li.warn { color: var(--warn-ink); } +.ed-issues li.info { color: var(--muted); } +.ed-bar { position: sticky; bottom: 0; z-index: 5; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface); box-shadow: 0 -4px 14px rgba(0, 0, 0, .05); } +.ed-bar.active { border-color: var(--accent-line); } +.ed-review { margin-top: 10px; display: flex; flex-direction: column; gap: 10px; } +.ed-review pre, .ed-diff pre { margin: 0; max-height: 320px; overflow: auto; padding: 10px 12px; border-radius: var(--r-sm); background: var(--code-bg); color: var(--code-ink); font: 12px/1.45 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; } +.ed-dry.bad { outline: 1px solid var(--bad-solid); } +.ed-changes { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.ed-changes li { min-width: 0; overflow-wrap: anywhere; } +.ed-from { color: var(--muted); text-decoration: line-through; } +.ed-to { color: var(--ink); font-weight: 600; } +.ed-diff summary { cursor: pointer; } +.ed-apply { display: flex; flex-direction: column; gap: 6px; width: 100%; } +.ed-langs { display: flex; flex-direction: column; gap: 12px; } +.ed-lang { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r-sm); } +.ed-items { display: flex; flex-direction: column; } +.ed-item { border-top: 1px solid var(--line); } +.ed-item-head { display: flex; align-items: center; gap: 8px; width: 100%; padding: 10px 14px; background: none; border: 0; color: inherit; text-align: left; cursor: pointer; font: inherit; } +.ed-item-head:hover { background: var(--hover); } +.ed-item-body { padding: 4px 14px 14px; gap: 12px; } +.ed-scenes { list-style: none; margin: 0; padding: 0; } +.ed-scenes li { display: grid; grid-template-columns: 28px minmax(80px, 140px) minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 10px 14px; border-top: 1px solid var(--line); } +.ed-scene-frame { min-width: 0; } +.rot90 { transform: rotate(90deg); } diff --git a/apps/desktop/src/ui/Editor.tsx b/apps/desktop/src/ui/Editor.tsx new file mode 100644 index 0000000..7479ebe --- /dev/null +++ b/apps/desktop/src/ui/Editor.tsx @@ -0,0 +1,298 @@ +// The building blocks of the window's editors (console parity, docs/console-parity.md): +// - useEditable: the values the files hold (project.editable = `storebound edit --show --json`, offline) +// - fields (text, multi-line, number, yes / no, choice, list) that keep unsaved edits in lib/edits.ts, with the +// store limit as a live counter, the checks of `check` / `scan` as the owner types, and "was: …" with a reset +// - EditBar: unsaved count, undo / redo, discard, and "Review and save": the dry run of project.edit in the window +// (old -> new, the diff per file, the checks, git), then Save (native dialog, then the files are written) +// - ApplyPanel: a store write's dry run in the window (old -> new per store and language), then Apply (native +// dialog, the real run) +// - GitNote: the edited files are uncommitted in git (storebound never commits) +import { useCallback, useEffect, useState, useSyncExternalStore, type ReactNode } from 'react'; +import { api, type EditableResult, type EditResult, type Project, type ToolResult } from '../api'; +import { t } from '../i18n'; +import { type EditArea, type EditOp, edits, keyOf } from '../lib/edits'; +import { failureText } from '../lib/results'; +import { useRead, useWrite } from '../store'; +import { Icon, type IconName } from './icons'; +import { Chip, Notice } from './kit'; +import { emailIssue, urlIssue } from '../../../../cli/lib/listing-rules'; +import { WriteButton } from './WriteButton'; + +/** Characters as the stores count them (code points). */ +export const chars = (s: string): number => [...s].length; + +export function useEditable(project: Project) { + return useRead(project.id, 'project.editable', { network: false }); +} + +/** Re-renders on every change of the unsaved edits. */ +export function useEdits(): typeof edits { + useSyncExternalStore(edits.subscribe, edits.snapshot); + return edits; +} + +export interface FieldIssueView { level: 'error' | 'warn' | 'info'; msg: string } + +/** The current value of a field: the unsaved edit, else the saved one. */ +export function useValue(project: Project, op: EditOp, saved: T): { value: T; dirty: boolean } { + const e = useEdits(); + const p = e.get(project.id, keyOf(op)); + if (!p) return { value: saved, dirty: false }; + const v = p.op.kind === 'config' ? (p.op.remove ? undefined : p.op.value) : p.op.value; + return { value: (v ?? (typeof saved === 'string' ? '' : v)) as T, dirty: true }; +} + +function Counter({ n, limit }: { n: number; limit: number }) { + const tone = n > limit ? 'bad' : n > limit * 0.95 ? 'warn' : ''; + return {n} / {limit}; +} + +function Issues({ issues }: { issues: FieldIssueView[] }) { + if (!issues.length) return null; + return ( +
    + {issues.map((i, k) =>
  • {i.msg}
  • )} +
+ ); +} + +interface FieldBase { project: Project; area: EditArea; label: string; hint?: ReactNode; issues?: FieldIssueView[]; id?: string; disabled?: boolean } + +/** A text field: one line or several, a live character counter against the store limit. */ +export function TextField({ project, area, op, saved, label, limit, multiline, rows = 3, placeholder, hint, issues = [], mono, id, disabled, kind }: FieldBase & { + /** The edit without its value: { kind: 'listing', store, lang, field } or { kind: 'config', path } or contact. */ + op: Omit, 'value'> | { kind: 'config'; path: string } | { kind: 'contact'; field: Extract['field'] }; + saved: string; limit?: number; multiline?: boolean; rows?: number; placeholder?: string; mono?: boolean; kind?: 'url' | 'email' | 'text'; +}) { + const e = useEdits(); + const make = (v: string): EditOp => (op.kind === 'config' ? (v === '' ? { kind: 'config', path: op.path, remove: true } : { kind: 'config', path: op.path, value: v }) : { ...op, value: v } as EditOp); + const { value, dirty } = useValue(project, make(saved), saved); + const fid = id ?? `ed-${keyOf(make('')).replace(/[^A-Za-z0-9_-]/g, '-')}`; + const n = chars(value ?? ''); + const set = (v: string) => e.set(project.id, make(v), area, saved); + const common = { id: fid, className: `input${mono ? ' mono' : ''}`, value: value ?? '', placeholder, disabled, 'aria-invalid': issues.some(i => i.level === 'error') || undefined, + onChange: (ev: { target: { value: string } }) => set(ev.target.value), 'data-edit': keyOf(make('')) }; + return ( +
+
+ + {limit !== undefined && } +
+ {multiline ?