Desktop: never a blank window (frozen-prototype fix, error screens, logs, state migration, boot check)

The signed release showed only its background colour and never started the sidecar. Tauri's freezePrototype
freezes Object.prototype before the bundle runs; d3-color and d3-format (under the visx charts) assign
`constructor` / `toString` on plain objects while loading, which throws on a frozen prototype, so the bundle
stopped before React drew anything. The saved state was not the cause.

- build/freeze-safe.ts: Vite plugin that rewrites those assignments in dependencies into a helper that defines
  the property when the frozen prototype would refuse it
- error boundaries for the window, each screen and each app tab (Copy details, Reload, Reset saved state with a
  backup); public/boot.js shows the same panel when the bundle fails or the window stays empty
- logs/host.log (start, saved state, sidecar start/stop, panics) and logs/webview.log (log_webview), rotated,
  home as ~, keys, tokens and e-mail addresses replaced
- state.json `version` 2 with an explicit 1 -> 2 migration (original kept as state.json.v1.bak), per-entry
  tolerant parsing, partial settings keep their fields, unreadable files kept aside
- folders that are gone: "Folder not found" with Locate... (project_locate) / Remove; portfolio reads skip them
- tools/desktop-boot-check.ts: the built window with the release CSP and the frozen prototype, a mocked host from
  the state fixtures (empty, D1 with folders gone, D3) and the real sidecar, through every screen; in bun run ci,
  the Forgejo CI workflow and the macOS release
This commit is contained in:
CRTkafa 2026-10-11 01:36:34 +00:00
parent 209b8d0559
commit 08eb314196
45 changed files with 2080 additions and 69 deletions

View file

@ -21,6 +21,7 @@ import { Icon, type IconName, Mark } from './ui/icons';
import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit';
import { type Command, Palette } from './ui/Palette';
import { ExportMenu, useExportItems, useRunExport } from './ui/Exports';
import { ErrorBoundary } from './ui/ErrorBoundary';
import { Toasts } from './ui/Toasts';
const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' };
@ -139,7 +140,8 @@ export function App({ onTheme }: { onTheme: () => void }) {
const appItem = (a: UnifiedApp) => {
const e = d.statusFor(a);
const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
const missing = !!a.project?.missing;
const bad = missing ? 1 : (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
return (
<div role="listitem" key={a.key}>
<button className="nav nav-app" aria-current={current({ screen: 'app', appId: a.key, tab: 'releases' })}
@ -147,7 +149,8 @@ export function App({ onTheme }: { onTheme: () => void }) {
<AppIcon name={a.name} src={d.iconFor(a)} />
<span className="grow">{a.name}</span>
{!a.project && <span className="so-dot" title={t('apps.storeOnlyHint')}><Icon name="cloud" /></span>}
{bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>}
{missing ? <span className="tag-count bad" title={t('folder.missingShort')} aria-label={t('folder.missingShort')}>!</span>
: bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>}
</button>
</div>
);
@ -220,19 +223,22 @@ export function App({ onTheme }: { onTheme: () => void }) {
<ExportMenu />
</header>
<main className="content" id="content" tabIndex={-1}>
{route.screen === 'portfolio' && <Portfolio />}
{route.screen === 'app' && app && <AppView key={app.key} app={app} tab={tabs.includes(route.tab) ? route.tab : 'releases'} />}
{route.screen === 'apps' && <AppFolders />}
{route.screen === 'accounts' && <Accounts focus={route.section} />}
{route.screen === 'ignored' && <Ignored />}
{route.screen === 'dependencies' && <Dependencies />}
{route.screen === 'settings' && <Settings onTheme={onTheme} section={route.section} />}
{/* one boundary per screen (keyed, so moving to another screen starts fresh): a failing screen keeps the shell */}
<ErrorBoundary key={route.screen === 'app' ? `app:${route.appId}` : route.screen} where={`screen ${route.screen}`}>
{route.screen === 'portfolio' && <Portfolio />}
{route.screen === 'app' && app && <AppView key={app.key} app={app} tab={tabs.includes(route.tab) ? route.tab : 'releases'} />}
{route.screen === 'apps' && <AppFolders />}
{route.screen === 'accounts' && <Accounts focus={route.section} />}
{route.screen === 'ignored' && <Ignored />}
{route.screen === 'dependencies' && <Dependencies />}
{route.screen === 'settings' && <Settings onTheme={onTheme} section={route.section} />}
</ErrorBoundary>
</main>
</div>
</div>
{palette && <Palette commands={commands} onClose={() => setPalette(false)} />}
{welcome && <Onboarding onClose={closeWelcome} />}
<Toasts />
{palette && <ErrorBoundary where="palette"><Palette commands={commands} onClose={() => setPalette(false)} /></ErrorBoundary>}
{welcome && <ErrorBoundary where="welcome"><Onboarding onClose={closeWelcome} /></ErrorBoundary>}
<ErrorBoundary where="toasts"><Toasts /></ErrorBoundary>
</NavCtx.Provider>
);
}

View file

@ -18,7 +18,7 @@ export type { ToolStatus } from '../../../cli/lib/tools';
export interface LocalTools { tools: import('../../../cli/lib/tools').ToolStatus[] }
export interface SidecarStatus { running: boolean; version: string; protocol: string; methods: Pick<MethodDescriptor, 'method' | 'title' | 'description' | 'kind' | 'network' | 'destructive' | 'json'>[]; tools: LocalTools | null }
/** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string; /** The folder is gone (moved, renamed, deleted): shown as "Folder not found". */ missing?: boolean }
export type AccountKind = 'play' | 'apple';
export interface Account { id: string; label: string; kind: AccountKind; created: string; studio?: string | null }
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
@ -126,6 +126,12 @@ export const api = {
pickPriceSheet: (projectId: string) => invoke<string | null>('price_sheet_pick', { projectId }),
/** Shows a path of an app folder in the file manager, or opens a folder / the gallery page. */
reveal: (projectId: string, rel = '', open = false) => invoke<void>('project_reveal', { projectId, rel, open }),
/** "Locate…" for a folder that is gone: native folder picker; the same app with its new path, or null. */
locateProject: (id: string) => invoke<Project | null>('project_locate', { id }),
/** Native confirmation, then state.json is moved aside (a backup) and the app starts empty. The backup path (~) or null. */
resetState: () => invoke<string | null>('state_reset'),
/** One entry in <app data>/logs/webview.log (sanitized and rate-limited by the host). */
logWebview: (level: 'error' | 'warn' | 'info', message: string, detail?: string) => invoke<void>('log_webview', { level, message, detail: detail ?? null }),
};
export type ExportKind = 'csv' | 'md' | 'json' | 'txt';

View file

@ -510,6 +510,9 @@ async function answer(cmd: string, a: Record<string, unknown>): Promise<unknown>
case 'export_save': await sleep(200); return `~/Downloads/${String(a.name)}.${String(a.kind)}`;
case 'price_sheet_pick': return `${HOME}/Downloads/prices-autumn.csv`;
case 'project_reveal': return null;
case 'project_locate': await sleep(200); return null;
case 'state_reset': return null;
case 'log_webview': console.info('[webview.log]', a.level, a.message); return null;
case 'project_remove': projects = projects.filter(p => p.id !== a.id); return null;
case 'project_set_accounts': { const p = projects.find(x => x.id === a.id)!; p.playAccount = (a.play as string | null) ?? null; p.appleAccount = (a.apple as string | null) ?? null; return p; }
case 'account_add_play': case 'account_add_apple': return null;

View file

@ -1225,4 +1225,28 @@ export const en = {
'wz.keysInto': 'New keys go into {name}.',
'wz.keysNoStudio': 'New keys stay without a studio.',
'wz.change': 'Change',
'crash.titleApp': 'storebound hit an error',
'crash.titleScreen': 'This screen hit an error',
'crash.leadApp': 'The window could not be shown. Your app folders, store keys and saved data are untouched. Reload usually fixes it; if it keeps happening, copy the details into a bug report.',
'crash.leadScreen': 'The rest of the app still works. Try again, reload the window, or copy the details into a bug report.',
'crash.details': 'Details',
'crash.copy': 'Copy details',
'crash.copied': 'Details copied.',
'crash.copyFailed': 'Could not copy: select the details and copy them by hand.',
'crash.retry': 'Try again',
'crash.reload': 'Reload',
'crash.reset': 'Reset saved state (keeps a backup)',
'crash.resetHint': 'Starts with an empty list. The saved state is kept as a backup file, store keys stay in the keychain, app folders are not touched.',
'crash.resetDone': 'Saved state reset. Backup: {path}. Reloading…',
'crash.logNote': 'Also written to logs/webview.log in the app data folder (home folder shown as ~, no keys).',
'folder.missing': 'Folder not found.',
'folder.missingText': 'storebound cannot find this app folder at {path}. It may have been moved, renamed or deleted. Locate it to keep its accounts and saved reads, or remove it from the list (no files are touched).',
'folder.missingShort': 'Folder not found',
'folder.locate': 'Locate…',
'folder.locateHint': 'Pick the folder that now holds this app\'s storebound.config.ts',
'folder.located': '{name} found',
'folder.locateFailed': 'Could not use that folder',
'folder.remove': 'Remove from list',
'folder.removed': '{name} removed from the list',
} as const;

View file

@ -1227,4 +1227,28 @@ export const tr: Record<keyof typeof en, string> = {
'wz.keysInto': 'Yeni anahtarlar {name} stüdyosuna gider.',
'wz.keysNoStudio': 'Yeni anahtarlar stüdyosuz kalır.',
'wz.change': 'Değiştir',
'crash.titleApp': 'storebound bir hatayla karşılaştı',
'crash.titleScreen': 'Bu ekran bir hatayla karşılaştı',
'crash.leadApp': 'Pencere gösterilemedi. Uygulama klasörleriniz, mağaza anahtarlarınız ve kayıtlı verileriniz olduğu gibi duruyor. Yeniden yüklemek genellikle düzeltir; tekrarlarsa ayrıntıları bir hata bildirimine kopyalayın.',
'crash.leadScreen': 'Uygulamanın geri kalanı çalışıyor. Yeniden deneyin, pencereyi yeniden yükleyin ya da ayrıntıları bir hata bildirimine kopyalayın.',
'crash.details': 'Ayrıntılar',
'crash.copy': 'Ayrıntıları kopyala',
'crash.copied': 'Ayrıntılar kopyalandı.',
'crash.copyFailed': 'Kopyalanamadı: ayrıntıları seçip elle kopyalayın.',
'crash.retry': 'Yeniden dene',
'crash.reload': 'Yeniden yükle',
'crash.reset': 'Kayıtlı durumu sıfırla (yedek tutulur)',
'crash.resetHint': 'Boş bir listeyle başlar. Kayıtlı durum bir yedek dosyada saklanır, mağaza anahtarları anahtar zincirinde kalır, uygulama klasörlerine dokunulmaz.',
'crash.resetDone': 'Kayıtlı durum sıfırlandı. Yedek: {path}. Yeniden yükleniyor…',
'crash.logNote': 'Uygulama veri klasöründeki logs/webview.log dosyasına da yazıldı (ana klasör ~ olarak, anahtarlar olmadan).',
'folder.missing': 'Klasör bulunamadı.',
'folder.missingText': 'storebound bu uygulama klasörünü {path} konumunda bulamıyor. Taşınmış, yeniden adlandırılmış ya da silinmiş olabilir. Hesaplarını ve kayıtlı okumalarını korumak için yerini gösterin ya da listeden kaldırın (hiçbir dosyaya dokunulmaz).',
'folder.missingShort': 'Klasör bulunamadı',
'folder.locate': 'Yerini göster…',
'folder.locateHint': 'Bu uygulamanın storebound.config.ts dosyasının artık bulunduğu klasörü seçin',
'folder.located': '{name} bulundu',
'folder.locateFailed': 'Bu klasör kullanılamadı',
'folder.remove': 'Listeden kaldır',
'folder.removed': '{name} listeden kaldırıldı',
};

View file

@ -0,0 +1,77 @@
// Uncaught errors of the window: one place that turns them into a readable report, sends it to
// <app data>/logs/webview.log (the host sanitizes again and rate-limits), and offers it for "Copy details".
// public/boot.js covers the time before React runs (a bundle that fails to load); from the first render on, React's
// root error callbacks, the error boundaries and the window handlers below report here.
import { api } from '../api';
export interface CrashReport { message: string; detail: string }
let home: string | null = null;
let version = '';
/** Shown as "~" in reports, like everywhere in the window. */
export function setCrashContext(h: string | null, v: string): void { home = h; version = v; }
const tilde = (s: string): string => {
const h = home?.replace(/[\\/]+$/, '');
return h && h.length > 1 ? s.split(h).join('~') : s;
};
export function errorMessage(e: unknown): string {
if (e instanceof Error) return `${e.name}: ${e.message}`;
if (typeof e === 'string') return e;
if (e && typeof e === 'object' && 'message' in e && typeof (e as { message: unknown }).message === 'string') return (e as { message: string }).message;
try { return JSON.stringify(e) ?? String(e); } catch { return String(e); }
}
/** Message plus a details block (where, version, time, stack, React component stack) with the home folder as ~. */
export function describe(where: string, e: unknown, componentStack?: string | null): CrashReport {
const message = tilde(errorMessage(e));
const lines = [
`storebound desktop ${version || '?'} · ${where}`,
`time: ${new Date().toISOString()}`,
'',
message,
];
const stack = e instanceof Error && e.stack ? e.stack : '';
if (stack) lines.push('', stack.trimEnd());
if (componentStack) lines.push('', 'component stack:', componentStack.trim());
return { message, detail: tilde(lines.join('\n')) };
}
const recent = new Map<string, number>();
/** Logs one report (the same message at most once every 10 s). Never throws. */
export function report(where: string, e: unknown, componentStack?: string | null, level: 'error' | 'warn' = 'error'): CrashReport {
const r = describe(where, e, componentStack);
const key = `${where}|${r.message}`;
const now = Date.now();
if ((recent.get(key) ?? 0) + 10_000 < now) {
recent.set(key, now);
if (recent.size > 100) recent.clear();
try { api.logWebview(level, `${where}: ${r.message}`, r.detail).catch(() => {}); } catch { /* no host (tests, a browser) */ }
}
return r;
}
/** window.onerror and unhandled promise rejections, after React took over from public/boot.js. */
export function installGlobalHandlers(): void {
// public/boot.js stops logging on its own from here
(window as { __storeboundCrashHandlers?: boolean }).__storeboundCrashHandlers = true;
window.addEventListener('error', ev => { report('window.onerror', ev.error ?? ev.message); });
window.addEventListener('unhandledrejection', ev => { report('unhandledrejection', ev.reason, null, 'warn'); });
}
/** Clipboard first, then the old selection way (the webview may refuse clipboard access). True when copied. */
export async function copyText(text: string): Promise<boolean> {
try { await navigator.clipboard.writeText(text); return true; } catch { /* fall through */ }
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.className = 'sr';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return ok;
} catch { return false; }
}

View file

@ -0,0 +1,68 @@
// What the host sends, made complete for the screens. The Rust host already fills defaults (store.rs migrates old
// state files), but the window must not depend on that: a field an older or newer host leaves out, or a value of the
// wrong type, becomes its default here instead of a "cannot read properties of undefined" at render time.
import { type Account, DEFAULT_SETTINGS, type Project, type Settings, STUDIO_COLORS, type Studio, type Workspace } from '../api';
import { NO_OVERRIDES, type Overrides } from './identity';
type Rec = Record<string, unknown>;
const isRec = (v: unknown): v is Rec => !!v && typeof v === 'object' && !Array.isArray(v);
const str = (v: unknown, d = ''): string => (typeof v === 'string' ? v : d);
const strOrNull = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
const folderName = (p: string): string => p.split(/[\\/]/).filter(Boolean).pop() ?? p;
export function normalizeProjects(v: unknown): Project[] {
const seen = new Set<string>();
return arr(v).filter(isRec).filter(p => typeof p.id === 'string' && typeof p.path === 'string' && !seen.has(p.id) && !!seen.add(p.id)).map(p => {
const path = p.path as string;
return { id: p.id as string, path, name: str(p.name).trim() || folderName(path), playAccount: strOrNull(p.playAccount), appleAccount: strOrNull(p.appleAccount), added: str(p.added), missing: p.missing === true };
});
}
export function normalizeAccounts(v: unknown): Account[] {
return arr(v).filter(isRec).filter(a => typeof a.id === 'string' && (a.kind === 'play' || a.kind === 'apple'))
.map(a => ({ id: a.id as string, label: str(a.label) || (a.id as string), kind: a.kind as Account['kind'], created: str(a.created), studio: strOrNull(a.studio) }));
}
function studios(v: unknown): Studio[] {
return arr(v).filter(isRec).filter(s => typeof s.id === 'string').map(s => ({
id: s.id as string,
name: str(s.name) || (s.id as string),
color: (STUDIO_COLORS as readonly string[]).includes(str(s.color)) ? (s.color as Studio['color']) : 'slate',
logo: typeof s.logo === 'string' && s.logo.startsWith('data:image/') ? s.logo : null,
created: str(s.created),
}));
}
function overrides(v: unknown): Overrides {
if (!isRec(v)) return NO_OVERRIDES;
const pairs = (x: unknown) => arr(x).filter(isRec).filter(p => typeof p.ios === 'string' && typeof p.android === 'string').map(p => ({ ios: p.ios as string, android: p.android as string }));
return {
pairs: pairs(v.pairs),
unpairs: pairs(v.unpairs),
links: arr(v.links).filter(isRec).filter(l => typeof l.key === 'string' && typeof l.project === 'string').map(l => ({ key: l.key as string, project: l.project as string })),
appStudio: arr(v.appStudio).filter(isRec).filter(l => typeof l.key === 'string' && typeof l.studio === 'string').map(l => ({ key: l.key as string, studio: l.studio as string })),
ignored: arr(v.ignored).filter((x): x is string => typeof x === 'string'),
};
}
function pick<T>(v: unknown, d: T, ok: (x: unknown) => boolean): T { return ok(v) ? (v as T) : d; }
const isNum = (x: unknown) => typeof x === 'number' && Number.isFinite(x);
const isBool = (x: unknown) => typeof x === 'boolean';
export function normalizeSettings(v: unknown): Settings {
const d = DEFAULT_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) },
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',
};
}
export function normalizeWorkspace(v: unknown): Workspace {
const w = isRec(v) ? v : {};
return { studios: studios(w.studios), overrides: overrides(w.overrides), settings: normalizeSettings(w.settings) };
}

View file

@ -5,7 +5,9 @@ import { devSwitch } from './dev/switches';
import { setLang } from './i18n';
import { applyPrefs, loadPrefs, type Prefs, resolveLang, savePrefs } from './prefs';
import { PrefsContext } from './prefs-ctx';
import { installGlobalHandlers, report } from './lib/crash';
import { DataProvider } from './store';
import { ErrorBoundary } from './ui/ErrorBoundary';
import { ExportProvider } from './ui/Exports';
import './styles.css';
@ -25,6 +27,8 @@ function Root() {
const lang = resolveLang(prefs.lang, systemLang());
setLang(lang);
useEffect(() => { applyPrefs(prefs, document.documentElement, systemLang()); }, [prefs]);
// React has the window now: public/boot.js stops watching for a blank start
useEffect(() => { document.documentElement.dataset.booted = '1'; }, []);
const update = useCallback((p: Prefs) => { setPrefs(p); savePrefs(p); }, []);
const onTheme = useCallback(() => {
const dark = prefs.theme === 'dark' || (prefs.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
@ -34,4 +38,12 @@ function Root() {
return <PrefsContext.Provider value={{ prefs, update }}><DataProvider><ExportProvider><App key={lang} onTheme={onTheme} /></ExportProvider></DataProvider></PrefsContext.Provider>;
}
createRoot(document.getElementById('root')!).render(<StrictMode><Root /></StrictMode>);
installGlobalHandlers();
createRoot(document.getElementById('root')!, {
// errors no boundary caught (a boundary's own fallback failing): logged; public/boot.js shows its plain panel
onUncaughtError: (e, info) => {
const r = report('react (uncaught)', e, info.componentStack);
(window as { __storeboundBlank?: (m: string, s?: string) => void }).__storeboundBlank?.(r.message, r.detail);
},
onRecoverableError: (e, info) => { report('react (recovered)', e, info.componentStack, 'warn'); },
}).render(<StrictMode><ErrorBoundary where="app" full><Root /></ErrorBoundary></StrictMode>);

View file

@ -8,12 +8,18 @@ import { shortPath, tildeText } from '../paths';
import { useNav } from '../nav';
import { useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons';
import { useFolderActions } from '../ui/FolderMissing';
import { AppIcon, Card, Chip, Empty, Notice, Seg, StoreBadge } from '../ui/kit';
import { checkState } from './Portfolio';
type Profile = 'app' | 'game' | 'subscription-app';
interface Run { title: string; project: string; job: string; lines: string[]; result?: ToolResult; outcome?: WriteOutcome; error?: string }
function LocateButton({ project }: { project: Project }) {
const { busy, locate } = useFolderActions(project);
return <button className="btn btn-sm btn-primary" onClick={locate} disabled={busy} title={t('folder.locateHint')}><Icon name="search" />{t('folder.locate')}</button>;
}
export function AppFolders() {
const d = useData();
const nav = useNav();
@ -88,7 +94,7 @@ export function AppFolders() {
<div className="list">
{d.projects.map(p => {
const e = d.statusOf(p);
const st = checkState(e);
const st = p.missing ? { text: t('folder.missingShort'), tone: 'bad' as const } : checkState(e);
return (
<div className="li" key={p.id} style={{ alignItems: 'center' }}>
<AppIcon name={p.name} src={d.icons[p.id]} />
@ -113,10 +119,12 @@ export function AppFolders() {
</select></label>
</div>
<div className="actions" style={{ flexWrap: 'nowrap' }}>
<button className="btn btn-sm" onClick={() => nav.go({ screen: 'app', appId: p.id, tab: 'releases' })} title={t('folders.openApp')}><Icon name="arrowRight" />{t('folders.open')}</button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => api.reveal(p.id).catch(e => setError(errorText(e)))} aria-label={t('folders.reveal')} title={t('folders.reveal')}><Icon name="eye" /></button>
<button className="btn btn-sm" onClick={() => check(p)} disabled={!!busy}><Icon name="shield" />{t('folders.check')}</button>
<button className="btn btn-sm" onClick={() => gallery(p)} disabled={!!busy} title={t('folders.galleryHint')}><Icon name="image" />{t('folders.gallery')}</button>
{p.missing ? <LocateButton project={p} /> : <>
<button className="btn btn-sm" onClick={() => nav.go({ screen: 'app', appId: p.id, tab: 'releases' })} title={t('folders.openApp')}><Icon name="arrowRight" />{t('folders.open')}</button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => api.reveal(p.id).catch(e => setError(errorText(e)))} aria-label={t('folders.reveal')} title={t('folders.reveal')}><Icon name="eye" /></button>
<button className="btn btn-sm" onClick={() => check(p)} disabled={!!busy}><Icon name="shield" />{t('folders.check')}</button>
<button className="btn btn-sm" onClick={() => gallery(p)} disabled={!!busy} title={t('folders.galleryHint')}><Icon name="image" />{t('folders.gallery')}</button>
</>}
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => remove(p)} disabled={!!busy} aria-label={t('folders.remove', { name: p.name })} title={t('folders.remove', { name: p.name })}><Icon name="trash" /></button>
</div>
</div>

View file

@ -9,6 +9,8 @@ import { storeNow } from '../lib/model';
import { type AppTab, TAB_ICON, TAB_KEY, tabsFor, useNav } from '../nav';
import { useData } from '../store';
import { Icon } from '../ui/icons';
import { ErrorBoundary } from '../ui/ErrorBoundary';
import { FolderMissing } from '../ui/FolderMissing';
import { AppIcon, Chip, Notice, PhaseChip, StoreBadge, StoreOnlyTag, StudioMark } from '../ui/kit';
import { AppInfoTab } from './tabs/AppInfo';
import { ArtTab } from './tabs/Art';
@ -138,7 +140,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
</div>
<AppControls app={app} />
{!app.project && <StoreOnlyBanner app={app} />}
{app.project?.missing ? <FolderMissing project={app.project} /> : <>
<div className="tabs" role="tablist" aria-label={t('app.sections', { name })} onKeyDown={onKey}>
{tabs.map((x, i) => (
<button key={x} ref={el => { tabRefs.current[i] = el; }} role="tab" id={`tab-${x}`} aria-selected={tab === x} aria-controls="tabpanel" tabIndex={tab === x ? 0 : -1} className="tab" onClick={() => setTab(x)}>
@ -147,18 +149,21 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
))}
</div>
<div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${tab}`} className="stack" style={{ gap: 16 }}>
{tab === 'releases' && <ReleasesTab app={app} />}
{tab === 'catalog' && app.project && <CatalogTab project={app.project} />}
{tab === 'prices' && app.project && <PricesTab project={app.project} />}
{tab === 'listings' && app.project && <ListingsTab project={app.project} />}
{tab === 'art' && app.project && <ArtTab project={app.project} />}
{tab === 'health' && <HealthTab app={app} />}
{tab === 'reviews' && <ReviewsTab app={app} />}
{tab === 'testflight' && <TestFlightTab app={app} />}
{tab === 'growth' && <GrowthTab app={app} />}
{tab === 'appinfo' && app.project && <AppInfoTab project={app.project} />}
{tab === 'checks' && app.project && <ChecksTab project={app.project} />}
<ErrorBoundary key={tab} where={`tab ${tab}`}>
{tab === 'releases' && <ReleasesTab app={app} />}
{tab === 'catalog' && app.project && <CatalogTab project={app.project} />}
{tab === 'prices' && app.project && <PricesTab project={app.project} />}
{tab === 'listings' && app.project && <ListingsTab project={app.project} />}
{tab === 'art' && app.project && <ArtTab project={app.project} />}
{tab === 'health' && <HealthTab app={app} />}
{tab === 'reviews' && <ReviewsTab app={app} />}
{tab === 'testflight' && <TestFlightTab app={app} />}
{tab === 'growth' && <GrowthTab app={app} />}
{tab === 'appinfo' && app.project && <AppInfoTab project={app.project} />}
{tab === 'checks' && app.project && <ChecksTab project={app.project} />}
</ErrorBoundary>
</div>
</>}
</div>
);
}

View file

@ -176,7 +176,7 @@ export function Portfolio() {
const row = (r: typeof all[number]) => {
const { app, e, l } = r;
const st = app.project ? checkState(e) : null;
const st = app.project?.missing ? { text: t('folder.missingShort'), tone: 'bad' as const } : app.project ? checkState(e) : null;
const cat = l?.catalog ?? e?.catalog;
const ios = !!(app.ios || e?.app?.platforms.ios), android = !!(app.android || e?.app?.platforms.android);
const sub = app.ios?.app.bundleId ?? e?.app?.platforms.ios?.bundleId ?? app.android?.app.id ?? e?.app?.platforms.android?.packageName ?? '';
@ -191,8 +191,8 @@ export function Portfolio() {
</div>
</div>
</td>
<td>{e || !app.project ? <StoreCell e={l} store="ios" on={ios} /> : <Skeleton lines={2} />}</td>
<td>{e || !app.project ? <StoreCell e={l} store="android" on={android} /> : <Skeleton lines={2} />}</td>
<td>{e || !app.project || app.project.missing ? <StoreCell e={l} store="ios" on={ios} /> : <Skeleton lines={2} />}</td>
<td>{e || !app.project || app.project.missing ? <StoreCell e={l} store="android" on={android} /> : <Skeleton lines={2} />}</td>
<td><NextCell e={l} /></td>
<td><HealthCell c={health[app.target]} android={android} /></td>
<td>

View file

@ -10,6 +10,8 @@ import { t } from './i18n';
import { buildApps, NO_OVERRIDES, type Overrides, type UnifiedApp } from './lib/identity';
import { isError, type HealthSnapshot, type Review } from './lib/model';
import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify';
import { setCrashContext } from './lib/crash';
import { normalizeAccounts, normalizeProjects, normalizeWorkspace } from './lib/normalize';
import { fixHint } from './lib/views';
export type ToastKind = 'job' | 'ok' | 'bad' | 'info';
@ -131,12 +133,14 @@ export function DataProvider({ children }: { children: ReactNode }) {
const reload = useCallback(async () => {
const [p, a, w, s] = await Promise.all([api.projects(), api.accounts(), api.workspace(), api.storeAppsCached()]);
setProjects(p);
setAccounts(a);
setStudios(w.studios);
setOverrides(w.overrides);
setSettings(w.settings);
setStoreApps(Object.fromEntries(s.map(x => [x.account, x.entry])));
// whatever an older or newer host sends, the screens get complete values (lib/normalize.ts)
const ws = normalizeWorkspace(w);
setProjects(normalizeProjects(p));
setAccounts(normalizeAccounts(a));
setStudios(ws.studios);
setOverrides(ws.overrides);
setSettings(ws.settings);
setStoreApps(Object.fromEntries((Array.isArray(s) ? s : []).filter(x => x && typeof x.account === 'string').map(x => [x.account, x.entry ?? null])));
}, []);
const apps = useMemo(() => buildApps({
@ -220,7 +224,7 @@ export function DataProvider({ children }: { children: ReactNode }) {
// start: app info, folders, accounts, workspace, sidecar, cached live portfolio
useEffect(() => {
api.appInfo().then(setInfo, () => {});
api.appInfo().then(i => { setInfo(i); setCrashContext(i.home, i.version); }, () => {});
reload().catch(() => {}).finally(() => setReady(true));
api.sidecarStatus().then(s => { setSidecar(s); setSidecarError(null); }, e => setSidecarError(errorText(e)));
api.cached<PortfolioResult>('portfolio.status', '*', { live: true }).then(e => { if (e) setLive(e); }, () => {});
@ -247,7 +251,7 @@ export function DataProvider({ children }: { children: ReactNode }) {
// icons: cached first, then read (offline, cheap)
useEffect(() => {
for (const p of projects) {
if (p.id in icons) continue;
if (p.id in icons || p.missing) continue;
setIcons(m => ({ ...m, [p.id]: null }));
api.cached<ToolResult & { data?: { dataUrl: string | null } }>('project.icon', p.id).then(c => {
if (c?.value.data?.dataUrl) setIcons(m => ({ ...m, [p.id]: c.value.data!.dataUrl }));

View file

@ -914,3 +914,14 @@ button.ck.ck-pick:focus-visible { outline: 2px solid var(--focus); outline-offse
button.ck.ck-pick[aria-checked="true"] { border-color: var(--accent-solid); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent-solid) 16%, transparent); }
.studio-new { cursor: default; }
.studio-new:hover { border-color: var(--line); box-shadow: none; }
/* Error screens: React error boundaries (ui/ErrorBoundary.tsx) and the plain panel of public/boot.js when the bundle
itself failed. Kept simple: they must render when everything else did not. */
.crash { padding: 24px 28px; }
.crash-full { min-height: 100%; display: grid; place-items: center; background: var(--bg); color: var(--ink); }
.crash-box { max-width: 760px; display: grid; gap: 12px; padding: 20px 22px; border: 1px solid var(--line-2); border-left: 4px solid var(--bad-solid); border-radius: 12px; background: var(--surface); }
.crash-box h2 { margin: 0; font-size: 17px; }
.crash-box p { margin: 0; color: var(--ink-2); line-height: 1.5; }
.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; }

View file

@ -0,0 +1,61 @@
// Error boundaries: a render error shows what failed and the ways out (Copy details, Reload, Reset saved state with a
// backup) instead of an empty window. One wraps the whole app (`full`), one each screen and app tab, so a broken
// screen leaves the sidebar and the other screens working. The fallback uses plain elements only: it must not fail
// the way the screen did.
import { Component, type ErrorInfo, type ReactNode, useState } from 'react';
import { api, errorText } from '../api';
import { t } from '../i18n';
import { type CrashReport, copyText, describe, report } from '../lib/crash';
interface Props { where: string; full?: boolean; children: ReactNode }
interface State { error: unknown; info: CrashReport | null }
export class ErrorBoundary extends Component<Props, State> {
override state: State = { error: null, info: null };
static getDerivedStateFromError(error: unknown): Partial<State> {
return { error: error ?? new Error('unknown error') };
}
override componentDidCatch(error: unknown, info: ErrorInfo): void {
this.setState({ info: report(this.props.where, error, info.componentStack) });
}
override render(): ReactNode {
if (this.state.error === null) return this.props.children;
const info = this.state.info ?? describe(this.props.where, this.state.error);
return <CrashPanel where={this.props.where} full={!!this.props.full} info={info} onRetry={this.props.full ? undefined : () => this.setState({ error: null, info: null })} />;
}
}
export function CrashPanel({ where, full, info, onRetry }: { where: string; full: boolean; info: CrashReport; onRetry?: () => void }) {
const [note, setNote] = useState<string | null>(null);
const copy = async () => setNote((await copyText(info.detail)) ? t('crash.copied') : t('crash.copyFailed'));
const reset = async () => {
try {
const backup = await api.resetState();
if (backup !== null) { setNote(t('crash.resetDone', { path: backup || '-' })); setTimeout(() => location.reload(), 1200); }
} catch (e) { setNote(errorText(e)); }
};
return (
<div className={full ? 'crash crash-full' : 'crash'} role="alert" data-crash={where}>
<div className="crash-box">
<h2>{full ? t('crash.titleApp') : t('crash.titleScreen')}</h2>
<p>{full ? t('crash.leadApp') : t('crash.leadScreen')}</p>
<pre className="crash-msg selectable">{info.message}</pre>
<details>
<summary>{t('crash.details')}</summary>
<pre className="crash-detail selectable">{info.detail}</pre>
</details>
<div className="actions">
<button className="btn" onClick={copy}>{t('crash.copy')}</button>
{onRetry && <button className="btn" onClick={onRetry}>{t('crash.retry')}</button>}
<button className="btn btn-primary" onClick={() => location.reload()}>{t('crash.reload')}</button>
<button className="btn btn-ghost" onClick={reset} title={t('crash.resetHint')}>{t('crash.reset')}</button>
</div>
{note && <p className="small muted" role="status">{note}</p>}
<p className="small muted">{t('crash.logNote')}</p>
</div>
</div>
);
}

View file

@ -0,0 +1,42 @@
// An app folder that is gone (moved, renamed, deleted, or an old worktree): say so, and offer Locate… (keeps the app's
// id, accounts and saved reads) or Remove from the list (no files touched). Shown in the app view and the folder list.
import { useState } from 'react';
import { api, errorText, type Project } from '../api';
import { t } from '../i18n';
import { useNav } from '../nav';
import { shortPath } from '../paths';
import { useData } from '../store';
import { Icon } from './icons';
import { Notice } from './kit';
export function useFolderActions(p: Project) {
const d = useData();
const [busy, setBusy] = useState(false);
const locate = async () => {
setBusy(true);
try {
const found = await api.locateProject(p.id);
if (found) { await d.reload(); d.toast({ kind: 'ok', title: t('folder.located', { name: found.name }) }); }
} catch (e) { d.toast({ kind: 'bad', title: t('folder.locateFailed'), detail: errorText(e) }); } finally { setBusy(false); }
};
const remove = async (after?: () => void) => {
setBusy(true);
try { await api.removeProject(p.id); await d.reload(); d.toast({ kind: 'ok', title: t('folder.removed', { name: p.name }) }); after?.(); }
catch (e) { d.toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) }); } finally { setBusy(false); }
};
return { busy, locate, remove };
}
export function FolderMissing({ project }: { project: Project }) {
const d = useData();
const nav = useNav();
const { busy, locate, remove } = useFolderActions(project);
return (
<Notice tone="warn" icon="folder" action={<div className="actions">
<button className="btn btn-sm btn-primary" onClick={locate} disabled={busy} title={t('folder.locateHint')}><Icon name="search" />{t('folder.locate')}</button>
<button className="btn btn-sm" onClick={() => remove(() => nav.go({ screen: 'portfolio' }))} disabled={busy}><Icon name="trash" />{t('folder.remove')}</button>
</div>}>
<b>{t('folder.missing')}</b> {t('folder.missingText', { path: shortPath(project.path, d.info?.home) })}
</Notice>
);
}