Compare commits

..

177 commits

Author SHA1 Message Date
CRT
6d14eda8cc storebound 0.8.78: version in package.json and every copy, CHANGELOG 0.8.78 section
All checks were successful
ci / gate (push) Successful in 6s
ci / ci (push) Successful in 3m15s
ci / windows (push) Successful in 7m25s
ci / linux (push) Successful in 5m52s
ci / acceptance (bun, 22, ubuntu-22.04, Linux, bun) (push) Successful in 29s
ci / acceptance (bun, 22, windows, Windows, bun) (push) Successful in 33s
ci / acceptance (node20, 20, ubuntu-22.04, Linux, node) (push) Successful in 1m21s
ci / acceptance (node22, 22, ubuntu-22.04, Linux, node) (push) Successful in 1m26s
ci / dev (push) Successful in 1m31s
ci / record (push) Successful in 14s
release / promote (push) Successful in 14m39s
ci / acceptance (node20, 20, windows, Windows, node) (push) Successful in 9m6s
ci / acceptance (node22, 22, windows, Windows, node) (push) Successful in 9m37s
2026-11-17 00:59:46 +07:00
CRT
af61adb9d1 apple build: short fix lines first in the device-family stop; test: a stopped build exits non-zero
All checks were successful
ci / gate (push) Successful in 2s
ci / ci (push) Successful in 1m22s
ci / linux (push) Successful in 8m5s
ci / windows (push) Successful in 9m36s
ci / acceptance (bun, 22, ubuntu-22.04, Linux, bun) (push) Successful in 40s
ci / acceptance (bun, 22, windows, Windows, bun) (push) Successful in 1m2s
ci / acceptance (node20, 20, ubuntu-22.04, Linux, node) (push) Successful in 1m55s
ci / acceptance (node22, 22, ubuntu-22.04, Linux, node) (push) Successful in 2m2s
ci / record (push) Successful in 13s
ci / dev (push) Successful in 1m33s
ci / acceptance (node20, 20, windows, Windows, node) (push) Successful in 8m24s
ci / acceptance (node22, 22, windows, Windows, node) (push) Successful in 8m19s
2026-11-16 22:11:56 +07:00
CRT
73e4614b34 storebound 0.8.77: version in package.json and every copy, CHANGELOG 0.8.77 section 2026-11-09 06:37:51 +07:00
CRT
108b362cd9 iPhone Duo: limit from Apple's reference data instead of a cut to 10, --duo-only; shared asset library helpers in their own module 2026-11-09 06:35:00 +07:00
CRT
5cc3da486d storebound 0.8.76: version in package.json and every copy, CHANGELOG 0.8.76 section 2026-11-08 18:24:15 +07:00
CRT
7e362ef962 ci: AppImage tools from the Forgejo mirror (sha256-checked) into ~/.cache/tauri; GitHub release assets fail too often 2026-11-08 18:20:36 +07:00
CRT
c1bed9440e storebound 0.8.75: version in package.json and every copy, CHANGELOG 0.8.75 section 2026-11-08 17:40:26 +07:00
CRT
793c322f99 CHANGELOG: 0.8.74 was not published (GitHub 504) 2026-11-08 17:37:34 +07:00
CRT
ab97d6d72f storebound 0.8.74: version in package.json and every copy, CHANGELOG 0.8.74 section 2026-11-08 16:58:18 +07:00
CRT
c5173e4cae ci: cache ~/.cache/tauri and retry the Linux bundle (GitHub release 504s); CHANGELOG note for 0.8.73 2026-11-08 16:55:29 +07:00
CRT
f637c5e4e7 storebound 0.8.73: version in package.json and every copy, CHANGELOG 0.8.73 section 2026-11-08 16:26:03 +07:00
CRT
3a22d7f455 ci: install bun from the npm registry (GitHub release assets answer 504 now and then), bun.sh with retries as fallback 2026-11-08 16:23:15 +07:00
CRT
96458bba5c ci: re-run (GitHub download outage) 2026-11-08 16:17:34 +07:00
CRT
b361e22631 ci: re-run (bun download 504) 2026-11-08 15:50:43 +07:00
CRT
b18d480d65 iPhone Duo: accept platform IPHONE_APP_STORE from appAssetLibraryRefData; a Duo failure warns, other sets continue 2026-11-08 15:49:17 +07:00
CRT
f6f9fc3c41 storebound 0.8.72: version in package.json and every copy, CHANGELOG 0.8.72 section 2026-11-08 15:20:10 +07:00
CRT
8573c9f6ae flags.json: regenerated 2026-11-08 15:18:12 +07:00
CRT
1ce4f026e9 api tables: refData and asset library images now wrapped by apple screenshots 2026-11-08 15:15:57 +07:00
CRT
73a962fbdc apple screenshots: iPhone Duo through the App Asset Library (IPHONE_DUO placement group, APP_SCREENSHOT), pitfall 130 2026-11-08 14:19:12 +07:00
CRT
b1043f5d79 storebound 0.8.71: version in package.json and every copy, CHANGELOG 0.8.71 section 2026-11-08 03:33:21 +07:00
CRT
01ea264a21 CHANGELOG: 0.8.71 summary (0.8.69 and 0.8.70 were not published) 2026-11-08 03:30:40 +07:00
CRT
ec381e8664 boot check: the portfolio with a Play page 404 counts no live version 2026-11-08 03:26:22 +07:00
CRT
f34192b546 desktop Portfolio: the Play phase uses the same label as Releases (Not live yet ...) 2026-11-08 03:26:22 +07:00
CRT
d71368e886 storebound 0.8.70: version in package.json and every copy, CHANGELOG 0.8.70 section 2026-11-08 03:17:41 +07:00
CRT
07052cffd2 public MCP: a browser on the bare host goes to the landing page 2026-11-08 03:14:37 +07:00
CRT
b82becf7fb public MCP: the bare host answers MCP (POST /) and names the connect URL (GET /) 2026-11-08 03:14:37 +07:00
CRT
9081ac921d storebound 0.8.69: version in package.json and every copy, CHANGELOG 0.8.69 section 2026-11-08 02:24:27 +07:00
CRT
9c001d1ca9 play: old testing builds below production listed with their replace command (status, validate); 'Not live yet' instead of 'In review'; commit redone without changesNotSentForReview on the auto-send 400; pitfalls #129 2026-11-08 02:18:24 +07:00
CRT
83d351cf42 storebound 0.8.68: version in package.json and every copy, CHANGELOG 0.8.68 section 2026-11-08 02:01:11 +07:00
CRT
d05294ebcd apple submit/resubmit --platform macos: apple.macos.noIap leaves IAPs out, no Game Center switch without apple.macos.gameCenter; pitfalls #128 2026-11-06 21:07:22 +07:00
CRT
36ef9c2c5c tests: placeholder home folders in the launcher test (scrub) 2026-11-06 21:04:14 +07:00
CRT
0950ef2c99 desktop: the app's own CLI on the terminal PATH (launcher rewritten on every start; npm installs stay first) 2026-11-06 21:01:19 +07:00
CRT
31f863ed06 storebound 0.8.67: version in package.json and every copy, CHANGELOG 0.8.67 section 2026-11-04 00:20:45 +07:00
CRT
64cb16e337 apple build --platform macos: apple.macos.prebuild, not the iOS project's build.prebuild 2026-11-04 00:17:04 +07:00
CRT
700fcc4d66 storebound 0.8.66: version in package.json and every copy, CHANGELOG 0.8.66 section 2026-11-03 23:43:46 +07:00
CRT
f1a9229cf9 changelog: macOS entitlements, MCP review-details platform 2026-11-03 23:40:51 +07:00
CRT
68467ffe9b apple build --platform macos: --tauri takes tauri.<name>.conf.json (tauri.appstore.conf.json found by itself), entitlements from --entitlements / apple.macos.entitlements / the merged config, Developer-ID-only keys refused or warned 2026-11-03 23:40:25 +07:00
CRT
d88ed3ec55 mcp: apple_review_details takes platform (macOS version, apple.macos.reviewNotes) 2026-11-03 23:40:25 +07:00
CRT
1e47c2ee60 apple.macos listing / review notes per platform + iOS-only claim warnings; apple upload of a .pkg: bounded pkgutil, macOS processing wait, heartbeats; release 409 pattern 2026-11-03 23:40:25 +07:00
CRT
53d57544bf storebound 0.8.65: version in package.json and every copy, CHANGELOG 0.8.65 section 2026-11-03 23:17:34 +07:00
CRT
d0f568ebc2 validate: removed-from-sale IAPs are no blockers; shots capture --device landscape (Mac / Chromebook frames from a web build); playwright lookup says why each place failed 2026-11-03 23:14:34 +07:00
CRT
cdd9321794 storebound 0.8.64: version in package.json and every copy, CHANGELOG 0.8.64 section 2026-11-02 18:22:39 +07:00
CRT
3a8d9d7551 flags: regenerate for the new apple build / flow options 2026-11-02 18:19:50 +07:00
CRT
f5da7c9f7a validate: macOS versions need Mac screenshots, Play reads survive an ended edit; macOS build numbers across platforms; Mac build prebuild + apple.macAppCheck; signing wording off the Mac; dry flows plan uploads 2026-11-02 18:16:25 +07:00
CRT
b1f1b206d3 storebound 0.8.63: version in package.json and every copy, CHANGELOG 0.8.63 section 2026-11-02 16:43:58 +07:00
CRT
4b6c28aff2 desktop: a second --hidden start stays in the tray (single-instance no longer opens the window) 2026-11-02 16:39:15 +07:00
CRT
a850ba6670 storebound 0.8.62: version in package.json and every copy, CHANGELOG 0.8.62 section 2026-10-30 00:29:52 +07:00
CRT
152e40fb8a doctor: warn when storebound runs from a folder macOS guards (a launchd job hangs opening it) 2026-10-30 00:26:07 +07:00
CRT
724f5b9763 apple build: a line before each slow step (App Store Connect reads, device families, web build) 2026-10-30 00:16:11 +07:00
CRT
064a708fdb storebound 0.8.61: version in package.json and every copy, CHANGELOG 0.8.61 section 2026-10-29 22:40:00 +07:00
CRT
9b0cc0bf10 regenerate the api coverage tables 2026-10-29 22:37:03 +07:00
CRT
1abd0936c3 testflight: description keys by language id or App Store locale, unknown keys are a config error, primary-locale check before Beta App Review 2026-10-29 22:33:59 +07:00
CRT
e185b61c8e storebound 0.8.60: version in package.json and every copy, CHANGELOG 0.8.60 section 2026-10-29 20:24:54 +07:00
CRT
edbcdad15d gradle: comment without a home path 2026-10-29 20:21:52 +07:00
CRT
1c64320b65 desktop-release: a fixed release tool left uncommitted for release --resume does not make the build dirty 2026-10-29 20:19:21 +07:00
CRT
6ebb656018 apple listing: a new version inherits the previous version's release type when apple.releaseType is unset; warn when the config differs 2026-10-29 20:19:21 +07:00
CRT
f5296cc9e9 play release --dry: no bundle upload into a discarded edit (a long upload outlived it: edit expired); shows the planned tracks 2026-10-29 20:19:20 +07:00
CRT
ab69ce020c play build: absolute --dir stays absolute; gradlew without exec bit is made executable 2026-10-29 20:19:16 +07:00
CRT
0ea7292164 release --resume: a fixed tools/desktop-release.ts may be uncommitted too 2026-10-29 20:18:52 +07:00
CRT
02435de966 desktop-release: sign by key path only (a TAURI_SIGNING_PRIVATE_KEY in the env made the signer refuse both) 2026-10-29 20:18:51 +07:00
CRT
96ec7ba60f desktop-release: sign by key path only (a TAURI_SIGNING_PRIVATE_KEY in the env made the signer refuse both) 2026-10-29 20:18:51 +07:00
CRT
17f57c6fb6 storebound 0.8.59: version in package.json and every copy, CHANGELOG 0.8.59 section 2026-10-29 19:10:28 +07:00
CRT
3b1c6160b5 docs: SSE keepalive for long tool calls 2026-10-29 19:06:22 +07:00
CRT
9620768897 mcp --http: SSE keepalive for long tool calls; public App Store search shares one 20-a-minute budget 2026-10-29 19:06:14 +07:00
CRT
c500866295 mcp --http --public: key-less public server (skills, pitfalls, limits, listing lint, App Store search), rate limit, 64 KB bodies 2026-10-29 19:06:14 +07:00
CRT
398d8cd375 storebound 0.8.58: version in package.json and every copy, CHANGELOG 0.8.58 section 2026-10-29 18:41:35 +07:00
CRT
a108aae53f mcp --http: --broker-profiles (store keys from the broker vault, memory only), --read-only, project by folder name under the roots 2026-10-29 18:38:11 +07:00
CRT
164ba390dd check / scan: project walks skip dot folders, worktrees and git-ignored output, no stat per entry (244 s -> 46 s on a big game repo) 2026-10-29 17:29:28 +07:00
CRT
f2d7beb7ce mcp --http: no request timeout (tool calls can run for many minutes) 2026-10-29 16:31:41 +07:00
CRT
8068993917 docs: mcp --http (shared server, project argument, token and introspection auth) 2026-10-29 16:21:50 +07:00
CRT
5f73fcbcf4 mcp --http: one Streamable HTTP server for every session (token or OAuth introspection auth, project argument per call, roots, origin check) 2026-10-29 16:19:53 +07:00
CRT
28a50e7d2e storebound 0.8.57: version in package.json and every copy, CHANGELOG 0.8.57 section 2026-10-27 19:01:14 +07:00
CRT
9a878d6562 apple upload: find the IPA of a build made with --out (build notes it in .storebound/last-apple-build.json; upload --out; the error names every folder searched and the last build's IPA) 2026-10-27 18:58:48 +07:00
CRT
ef80cd2760 storebound 0.8.56: version in package.json and every copy, CHANGELOG 0.8.56 section 2026-10-27 17:17:39 +07:00
CRT
bf95ee55c4 regenerate the api coverage tables 2026-10-27 17:13:34 +07:00
CRT
2dc20b61de regenerate embedded skills 2026-10-27 17:10:59 +07:00
CRT
f64f125de6 docs: escape the table pipes 2026-10-27 17:08:39 +07:00
CRT
5f2e03dc7d docs: apple release type flags and config template line 2026-10-27 17:07:53 +07:00
CRT
85cf494c0a apple: release type (apple.releaseType, apple release --after-approval|--manual), device-family preflight, TestFlight invite needs an installable build 2026-10-27 17:07:37 +07:00
CRT
4763862178 storebound 0.8.55: version in package.json and every copy, CHANGELOG 0.8.55 section 2026-10-26 20:21:17 +07:00
CRT
3dc3104bbc scrub: /Users/Shared is the system shared folder, not a home path 2026-10-26 20:17:46 +07:00
CRT
0858f4e538 path-free: a shared build folder outside home is not a leak (only home and user-name paths are private) 2026-10-26 20:13:11 +07:00
CRT
efa9503a50 storebound 0.8.54: version in package.json and every copy, CHANGELOG 0.8.54 section 2026-10-26 19:16:46 +07:00
CRT
f109c519ae apple build: --derived-data (default <out>/DerivedData with --out), --path-free (Swift/clang prefix maps, no serialized debug options) and an archive path scan 2026-10-26 19:12:21 +07:00
CRT
cb20912f0e storebound 0.8.53: version in package.json and every copy, CHANGELOG 0.8.53 section 2026-10-26 18:17:15 +07:00
CRT
db52afce1d play release: read the production kind inside the release's own edit (no extra edit); the not-sent-for-review tests approve their first release 2026-10-26 18:12:19 +07:00
CRT
ae9d26d3f6 Updates are agent steps: --yes ships an update of a live app (Play production, App Store submit / release) without an owner gate; the first release stays the owner's (exit 3 OWNER_STEP, --first-release); apple release is a ship step 2026-10-26 18:09:50 +07:00
CRT
c247b7e54a release --resume: skip the desktop publish when the version is already live (a second run re-signs and the server never replaces a published file) 2026-10-26 16:52:29 +07:00
CRT
46c841d209 storebound 0.8.52: version in package.json and every copy, CHANGELOG 0.8.52 section 2026-10-26 11:08:21 +07:00
CRT
1953aa59d8 CHANGELOG: 0.8.51 was not published 2026-10-26 11:05:27 +07:00
CRT
05d0e227a1 release: the dev-channel job never gates a release; desktop-dev retries the live dev latest.json on 5xx 2026-10-26 11:05:08 +07:00
CRT
1030cdff0c storebound 0.8.51: version in package.json and every copy, CHANGELOG 0.8.51 section 2026-10-26 10:27:48 +07:00
CRT
5833776a4b analytics and reports for a collector: store-only configs, --json snapshot, App Usage and Play install stock numbers, per-day sales ranges for both stores 2026-10-26 10:20:27 +07:00
CRT
b59665c661 storebound 0.8.50: version in package.json and every copy, CHANGELOG 0.8.50 section 2026-10-25 23:18:12 +07:00
CRT
2c5e30090f credential broker: Play tokens from POST /api/google/token (cached, single flight, local key fallback), grants and APIs per package in validate, Play write preflight, apps check and the desktop Accounts view; Google 403 names the API or grant, no retry 2026-10-25 22:51:32 +07:00
CRT
304407e523 apple signing: App Group association fails early under automatic signing too (API capability + newest profile, steps and deep link, exit before the archive); console plan/verify apple-app-group 2026-10-25 22:35:36 +07:00
CRT
d978bb7a8b desktop icon: the brand mark at every size (small Windows sizes were a plain S tile), each size resampled on its own, 20/30/36/40/60/72/80/96 px added for 125-200 % scaling 2026-10-25 21:08:13 +07:00
CRT
d7c36cbdb6 storebound 0.8.49: version in package.json and every copy, CHANGELOG 0.8.49 section 2026-10-25 20:15:46 +07:00
CRT
d43c95db7e desktop: read StartupApproved through the registry API, no reg.exe (the security test allows no other programs) 2026-10-25 21:11:31 +08:00
CRT
53845c6dd9 desktop: autostart respects Windows Startup apps (turned off there stays off; the Run entry is no longer re-enabled on every start) 2026-10-24 21:13:10 +08:00
CRT
da7ca48ab4 desktop tray: card as tall as its content, card and menu open from the tray icon's edge (never over the taskbar); menu permission files 2026-10-24 19:53:10 +08:00
CRT
6782ac6078 api tables: regenerate for the new Play listing calls 2026-10-24 19:49:26 +08:00
CRT
ed8d138a8e play: a new language is created with everything Play needs to commit it (icon, feature graphic, phone and tablet screenshots); play images creates a missing listing 2026-10-24 19:46:57 +08:00
CRT
2ec1f0ab13 storebound 0.8.48: version in package.json and every copy, CHANGELOG 0.8.48 section 2026-10-24 18:17:14 +07:00
CRT
a889ada137 tests: adhoc register --yes gets 20 s (timed out at 5 s on a busy CI runner) 2026-10-24 19:09:21 +08:00
CRT
5236f002f1 desktop: tray menu panels and pinnable context menus
The tray's right-click menu is drawn by the app: one tree from tray.rs
(stable submenu keys), one frameless always-on-top menu-N window per
panel rendered by tray-menu.html with the design system, placed inside
the monitor's work area. A pure panel book keeps transient and pinned
panels apart; pinned panels (pin button, Ctrl+click, middle click) are
draggable, step aside from each other and are saved in state.json
(menuPins) and restored at start. tray_update pushes the tree to the
open panels, which update in place; closed panels are destroyed. The
native menu, rendered from the same tree, stays as the fallback and on
Linux. Only menu-* windows get the menu_* commands (menu.json).

In-app context menus get the same behaviour through a pure menu stack
(ui/menu-stack.ts): pin a menu, tear off a submenu, pinned panels
survive the next menu, are draggable and re-read their entries from
live sources so data changes update them in place.

Also drops a stray diff3 marker line from CHANGELOG.md.
2026-10-24 13:44:08 +08:00
CRT
445ab1adbc apple signing: every signable target (extensions, App Group check), build keychain unlock over SSH, api confirm docs 2026-10-24 13:07:58 +08:00
CRT
5b6e0992ca desktop: boot check finds unsaved marks on the sub views; neutral next-step lines before a read 2026-10-24 13:06:42 +08:00
CRT
0ef27cf2e4 desktop: five sections by job (Release, Store page, Revenue, Players, Health), Game services view, sidebar by attention
- app view: 12 tabs become 5 sections, each with a header (what it is for, the one next step from state
  already read) and its sub views in a segmented control; 1-5 jump, Ctrl+Shift+[ ] cycle, Ctrl+K and the
  context menu list sections and sub views; old tab ids, section and section/sub links all resolve
- Players > Game services (games only): both stores, one row per leaderboard / achievement with its
  languages and each store's state, Game Center locale map, Play API-disabled state with the console plan
- games status --json: items, localeMap, playApiDisabled; inspect summary: games
- sidebar: apps grouped by attention / in progress / live / not on a store, one status line each, studio
  filter, workspace as a footer icon row
- boot check opens places like a person (section, then sub view)
2026-10-24 13:06:42 +08:00
CRT
98cd1d3c92 embedded: regenerated 2026-10-24 13:02:02 +08:00
CRT
66247f35d9 flags: shots fonts --lang, capture --probe 2026-10-24 13:01:45 +08:00
CRT
b059e83b90 shots fonts usage line 2026-10-24 13:01:32 +08:00
CRT
61b5fa0623 shots: feature rotate, per-language frame fallback, layout-aware capture selectors 2026-10-24 13:00:48 +08:00
CRT
2e1c7cdc3c mas: placeholders the scrub accepts 2026-10-24 12:23:53 +08:00
CRT
634d5dd71d generated API tables refreshed for the macOS build upload 2026-10-24 12:23:52 +08:00
CRT
33a7f73ab9 docs: build-and-sign Mac App Store Tauri section, pitfall 114, changelog 2026-10-24 12:23:36 +08:00
CRT
f588f4e1aa path-free: no cargo trim-paths (nightly only) 2026-10-24 12:23:20 +08:00
CRT
0263f62443 mas build: cargo target folder is src-tauri/target 2026-10-24 12:23:20 +08:00
CRT
5fc15dd773 apple build/upload: flags and help for the macOS Tauri path 2026-10-24 12:23:17 +08:00
CRT
9a937b5512 apple build --platform macos --tauri: Mac App Store build of a Tauri app (sandbox entitlements, profile, productbuild pkg, path-free, checks); apple upload accepts the pkg 2026-10-24 12:22:27 +08:00
CRT
2e8593ed5c pitfalls spacing 2026-10-24 12:17:45 +08:00
CRT
b325b45354 merge fixups: changelog and pitfall numbering 2026-10-24 12:17:01 +08:00
CRT
089c149289 desktop coverage test: shots copy is agent-edited 2026-10-24 12:16:49 +08:00
CRT
8084104a4d desktop coverage entry for shots copy 2026-10-24 12:16:49 +08:00
CRT
fb1609cba7 upload --pre-check/--evidence, shots copy translate, game-center --locale-map, play games API-disabled hint 2026-10-24 12:16:48 +08:00
CRT
26f9559e1a play-publish-changes: a release is ready only when the store page shows an older version; unknown reads are not determined, never a mismatch 2026-10-24 12:12:37 +08:00
CRT
4e2ffd6b3d generated API tables refreshed for the play-publish-changes form 2026-10-24 12:01:37 +08:00
CRT
1bb43fd4a0 play managed publishing: console plan/verify play-publish-changes, ready-to-publish items in play status, desktop hint 2026-10-24 11:56:07 +08:00
CRT
29a9683ab7 dev channel: Apache serves /desktop/dev/latest.json; the VDS publisher lists releases without the draft filter (it hid the dev drafts) 2026-10-23 23:46:03 +08:00
CRT
9947ea1639 dev channel VDS publisher: send a User-Agent (Cloudflare refuses urllib's default with 403) 2026-10-23 23:17:05 +08:00
CRT
39b2f73ad7 desktop dev update channel: every push to main builds dev bundles (<next patch>-dev.<UTC>), the VDS signs and publishes dev/latest.json (newest 5); app channel setting stable|dev, background updater at start / 15 min / resume / channel switch, deferred while in use, no downgrade, autostart rewritten on every start, card shows version and channel 2026-10-23 23:14:08 +08:00
CRT
4dff7d9b2e desktop open: Windows window check uses real top-level windows (the tray helper windows and MainWindowHandle also answer for a hidden app) 2026-10-23 22:53:30 +08:00
CRT
8df41a26b0 desktop open: a hidden tray copy that is already running counts once its window is visible (Windows), graceful stop wait 3 s on Windows 2026-10-23 22:53:30 +08:00
CRT
d4cf1ad3a1 shots: full-bleed layout (shots.layout bleed) with corner captions, per-size frames, and landscape orientation, on top of the landscape sizes 2026-10-23 22:45:10 +08:00
CRT
9ed1890de8 storebound 0.8.47: version in package.json and every copy, CHANGELOG 0.8.47 section 2026-10-23 16:03:29 +07:00
CRT
8f69a27709 desktop install: stop the running app by exact path, check the installed exe's real version, verify it opened 2026-10-23 15:57:32 +07:00
CRT
a01c78aa20 generated API tables and flags refreshed for the play products clamp (Forgejo ci failed on stale api tables) 2026-10-23 15:56:36 +07:00
CRT
b0641c1fc8 play products: clamp regional prices to Play's min/max, per-product results; apple iap: skip live localizations, per-product results 2026-10-23 16:53:25 +08:00
CRT
882255a32f storebound 0.8.46: version in package.json and every copy, CHANGELOG 0.8.46 section 2026-10-23 14:44:51 +07:00
CRT
84f9793af5 Merge origin/main (0.8.45 tag, not published) 2026-10-23 15:40:56 +08:00
CRT
487e138f9d watch: ingest sink (--notify ingest) posting events to a push ingest endpoint 2026-10-23 15:30:18 +08:00
CRT
960662029e storebound 0.8.45: version in package.json and every copy, CHANGELOG 0.8.45 section 2026-10-23 13:50:24 +07:00
CRT
5b3905679b CHANGELOG: 0.8.44 was not published 2026-10-23 14:48:09 +08:00
CRT
b36b92dc90 Merge origin/main (0.8.44 tag) 2026-10-23 14:48:03 +08:00
CRT
0b0007045c desktop tests: clippy clean (repeat_n in the tray test, unix-only time imports in ai_fix) 2026-10-23 14:47:53 +08:00
CRT
12e56c5a82 storebound 0.8.44: version in package.json and every copy, CHANGELOG 0.8.44 section 2026-10-23 13:16:42 +07:00
CRT
84efa4e913 desktop coverage: place for the status command 2026-10-23 14:14:02 +08:00
CRT
bffbf94278 portfolio test: android identity carries developerId and appId 2026-10-23 14:11:38 +08:00
CRT
987f0775b3 tray card: per-icon Phosphor imports; teaser pins the current app-privacy step 5 text 2026-10-23 14:07:44 +08:00
CRT
e2ff7efcda CHANGELOG: 0.8.43 was not published; notes move to Unreleased 2026-10-23 13:56:01 +08:00
CRT
5379845e78 Merge origin/main (0.8.43 tag) 2026-10-23 13:55:50 +08:00
CRT
960e084bea ship step: apple build plan keeps its version and build in --json; test fixtures pass the scrub (documentation IPs, neutral home paths, 10-char key ids) 2026-10-23 13:55:44 +08:00
CRT
b1ed2ad8ca storebound 0.8.43: version in package.json and every copy, CHANGELOG 0.8.43 section 2026-10-23 12:20:06 +07:00
CRT
6abc1f65dd Merge origin/main (0.8.42 tag, not published); API tables and flags regenerated 2026-10-23 13:16:13 +08:00
CRT
f03a83bf3d Merge origin/main (0.8.42 tag, not published); API tables regenerated 2026-10-23 13:15:34 +08:00
CRT
021c0eef5a Regenerate the API tables with forward slashes 2026-10-23 13:13:45 +08:00
CRT
2e888a01cc docs/ship-step.md, pitfall 110 (pipeline exit 7 and double uploads), CHANGELOG Unreleased 2026-10-23 13:13:28 +08:00
CRT
06a0b424f5 Ship-step contract for pipelines: uniform exit codes (0/1/2/3/4/7) in cli/lib/ship-step.ts, one final --json line, --result-file (atomic, also on failure), --progress json, --env-file with secret redaction, --version-from; idempotent play upload / apple upload / play release / apple submit re-runs end with exit 7; play upload takes --track production and --version-code 2026-10-23 13:13:21 +08:00
CRT
4eac8e8cd8 storebound status: per platform live and next version, build, track, review state and rollout % without uploading (read-only, one JSON line); release status --app also takes an app folder or a store id 2026-10-23 13:13:15 +08:00
CRT
4933279987 gen-api: module names with forward slashes on Windows too (the tables were stale on Linux CI) 2026-10-23 13:13:03 +08:00
CRT
0ed7bc1ca0 storebound 0.8.42: version in package.json and every copy, CHANGELOG 0.8.42 section 2026-10-23 11:30:53 +07:00
CRT
54451c87c8 Regenerate the API tables (wrapped.gen.ts, api-coverage.md); 0.8.41 notes move to Unreleased 2026-10-23 12:29:24 +08:00
CRT
19b4868852 storebound 0.8.41: version in package.json and every copy, CHANGELOG 0.8.41 section 2026-10-23 10:25:06 +07:00
CRT
f3e7c98994 desktop reads: a card that joins a read or gets the 'read just now' answer applies it (no bus event for those: a tab opened again stayed on its skeleton); invalidate before a write's after-refresh, editor save re-reads with force 2026-10-23 11:22:26 +08:00
CRT
fa081666ec CHANGELOG: reads registry and tray card 2026-10-23 11:16:12 +08:00
CRT
fb37911f5e Desktop: generated permissions of the tray card commands 2026-10-23 11:15:40 +08:00
CRT
60a72e6947 Desktop: tray mini card on left click (store status at a glance next to the tray icon; Refresh runs the main window's Refresh all) 2026-10-23 11:15:35 +08:00
CRT
c03938f9dc desktop: one read registry for every read button: single-flight per canonical key, broad reads cover narrow keys, overlapping buttons all busy and disabled (useReadState), 20 s 'read just now' memo, quota pause on the buttons, every read through the scheduler (Check again, Import apps, account Test, Read the stores, Dependencies), writes invalidate only the reads they change; tests/read-registry.test.ts; fixtures ?blocked and window.__fakeCalls 2026-10-23 11:09:51 +08:00
CRT
7345de2f7c Desktop boot check: quota row match as plain text 2026-10-23 10:47:39 +08:00
CRT
2638b90046 Desktop boot check: the reader's quota row uses the short wording 2026-10-23 10:46:49 +08:00
CRT
f052831fea Desktop boot check: the dry-run preview is accepted whenever it shows, also during waits 2026-10-23 10:44:54 +08:00
CRT
26ebb64458 Desktop: tab row measures the room inside the sticky bar's padding (the More button was clipped); editor saves skip the in-app preview (their Review step already showed the dry run) 2026-10-23 10:44:45 +08:00
CRT
83bb9a621e Desktop boot check: say why a tab could not be opened 2026-10-23 10:36:38 +08:00
CRT
8106d7c9a2 Desktop boot check: tabs opened like a person (the More menu when a tab is not in the row); the fake host answers window dry runs like the Rust host (dryRun forced), art.pull preview dry run 2026-10-23 10:31:40 +08:00
CRT
ffaf42c55d Merge origin/main (0.8.40 tag, not published) 2026-10-23 10:26:05 +08:00
CRT
5b7b16ac08 Desktop boot check: accept the in-app dry-run preview before the native confirm 2026-10-23 10:25:26 +08:00
CRT
c7bae75ed0 apple build/upload: accept --allow-version-mismatch (flag list regenerated); 1.0 and 1.0.0 are one version train 2026-10-23 09:57:13 +08:00
354 changed files with 20415 additions and 1275 deletions

View file

@ -9,7 +9,7 @@
"name": "storebound", "name": "storebound",
"source": ".", "source": ".",
"description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.",
"version": "0.8.40", "version": "0.8.78",
"category": "development", "category": "development",
"tags": [ "tags": [
"mobile", "mobile",

View file

@ -1,6 +1,6 @@
{ {
"name": "storebound", "name": "storebound",
"version": "0.8.40", "version": "0.8.78",
"description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.",
"author": { "author": {
"name": "CRTkafa" "name": "CRTkafa"

View file

@ -1,6 +1,6 @@
{ {
"name": "storebound", "name": "storebound",
"version": "0.8.40", "version": "0.8.78",
"description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.",
"author": { "author": {
"name": "CRTkafa" "name": "CRTkafa"

View file

@ -20,6 +20,12 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha
testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final
Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For
these you prepare everything, show the dry run, and the owner presses one button or says yes. these you prepare everything, show the dry run, and the owner presses one button or says yes.
**Updates are agent steps:** a new version of an app that is already on the store (Play: the production track holds
a published release; App Store: a version of the platform is or was on sale) is yours end to end, no owner gate
per update: `storebound play release <aab> --production completed --yes`, `storebound play upload --track
production --yes`, `storebound apple submit --build <n> --yes`, `storebound apple release --manual-release --yes`
(docs/bypass.md). Only the **first-ever release** of an app stays the owner's (exit 3 `OWNER_STEP`: after the
owner's yes re-run with `--first-release`), plus removal from sale, live price changes and anything that costs money.
**Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too:
MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and
console plans' `buttons.final`. Say in one line what you pressed; every action is logged to console plans' `buttons.final`. Say in one line what you pressed; every action is logged to

View file

@ -26,6 +26,7 @@ runs:
with: with:
path: | path: |
~/.bun/install/cache ~/.bun/install/cache
~/.cache/tauri
~/.cargo/registry/index ~/.cargo/registry/index
~/.cargo/registry/cache ~/.cargo/registry/cache
~/.cargo/git/db ~/.cargo/git/db
@ -35,7 +36,7 @@ runs:
shell: bash shell: bash
run: | run: |
P="${FORGEJO_PATH:-$GITHUB_PATH}" P="${FORGEJO_PATH:-$GITHUB_PATH}"
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null bash tools/ci-install-bun.sh
echo "$HOME/.bun/bin" >> "$P" echo "$HOME/.bun/bin" >> "$P"
command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
echo "$HOME/.cargo/bin" >> "$P" echo "$HOME/.cargo/bin" >> "$P"

View file

@ -33,7 +33,7 @@ jobs:
if: ${{ matrix.platform == 'Linux' }} if: ${{ matrix.platform == 'Linux' }}
shell: bash shell: bash
run: | run: |
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null bash tools/ci-install-bun.sh
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}" echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
- name: Acceptance matrix (Linux) - name: Acceptance matrix (Linux)
if: ${{ matrix.platform == 'Linux' }} if: ${{ matrix.platform == 'Linux' }}
@ -97,7 +97,7 @@ jobs:
path: acceptance-runs/Windows-bun path: acceptance-runs/Windows-bun
- name: Matrix (markdown), red cells fail the job - name: Matrix (markdown), red cells fail the job
run: | run: |
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null bash tools/ci-install-bun.sh
export PATH="$HOME/.bun/bin:$PATH" export PATH="$HOME/.bun/bin:$PATH"
V=$(bun tools/desktop-version.ts --print) V=$(bun tools/desktop-version.ts --print)
mkdir -p out mkdir -p out

View file

@ -102,7 +102,7 @@ jobs:
if: ${{ matrix.platform == 'Linux' }} if: ${{ matrix.platform == 'Linux' }}
shell: bash shell: bash
run: | run: |
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null bash tools/ci-install-bun.sh
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}" echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
- name: Acceptance matrix (Linux) - name: Acceptance matrix (Linux)
if: ${{ matrix.platform == 'Linux' }} if: ${{ matrix.platform == 'Linux' }}
@ -173,7 +173,9 @@ jobs:
working-directory: apps/desktop working-directory: apps/desktop
run: | run: |
rm -rf "$CARGO_TARGET_DIR/release/bundle" rm -rf "$CARGO_TARGET_DIR/release/bundle"
bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles appimage,deb --ci # the AppImage tools come from GitHub releases, which answer 504 now and then (cached in ~/.cache/tauri)
bash ../../tools/ci-tauri-tools.sh
for i in 1 2 3; do bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles appimage,deb --ci && break; [ $i = 3 ] && exit 1; sleep 30; done
- name: Self-test the exact artifacts - name: Self-test the exact artifacts
run: | run: |
V=$(bun tools/desktop-version.ts --print) V=$(bun tools/desktop-version.ts --print)
@ -223,6 +225,34 @@ jobs:
name: storebound-desktop-linux name: storebound-desktop-linux
path: out/ path: out/
retention-days: 7 retention-days: 7
# dev channel (tools/desktop-dev.ts): the same commit again with the version <next patch>-dev.<commit UTC>, only in
# this workspace (never committed); a failure here never touches the release candidate above
- name: Dev build (AppImage + deb, dev version)
id: dev
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
continue-on-error: true
env:
FORBIDDEN_TERMS: ${{ secrets.FORBIDDEN_TERMS }}
run: |
set -euo pipefail
V=$(bun tools/desktop-dev.ts set)
bun tools/build-sidecars.ts --target bun-linux-x64
patchelf --set-rpath '$ORIGIN/../lib' apps/desktop/src-tauri/binaries/storebound-x86_64-unknown-linux-gnu
B="$CARGO_TARGET_DIR/release/bundle"; rm -rf "$B"
bash tools/ci-tauri-tools.sh
for i in 1 2 3; do (cd apps/desktop && bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles appimage,deb --ci) && break; [ $i = 3 ] && exit 1; sleep 30; done
mkdir -p dev && cp "$B/appimage/storebound_${V}_amd64.AppImage" "$B/deb/storebound_${V}_amd64.deb" dev/
chmod +x dev/*.AppImage
(cd /tmp && rm -rf squashfs-root && "$GITHUB_WORKSPACE/dev/storebound_${V}_amd64.AppImage" --appimage-extract >/dev/null && squashfs-root/usr/bin/storebound-desktop --self-test)
umask 077; printf '%s\n' "$FORBIDDEN_TERMS" > "$RUNNER_TEMP/terms.txt"
rc=0; STOREBOUND_FORBIDDEN_TERMS="$RUNNER_TEMP/terms.txt" bun tools/privacy-scan.ts dev/ || rc=$?
rm -f "$RUNNER_TEMP/terms.txt"; git checkout -- . ; exit $rc
- uses: actions/upload-artifact@v3
if: steps.dev.outcome == 'success'
with:
name: storebound-desktop-dev-linux
path: dev/
retention-days: 3
windows: windows:
needs: gate needs: gate
@ -288,6 +318,78 @@ jobs:
name: storebound-desktop-windows name: storebound-desktop-windows
path: out/ path: out/
retention-days: 7 retention-days: 7
# dev channel (tools/desktop-dev.ts): see the linux job
- name: Dev build (NSIS, dev version)
id: dev
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
continue-on-error: true
shell: pwsh
env:
FORBIDDEN_TERMS: ${{ secrets.FORBIDDEN_TERMS }}
run: |
$ErrorActionPreference = 'Stop'
$V = bun tools/desktop-dev.ts set
if ($LASTEXITCODE -ne 0) { throw "dev version stamp refused" }
bun tools/build-sidecars.ts --target bun-windows-x64
Remove-Item -Recurse -Force "$env:CARGO_TARGET_DIR\release\bundle\nsis" -ErrorAction SilentlyContinue
Push-Location apps/desktop
bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles nsis --ci
if ($LASTEXITCODE -ne 0) { throw "dev build failed" }
Pop-Location
New-Item -ItemType Directory -Force dev | Out-Null
Copy-Item "$env:CARGO_TARGET_DIR\release\bundle\nsis\storebound_${V}_x64-setup.exe" dev\
Start-Process -Wait -FilePath "dev\storebound_${V}_x64-setup.exe" -ArgumentList '/S'
& "$env:LOCALAPPDATA\storebound\storebound-desktop.exe" --self-test
if ($LASTEXITCODE -ne 0) { throw "dev self-test failed" }
Start-Process -Wait -FilePath "$env:LOCALAPPDATA\storebound\uninstall.exe" -ArgumentList '/S'
$t = Join-Path $env:RUNNER_TEMP "terms-$([guid]::NewGuid()).txt"
Set-Content -Path $t -Value $env:FORBIDDEN_TERMS -NoNewline:$false
$env:STOREBOUND_FORBIDDEN_TERMS = $t
bun tools/privacy-scan.ts dev
$rc = $LASTEXITCODE
Remove-Item -Force $t
git checkout -- .
if ($rc -ne 0) { throw "privacy scan failed" }
- uses: actions/upload-artifact@v3
if: steps.dev.outcome == 'success'
with:
name: storebound-desktop-dev-windows
path: dev/
retention-days: 3
# dev channel: the dev bundles of both jobs go to a Forgejo draft dev-<version> (no tag; the newest 5 kept); the VDS
# (tools/vds/storebound-desktop-dev, a root timer) signs them with the updater key and publishes
# storebound.dev/desktop/dev/latest.json. macOS has no dev build: Developer ID signing needs the Mac's GUI session.
dev:
needs: [linux, windows]
if: ${{ always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.linux.result == 'success' && needs.windows.result == 'success' }}
runs-on: ubuntu-22.04
timeout-minutes: 40
env:
FORGEJO_TOKEN: ${{ secrets.RELEASE_TOKEN }}
FORGEJO_URL: ${{ github.server_url }}
FORGEJO_ORIGIN: ${{ secrets.FORGEJO_ORIGIN }}
SHA: ${{ github.sha }}
steps:
- uses: actions/checkout@v4
- name: Tools
run: |
bash tools/ci-install-bun.sh
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
- uses: actions/download-artifact@v3
with:
name: storebound-desktop-dev-linux
path: dev
- uses: actions/download-artifact@v3
with:
name: storebound-desktop-dev-windows
path: dev
- name: Draft dev-<version> (newest 5 kept), then wait for the VDS to publish it
run: |
ls -la dev
bun tools/desktop-dev.ts record --dir dev --yes
V=$(ls dev | sed -n 's/^storebound_\(.*\)_x64-setup\.exe$/\1/p')
bun tools/desktop-dev.ts wait "$V" --minutes 20
record: record:
needs: [gate, linux, windows] needs: [gate, linux, windows]
@ -307,7 +409,7 @@ jobs:
# no apt: the installers were scanned with the private terms in their own jobs; this job only records # no apt: the installers were scanned with the private terms in their own jobs; this job only records
- name: Tools - name: Tools
run: | run: |
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null bash tools/ci-install-bun.sh
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}" echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
[ -n "$FORGEJO_TOKEN" ] || { echo "secret RELEASE_TOKEN is missing (repo Settings > Actions > Secrets)" >&2; exit 1; } [ -n "$FORGEJO_TOKEN" ] || { echo "secret RELEASE_TOKEN is missing (repo Settings > Actions > Secrets)" >&2; exit 1; }
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3

View file

@ -61,7 +61,7 @@ jobs:
- name: Tag, package.json version, every version copy and the CHANGELOG agree - name: Tag, package.json version, every version copy and the CHANGELOG agree
id: check id: check
run: | run: |
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null bash tools/ci-install-bun.sh
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}" echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
export PATH="$HOME/.bun/bin:$PATH" export PATH="$HOME/.bun/bin:$PATH"
bun tools/desktop-version.ts bun tools/desktop-version.ts

View file

@ -20,6 +20,12 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha
testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final
Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For
these you prepare everything, show the dry run, and the owner presses one button or says yes. these you prepare everything, show the dry run, and the owner presses one button or says yes.
**Updates are agent steps:** a new version of an app that is already on the store (Play: the production track holds
a published release; App Store: a version of the platform is or was on sale) is yours end to end, no owner gate
per update: `storebound play release <aab> --production completed --yes`, `storebound play upload --track
production --yes`, `storebound apple submit --build <n> --yes`, `storebound apple release --manual-release --yes`
(docs/bypass.md). Only the **first-ever release** of an app stays the owner's (exit 3 `OWNER_STEP`: after the
owner's yes re-run with `--first-release`), plus removal from sale, live price changes and anything that costs money.
**Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too:
MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and
console plans' `buttons.final`. Say in one line what you pressed; every action is logged to console plans' `buttons.final`. Say in one line what you pressed; every action is logged to

View file

@ -21,6 +21,12 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha
testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final
Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For
these you prepare everything, show the dry run, and the owner presses one button or says yes. these you prepare everything, show the dry run, and the owner presses one button or says yes.
**Updates are agent steps:** a new version of an app that is already on the store (Play: the production track holds
a published release; App Store: a version of the platform is or was on sale) is yours end to end, no owner gate
per update: `storebound play release <aab> --production completed --yes`, `storebound play upload --track
production --yes`, `storebound apple submit --build <n> --yes`, `storebound apple release --manual-release --yes`
(docs/bypass.md). Only the **first-ever release** of an app stays the owner's (exit 3 `OWNER_STEP`: after the
owner's yes re-run with `--first-release`), plus removal from sale, live price changes and anything that costs money.
**Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too:
MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and
console plans' `buttons.final`. Say in one line what you pressed; every action is logged to console plans' `buttons.final`. Say in one line what you pressed; every action is logged to

View file

@ -3,8 +3,188 @@
## Unreleased ## Unreleased
## 0.8.40 · 2026-10-23 ## 0.8.78 · 2026-11-16
- **apple build:** the device-family stop prints short `fix:` lines first (e.g. `fix: apple.ipad: true in storebound.config.ts`); a test proves a stopped build exits non-zero through the ship-step path.
## 0.8.77 · 2026-11-08
- **iPhone Duo:** outer and inner files are no longer cut to the first 10: the limit comes from Apple's reference data, and over it nothing changes and nothing is dropped. `apple screenshots --duo-only` writes only the Duo set. `apple cpp` no longer lists creative-assets flags.
## 0.8.76 · 2026-11-08
- 0.8.75 was tagged but not published (GitHub 502/504 in the Linux AppImage bundling). CI now takes the AppImage tools from a checked mirror instead of GitHub.
## 0.8.75 · 2026-11-08
- 0.8.74 was tagged but not published (GitHub release downloads answered 504 during the Linux AppImage bundling); 0.8.75 ships its section.
## 0.8.74 · 2026-11-08
- 0.8.73 was tagged but not published (a GitHub 504 in the Linux AppImage bundling); 0.8.74 ships its section below. CI caches the AppImage tools and retries the Linux bundle.
## 0.8.73 · 2026-11-08
- **iPhone Duo:** the live API names the platform IPHONE_APP_STORE (not IOS); accepted. A Duo problem now warns and the other screenshot sets still upload.
## 0.8.72 · 2026-11-08
- **iPhone Duo screenshots upload.** `apple screenshots` now sends them through the App Asset Library (display class
IPHONE_DUO, placement APP_SCREENSHOT) instead of skipping them as "not in the API" (pitfall 130).
## 0.8.71 · 2026-11-07
- 0.8.69 and 0.8.70 were tagged but not published (the desktop release check stopped them); 0.8.71 ships both sections below. Desktop Portfolio: the Play state of an app uses the same words as Releases ("Not live yet: in review or blocked before review").
## 0.8.70 · 2026-11-07
- Public MCP server: the bare host is the endpoint too. `POST /` answers MCP like `/mcp` (someone who pastes `https://mcp.example.com` into a connector gets connected), `GET /` sends a browser to the landing page and names the connect URL to any other client. A signed-in server keeps `/` closed.
## 0.8.69 · 2026-11-07
- Play: `play status` and `validate` list every build still active on a testing track below the production build, with the `play release --version-code <n> --<track> completed` that replaces it (an old build with a policy issue, e.g. READ_MEDIA_IMAGES, blocks Send changes for review for the whole app). A completed production release the store page does not show yet reads "Not live yet: in review or blocked before review" instead of "In review" (CLI and desktop). A commit with `--not-sent-for-review` that Play answers with 400 "Changes are sent for review automatically" is redone without the parameter (pitfalls #129).
## 0.8.68 · 2026-11-07
- Desktop app: `storebound` works in a terminal with only the app installed. On every start the app puts a launcher for its own CLI on the PATH (Windows: `%LOCALAPPDATA%\storebound\bin`, added to the user PATH once; macOS / Linux: `~/.local/bin`, added to `~/.zprofile` / `~/.profile` when missing). An npm / bun install stays first, a file that is not the app's launcher is never overwritten, AppImage runs skip it, `STOREBOUND_NO_CLI_SHIM=1` turns it off.
- `apple resubmit` / `apple submit --platform macos`: `apple.macos.noIap` leaves every in-app purchase out of the macOS submission and, without `apple.macos.gameCenter: true`, the Game Center switch is not touched (no `gameCenterAppVersions` call); the dry run names what it left out and why (pitfalls #128).
## 0.8.67 · 2026-11-03
- `apple build --platform macos`: runs `apple.macos.prebuild` (new) before `tauri build`, no longer `build.prebuild` / `apple.prebuild`, which belong to the iOS project (a Capacitor sync or OTA gate ran for a Tauri Mac build); the dry run names the skipped one.
## 0.8.66 · 2026-11-03
- `apple.macos: { listing, reviewNotes, gameCenter, noIap }`: an app with iOS and macOS versions gets its own Mac listing file and review notes (`apple listing --platform macos`, `apple review-details --platform macos`, new there); `validate` warns about iOS-only claims in a macOS version's texts (Game Center, tap / swipe, iPhone / iPad, in-app purchases with `noIap`).
- `apple upload <pkg>`: reading the package is bounded (pkgutil signature check 90 s, expand 5 min, then the `apple build` .json) and logged; the processing wait finds macOS builds (it looked only at iOS and sat silently until --timeout); every slow read prints a heartbeat; an SSH / non-GUI session is warned about up front.
- `apple build --platform macos`: `--tauri` takes a `tauri.<name>.conf.json` overlay (merged over tauri.conf.json and passed to `tauri build --config`; `tauri.appstore.conf.json` / `tauri.mas.conf.json` next to it are used by themselves); the Mac App Store entitlements come from `--entitlements`, `apple.macos.entitlements` or the merged config (a two-channel project signed the App Store app with its Developer ID plist); the plan lists the final keys, `get-task-allow` / `cs.disable-library-validation` stop the build (`--allow-entitlements`), other hardened-runtime exceptions warn.
- MCP `apple_review_details` takes `platform`.
- `apple release`: a 409 on a release type change is recognized again (a stray control character had broken the pattern).
## 0.8.65 · 2026-11-03
- `validate`: in-app purchases removed from sale (DEVELOPER_REMOVED_FROM_SALE, REMOVED_FROM_SALE) are no blockers; a warning only when the config still sells one.
- `shots capture --device landscape`: Mac App Store / Chromebook frames from a web build (desktop viewport at `shots.landscape.size`, default 1440x900 @2x) into `<lang>/landscape/`; on by default when the project renders a landscape size. The simulator and emulator sources skip it with a warning.
- `shots render` / `capture`: "playwright not found" now lists each place looked at and why it failed (an import error was reported as not found).
## 0.8.64 · 2026-11-02
- `validate` / `release plan`: a macOS version is checked against Mac screenshots (APP_DESKTOP, with `apple.mac`), not the iPhone / iPad sets; with no editable version, iOS is picked over macOS.
- `validate --play`: reads go through the locked read-only edit and retry once on a fresh edit when Play ends it ("This Edit has been deleted" was shown as a blocker; it is now a warning to re-run at most).
- Build numbers for macOS (`apple build --platform macos`, `apple upload` of a .pkg) come from every build of the app, as `apple next-build` does (a macOS-only list proposed a number an iOS build already had).
- `apple build --platform macos` runs `build.prebuild` / `apple.prebuild` before `tauri build` (`--no-prebuild` skips it), and the new `apple.macAppCheck` command on the built .app before productbuild ({file} = the .app; a nonzero exit stops the build).
- `apple signing status` / the Mac build dry run on Windows or Linux say the keys live on the Mac that made the certificates (build there) instead of suggesting a new certificate.
- Flows: a dry `flow run` plans the upload, TestFlight wait and distribute steps after a dry build instead of failing on the missing IPA; `beta` and `release` need VERSION (no silent 1.0.0); `beta` distributes to the config's internal TestFlight group when GROUP is empty; `release` has optional macOS steps (MAC_TAURI), PLAY_TRACK (e.g. beta = open testing) and a promote owner step.
## 0.8.63 · 2026-11-02
- Desktop: a second start at logon (`--hidden`, e.g. a Startup folder shortcut next to the Run entry) keeps the app in the tray instead of opening its window.
## 0.8.62 · 2026-10-29
- `doctor` warns when storebound runs from a folder macOS guards (~/Desktop, ~/Documents, ~/Downloads, iCloud Drive; e.g. a `bun link` to a checkout there): a launchd job or CI agent without access to it blocks in open() with no output.
- `apple build` prints a line before each slow step (App Store Connect reads, device families, web build), so a run without a terminal that stalls shows where.
## 0.8.61 · 2026-10-29
- TestFlight: `apple.testflight.description` takes a language id or its App Store locale (`en` or `en-US`; an `en-US` key was skipped silently), `check` names an unknown key, and `distribute --submit-review` stops (dry run: warns) when the app's primary locale has no beta localization (Beta App Review answers 422 MISSING_BETA_APP_LOCALIZATION).
## 0.8.60 · 2026-10-29
- `apple listing` creates a new version with the release type of the newest version before it (MANUAL or AFTER_APPROVAL) when `apple.releaseType` is not set; a first version stays MANUAL. The plan names where the type came from, and warns when `apple.releaseType` differs from the previous version's.
- `play release <aab> --dry` uploads nothing: it names the versionCode it would upload and the track changes it would make (the bundle went into a discarded edit, and a long upload could outlive the edit: "This edit has expired").
- `play build`: an absolute `--dir` / `play.build.dir` stays absolute (it was taken as a folder under the project and lost its leading slash); a `gradlew` without the exec bit (committed from Windows) is made executable with a note to commit the mode. The desktop release signs by key path only.
## 0.8.59 · 2026-10-29
- `mcp --http`: a `tools/call` that accepts `text/event-stream` gets SSE keepalive comments every 20 s and then its result, so long calls survive proxies that cut silent responses. The public server's App Store search keeps one budget of 20 calls a minute (Apple's limit).
- `storebound mcp --http --public`: a public, key-less MCP server (no sign-in, no store credentials, no project folders, no child processes, read-only). Tools: `skills_list`, `skill_get`, `pitfalls_search`, `store_limits`, `listing_lint` and `aso_search` (the public iTunes Search API, the only network call). Rate limit per client (`--rate`, 429 with Retry-After; `--trust-proxy` for X-Forwarded-For), 64 KB request bodies, CORS preflight. docs/mcp.md.
## 0.8.58 · 2026-10-29
- `check` and `scan` are fast on big repos: project walks skip dot folders (tool state, worktree copies), linked git worktrees and the folders git ignores (Pods, Carthage, SourcePackages and ios / android stay in), and read entry types from the listing instead of a stat per file. A game repo with worktree copies went from 244 s to 46 s for `check`.
- `storebound mcp --http`: one Streamable HTTP MCP server that every agent session of a machine shares (no process per session). Each tool gets a `project` argument (absolute path inside `--roots`); auth is a local bearer token (`~/.storebound/mcp-token`, made on first start) or, for a server behind TLS, OAuth bearer tokens checked by introspection (RFC 7662) with protected resource metadata (RFC 9728). docs/mcp.md.
## 0.8.57 · 2026-10-27
- `apple upload` finds the IPA of a build made with `--out`: `apple build` notes its IPA and out folder in `.storebound/last-apple-build.json`, and upload searches `--out` (new flag), then that last build's out, then `apple.build.out` / `build/ios`. When nothing is found, the error names every folder it searched and the last build's IPA.
## 0.8.56 · 2026-10-27
- Release type. `apple.releaseType: afterApproval | manual | scheduled` (+ `apple.earliestReleaseDate`): `apple listing` creates versions with it (MANUAL when unset, existing versions untouched) and `apple submit` / `resubmit` set it before submitting when it differs, the dry run showing old -> new. New `apple release --after-approval | --manual | --scheduled <ISO date> [--platform] [--version] [--first-release] --yes` changes it on a version App Review has not approved yet (clear refusal otherwise, with `--manual-release` as the way out); exit 7 when it already has that type; an update is an agent step, after-approval on the first version of an app is exit 3 OWNER_STEP. Pitfall 125.
- Device families. `validate` and `apple build` read the device families of the last live version (build bundle `deviceProtocols`, device models, iPad screenshot sets) and compare them with TARGETED_DEVICE_FAMILY in the Xcode project and `apple.ipad`; a gap stops `apple build` before the archive with the exact fix (ITMS-90101 otherwise comes after the build; `--allow-device-gap` overrides). Offline `check` warns when the live families are unknown or the config and project disagree. Pitfall 126.
- TestFlight. `apple testflight testers --invite` checks that the tester's group has an installable build (past Beta App Review for external groups); without one it adds the tester, skips the invite and prints when it can go out (exit 0). Apple's 409 NO_INSTALLABLE_BUILDS is handled the same way; `distribute --submit-review` prints the hint for testers not invited yet. Pitfall 127.
## 0.8.55 · 2026-10-26
- `apple build --path-free`: a checkout in a shared build folder outside the home folder is no longer a leak needle (dsymutil and the module cache record it; only home and user-name paths count).
## 0.8.54 · 2026-10-26
- `apple build` is hermetic and can be path-free. `--derived-data <dir>` (`apple.build.derivedData`) is xcodebuild `-derivedDataPath`; with `--out` (or `apple.build.out`) it defaults to `<out>/DerivedData` instead of `~/Library/Developer/Xcode/DerivedData` (without `--out` Xcode's folder stays). `--path-free` (`apple.build.pathFree`) remaps the home folder, checkout, out and DerivedData out of the app binary and the archive's dSYMs / Symbols (Swift `-debug-prefix-map` / `-file-prefix-map`, clang `-ffile-prefix-map`; dwarf-with-dsym stays, symbol upload keeps working), scans the archive and stops before the export with the hit count and the first file + offsets (never the paths). `--scan-paths` only scans and warns. A `--out` outside the home folder prints a hint. `--json` / `latest.json` carry `derivedData`, `pathFree` and `leaks`. Store-pitfalls 124.
## 0.8.53 · 2026-10-26
- Updates are agent steps (the owner's standing rule), first releases stay the owner's. `play release <aab> --production completed|inProgress --yes`, `play upload --track production --yes`, `apple submit --build <n> --yes` and `apple release --manual-release --yes` run without an owner gate, in a terminal and in a pipeline, when the store says the app is already live (Play: the production track holds a completed / inProgress / halted release; App Store: a version of the platform is or was `READY_FOR_SALE` / `READY_FOR_DISTRIBUTION` / `REPLACED_WITH_NEW_VERSION`; `cli/lib/release-kind.ts`). The result line carries `releaseKind`; a re-run is exit 7. The first-ever release of an app with `--yes` is exit 3 `OWNER_STEP` ("first release of this app: the owner approves it once"), approved by `--first-release` (after the owner's yes) or bypass mode; a person answering the prompt (no `--yes`) is the approval too. `apple release` is now a ship step (`--json`, `--result-file`, exit 7 when the version is released already). Policy in docs/bypass.md ("Updates are agent steps"), docs/ship-step.md, the release-management and play-first-release skills, AGENTS.md; pitfall 123 / 96.
## 0.8.52 · 2026-10-26
- `analytics snapshot` and `reports` for a collector: a store-only config may name the App Store app by `apple.appId` alone (`bundleId` null or absent; every write still needs it); the Play reports bucket also comes from env `PLAY_REPORTS_BUCKET` or the credential profile's `reportsBucket` when `play.reportsBucket` is missing; `analytics snapshot --json` prints the snapshot as one JSON document on stdout (also when every store failed, with the exit code 1) and `--no-write` skips the file.
- Snapshots carry active-user numbers per day: App Store App Usage (`sessions`, `activeDevices`, `sessionSeconds`, `crashes` from the App Sessions and App Crashes reports; a missing usage report is a `notes` line, not a failure) and Play `activeDeviceInstalls` and `totalUserInstalls` (installs overview file, else the country file summed) next to `installs` (Daily User Installs).
- `reports apple-sales --days N | --from YYYY-MM-DD [--to ...] --json` reads the daily SALES reports of a range into one JSON (per-day summary and totals per currency, range totals per currency, `missing` days listed, never errors); `reports play-sales --days N | --from ...` gives the daily revenue per currency from the estimated sales reports (orders, refunds, charged, refunded, net, by order charged date). MCP `reports` takes `days`, `from`, `to`.
- Release: the dev-channel CI job no longer gates a release.
## 0.8.51 · 2026-10-26
- Tagged but not published (the dev-channel job hit a CDN 502); everything ships in the next version.
## 0.8.50 · 2026-10-25
- App Groups fail early under automatic signing too: `apple signing status` / `ensure` and `apple build` read the App ID's APP_GROUPS capability settings and the newest profile the API lists for each bundle id (an Xcode-managed one too) and compare it with the target's `com.apple.security.application-groups`. A profile without the group (or the capability off) stops `signing ensure` and `apple build` before the archive with the exact portal steps (Certificates, Identifiers & Profiles > Identifiers > the ID > App Groups > Configure > tick the group > Continue > Save), the deep link `.../identifiers/bundleId/edit/<resource id>`, the plan command and `signing ensure --refresh-profile`; a group nothing can prove only warns with the same steps. `apple build --allow-app-group-gap` overrides.
- New `storebound console plan apple-app-group [--bundle-id <id>] [--groups group.a,group.b] [--lookup]` (MCP `console_plan`: `bundleId`, `groups`, `lookup`): the agent-first developer portal plan to assign an App Group to an extension's App ID (start URL per bundle id resource id, portal labels, answer sheet per extension, never-press list: Remove / Delete / Revoke). Its final Save is the agent's own (`buttons.finalByAgent`: a capability edit, not a store submission). `console verify apple-app-group` (MCP `console_verify`, API only) re-reads the App ID and the newest profile and fails while a group is missing or cannot be proven.
- Google access through a credential broker (`~/.storebound/broker.json`: `url`, `apiKeyFile`; env `STOREBOUND_BROKER_URL` / `STOREBOUND_BROKER_KEY_FILE`): Play tokens come from the broker's `POST /api/google/token` (in memory until 5 minutes before expiry, one request per account and scope, never logged; ya29. tokens and the API key redacted in errors), the local service account key stays the fallback when the broker does not answer or does not know the account; a broker that refuses the API key stops without retry. `PLAY_SERVICE_ACCOUNT_EMAIL` names the account (env, profile, project file); a profile opts out with `"broker": false`. The key file must be mode 600 on macOS / Linux. Play write commands read the package's Play permissions and enabled APIs from the broker first and stop before any Play call on a missing one (`CAN_MANAGE_TRACK_APKS`, `CAN_MANAGE_PUBLIC_LISTING`, `CAN_MANAGE_ORDERS`, `CAN_MANAGE_APP_CONTENT`, the Games Configuration API) with the exact permission or API and its link; `validate` lists them (gaps are blockers, SDK config drift a warning) and `--json` carries `credentials.play.source`; `doctor`, `accounts` and `apps check` / the desktop's Accounts view say whether tokens come from the broker or the key file. A Google 403 SERVICE_DISABLED / PERMISSION_DENIED in the Play client names the API or grant with its fix link and is never retried (pitfall 122, docs/credential-broker.md).
## 0.8.49 · 2026-10-25
- `play listing` for a language Play does not have yet uploads, in the same edit as the text, everything Play requires to commit it: icon, feature graphic, 2+ phone screenshots from `store/renders/<lang>/` and the tablet sets when the other languages have them (a set the folder lacks falls back to the default language's). The dry run lists the uploads or refuses with the missing file, instead of a 403 "too few screenshots" at commit. `play images` creates a Play listing that does not exist yet (text from the listing file) together with its images instead of skipping the language (pitfall 102).
## 0.8.48 · 2026-10-24
- Desktop tray: the right-click menu is drawn by the app (the design system's menu look) instead of the OS menu. Each submenu opens as its own small panel; the pin button, Ctrl+click or a middle click keeps a panel open (pinned): it can be dragged, steps aside so it never covers another pinned panel, and comes back after a restart. Values (the apps and their store state, mute) update in place after every store read without closing anything. The native menu stays as a fallback (and on Linux), built from the same menu tree. The left-click tray card is unchanged.
- Desktop right-click menus in the window work the same way: a menu's pin button keeps it open as a floating panel, a submenu can be torn off (its pin button, Ctrl+click or a middle click), pinned panels survive the next menu, can be dragged, and update in place when the data behind them changes ("Gone" when the thing they were for left the screen).
- `shots.feature.rotate` (degrees) is honoured by the Play feature graphic like a scene frame's `rotate`: added to the template tilt and the phone is re-fitted (`-90` stands a landscape game frame upright); with `shots.layout: "bleed"` the frame image is turned and still covers the canvas.
- `shots check` / `shots render` without frames for a language that has copy use the default language's frames (an info line, no failure); `shots.perLanguageFrames: true` requires per-language frames. `shots fonts --lang en,tr` limits the report to those languages (the font manifest keeps all of them).
- `shots capture` web shots take `waitSelector` and `click` selector lists per layout (`{ phone, tablet, any }`, data attributes first, `text=` fallback). A miss names the selector and the size with every candidate's match count; `shots capture --dry` prints the candidates per size and `--dry --probe` opens the pages and reports which one matched or MISSed on which size.
- `apple signing ensure` signs every target of the Xcode project, not only the app: it reads the pbxproj targets (app, app extensions such as a share extension or widget, watch app, App Clip: Release PRODUCT_BUNDLE_IDENTIFIER and entitlements), registers each extension's bundle id (`POST /v1/bundleIds`, platform from the profile type), enables the capabilities its entitlements need (read back) and, with manual signing, creates its App Store profile; `--dry` lists every target. `apple.signing.extensions` (`bundleId`, `name`, `capabilities`, `appGroups`) replaces the detected extensions when detection is wrong; `status` shows a target table.
- App Groups: the API cannot assign a group to a bundle id, so `signing status` / `ensure` and (manual signing) `apple build` decode the profile and compare its `com.apple.security.application-groups` with the target's entitlements; a gap names the developer portal link (`.../identifiers/bundleId/edit/<id>`) and the steps to tick the group. `signing ensure --refresh-profile` makes the profile again afterwards; `apple build --allow-app-group-gap` overrides.
- `apple build` over SSH / in CI: the refusal now names the fixes (GUI session `.command` file, a CI runner with an unlocked keychain, a build keychain). New `--keychain-unlock` (keychain password from `STOREBOUND_KEYCHAIN_PASSWORD`, never printed; runs `security unlock-keychain` and `set-key-partition-list`) and `--keychain <path>` (sign with a build keychain).
- `storebound api` writes: the usage, the dry-run message and the refusals show the agent form with an example (`--yes --confirm <operationId>`), and the store-api skill says both flags are needed.
- Play managed publishing: `storebound console plan play-publish-changes` (Publishing overview > "Changes ready to publish" > the owner's final "Publish N changes" + its confirm dialog; never-press: Discard changes, Stop managed publishing; `--lookup` lists the ready production releases from the API) and `console verify play-publish-changes` (API: passes when no production release is left ready to publish; or the page text). `play status` (and `--json` `readyToPublish`) prints the ready items and the plan hint, `storebound status` names the plan, and the desktop Releases tab shows the same hint with a button that opens Publishing overview. A release counts as ready to publish only when the public store page positively shows an older version; a 404, a failed or stale page read, a same or unparseable version is never ready (verify says "not determined" instead of a mismatch).
- `apple upload` / `play upload` `--pre-check "<cmd with {file}>"` (config `upload.preCheck`) runs your gate before any byte is sent; a nonzero exit refuses the upload (ship-step exit 1, `PRE_CHECK_FAILED`). `--evidence <path.json>` (`upload.evidence`) writes file, sha256, size, command, exit code, stdout tail, time and version, also on failure, and the result carries it as `preCheck`.
- New `storebound shots copy translate --to de,es` fills store/shots/copy.json per language (agent translation or `--translate "<cmd>"`), machine-translated until `shots copy reviewed`, caption limits respected; `shots copy check`; `check` / `shots render` name this command for a missing language.
- `apple game-center --locale-map en=en-GB` (config `games.localeMap`) maps a config language to the live Game Center locale; the dry run suggests it when the live Game Center has exactly one variant of the language.
- `play games`: a 403 SERVICE_DISABLED / accessNotConfigured names the Google Play Game Services Publishing API, the enable URL for the project and `console plan play-games-services`.
- `apple build --platform macos --tauri <src-tauri> [--path-free] [--unsigned]`: Mac App Store build of a Tauri app. Generated sandbox entitlements, Mac App Store profile (installed, `--profile` or from the API), Apple Distribution / Mac Installer Distribution identities, `tauri build --bundles app`, checks of the .app, `productbuild` to a signed .pkg, `pkgutil --check-signature`; `--path-free` remaps local paths in rustc and fails on any leak of the home folder or user name. `apple upload <pkg> --platform macos` uploads it (platform MAC_OS). New certificate types MAC_APP_DISTRIBUTION and MAC_INSTALLER_DISTRIBUTION. Pitfall 119.
- Desktop dev update channel: Settings > Updates offers Stable (the npm releases) and Dev (every push to main). Each push to main builds Windows and Linux bundles stamped `<next patch>-dev.<UTC commit time>` (above the current stable, below the next one); the VDS signs them and serves `storebound.dev/desktop/dev/latest.json` (newest 5 kept). The app checks its channel at start, every 15 minutes, after sleep and right after a channel switch, installs a strictly newer build quietly (deferred while the window is in use), never downgrades (dev back to stable waits for a newer stable), rewrites its logon autostart on every start, and the tray card shows version and channel. No macOS dev builds (Developer ID signing needs the Mac's GUI session).
- `shots` full-bleed layout: `shots.layout: "bleed"` fills the image with the app's own frame (no device, no background) and puts the scene title as a short corner caption (`corner`, `captionScale`, `captionWidth`, `captionInset` per scene) legible through a text shadow and soft glow only; the Play feature graphic shows the logo or `shots.feature.title`. Frames are captured per size at its own pixels in `<frames>/<lang>/<size>/<name>.png` (feature: `<lang>/feature/`), including the `mac` and `chromebook` sizes; `shots check` / `capture --source folder` verify aspect and native width. `shots.orientation: "landscape"` (bleed only) renders every portrait size landscape (stores accept it). Templates `template-bleed.html`, `feature-bleed.html`.
- `storebound desktop`: "opened" now also works when a hidden tray copy is already running. On Windows it prints "opened" only when a process of the installed path has a visible window (the running copy shows it through the single-instance handoff); on macOS / Linux a visible start or a handoff to the running copy counts, otherwise it says only a tray copy runs. The graceful stop waits 3 s on Windows (closing a tray app only hides it), then stops by PID.
## 0.8.47 · 2026-10-23
- `storebound desktop`: an update no longer reports "installed" while the old app stays. It stops the running app first (exact install path only, graceful close, then by PID), checks the installed exe's own version (Windows PE version resource instead of the registry entry; Info.plist on macOS) and fails with what it found, and prints "opened" only when a visible (not `--hidden`) process started from the installed path, otherwise it names the app's log.
- `play products` / `play subscriptions`: regions outside Play's min / max (a 649.99 USD product in KR: "must be between ₩70 and ₩600,000") are flagged in the dry run (old -> new) and clamped to the bound on write with a warning; `--skip-out-of-range-regions` leaves them out. Limits Play reports in a 400 are learned (`.storebound/play-price-limits.json`) and the write is retried. A product or subscription that fails no longer stops the others: per-product results, exit 1 at the end.
- `apple iap` / `apple subscriptions`: edits to approved (ACTIVE) localizations, which App Store Connect refuses with 409 UNMODIFIABLE, are marked "not editable now" in the dry run and skipped with a warning on write; prices and the other changes still apply. One IAP failing no longer stops the rest (results at the end, exit 1).
## 0.8.46 · 2026-10-23
- `storebound watch` has an `ingest` sink (`--notify ingest`, `ingest` in ~/.storebound/watch.json): a JSON POST per event to a push ingest endpoint with a Bearer token read from a file at send time (refused when group or world readable), 8 KiB body cap, 60 sends a minute, one retry on 5xx; `watch test` covers it.
- Ship-step contract for release pipelines (docs/ship-step.md): `play build | upload | release`, `apple build | upload | submit | resubmit` exit 0 ok, 1 failure, 2 usage, 3 needs the owner (with `error.code` and the console deep link), 4 store refused, 7 nothing to do; `--json` ends with exactly one result line on stdout, `--result-file` writes it atomically (also on failure), `--progress json` gives one JSON line per phase on stderr.
- `--env-file <path>` loads KEY=VALUE secrets before the credentials resolve (POSIX: mode 600 or stricter) and every known secret value is scrubbed from stdout, stderr and the result file; `--version-from version.json` takes the version and build ({version, build}, {versionName, versionCode}, {marketing, build}).
- Re-runs never upload twice: `play upload` with a versionCode Play has and `apple upload` with a build number App Store Connect has end with exit 7 and what is there; `play release` with the same release and `apple submit` of an already submitted build too.
- `play upload --track production` (the pipeline's update step; `--status draft` keeps it for the Console) and `--version-code N` to pick the AAB.
- New `storebound status [--app <name|store id|folder>] [--json]`: per platform the live and next version, build, track, review state and rollout %, read-only. `release status --app` also takes a folder or a store id.
- Desktop: every read goes through one registry: one store call per read however many buttons are clicked, overlapping buttons (Refresh all, card refresh, Check again, Import, Test) are busy and disabled together, a read just finished is not repeated, and all reads share the scheduler's rate limits and backoff.
- Desktop: tray mini card on left click (rejections, releases moving, crash alerts, recent low reviews, refresh, quick actions); right click keeps the menu.
- `apple build` / `apple upload`: `--allow-version-mismatch` is accepted (it was missing from the flag list); 1.0 and 1.0.0 count as the same version train, as on App Store Connect.
- Desktop: custom context menus everywhere (apps, releases, art, reviews, checks, fields, products, accounts, folders) with keyboard navigation, Shift+F10 and submenus; the WebView2 browser menu and browser shortcuts are off. - Desktop: custom context menus everywhere (apps, releases, art, reviews, checks, fields, products, accounts, folders) with keyboard navigation, Shift+F10 and submenus; the WebView2 browser menu and browser shortcuts are off.
- Desktop: each app shows once again (a folder project no longer appears a second time as a store-only app); a store app with a folder's bundle id or package is never listed separately. - Desktop: each app shows once again (a folder project no longer appears a second time as a store-only app); a store app with a folder's bundle id or package is never listed separately.
- Desktop UX pass on every screen: app tabs fit the window, slim app header, secondary actions in "…" menus, Ctrl+K lists app actions, Alt+Up/Down switches apps, accounts and folders decluttered. - Desktop UX pass on every screen: app tabs fit the window, slim app header, secondary actions in "…" menus, Ctrl+K lists app actions, Alt+Up/Down switches apps, accounts and folders decluttered.
@ -12,6 +192,30 @@
- Desktop: tabs in one row with a More menu, one Refresh, reviews keyboard (J/K, R, C, O), Settings and More tools search, sticky first column and compact density for wide tables, styled in-app dry-run preview before every write. - Desktop: tabs in one row with a More menu, one Refresh, reviews keyboard (J/K, R, C, O), Settings and More tools search, sticky first column and compact density for wide tables, styled in-app dry-run preview before every write.
- Checks: "Open guide" opens the matching skill for every finding. - Checks: "Open guide" opens the matching skill for every finding.
## 0.8.45 · 2026-10-23
- Tagged but not published (the release upload could not reach the server after an IP change); everything ships in the next version.
## 0.8.44 · 2026-10-23
- Tagged but not published (desktop clippy red on the bump commit); everything ships in the next version.
## 0.8.43 · 2026-10-23
- Tagged but not published (CI red: scrub hits in test fixtures, a ship-step test); everything ships in the next version.
## 0.8.42 · 2026-10-23
- Tagged but not published (generated API tables differed on Linux CI); everything ships in the next version.
## 0.8.41 · 2026-10-23
- Tagged but not published (a generated API table was stale in CI); everything ships in the next version.
## 0.8.40 · 2026-10-23
- Tagged but not published (the desktop boot check stopped it); everything ships in the next version.
## 0.8.39 · 2026-10-23 ## 0.8.39 · 2026-10-23
- Tagged but not published; everything ships in the next version. - Tagged but not published; everything ships in the next version.

View file

@ -19,6 +19,12 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha
testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final
Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For
these you prepare everything, show the dry run, and the owner presses one button or says yes. these you prepare everything, show the dry run, and the owner presses one button or says yes.
**Updates are agent steps:** a new version of an app that is already on the store (Play: the production track holds
a published release; App Store: a version of the platform is or was on sale) is yours end to end, no owner gate
per update: `storebound play release <aab> --production completed --yes`, `storebound play upload --track
production --yes`, `storebound apple submit --build <n> --yes`, `storebound apple release --manual-release --yes`
(docs/bypass.md). Only the **first-ever release** of an app stays the owner's (exit 3 `OWNER_STEP`: after the
owner's yes re-run with `--first-release`), plus removal from sale, live price changes and anything that costs money.
**Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too:
MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm <operationId>`, and
console plans' `buttons.final`. Say in one line what you pressed; every action is logged to console plans' `buttons.final`. Say in one line what you pressed; every action is logged to

14
apps/desktop/card.html Normal file
View file

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="data:," />
<title>storebound</title>
</head>
<body class="tc-page">
<div id="card"></div>
<script type="module" src="/src/card/main.tsx"></script>
</body>
</html>

View file

@ -1,6 +1,6 @@
{ {
"name": "@storebound/desktop", "name": "@storebound/desktop",
"version": "0.8.40", "version": "0.8.78",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",

View file

@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]] [[package]]
name = "storebound-desktop" name = "storebound-desktop"
version = "0.8.40" version = "0.8.78"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"getrandom 0.3.4", "getrandom 0.3.4",
@ -4126,6 +4126,7 @@ dependencies = [
"url", "url",
"webview2-com", "webview2-com",
"windows-core", "windows-core",
"winreg",
"zip", "zip",
] ]

View file

@ -1,6 +1,6 @@
[package] [package]
name = "storebound-desktop" name = "storebound-desktop"
version = "0.8.40" version = "0.8.78"
description = "storebound desktop: every game's releases on both stores in one window" description = "storebound desktop: every game's releases on both stores in one window"
license = "MIT" license = "MIT"
edition = "2021" edition = "2021"
@ -53,6 +53,8 @@ zip = { version = "4", default-features = false, features = ["deflate-flate2-zli
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
webview2-com = "0.39" webview2-com = "0.39"
windows-core = "0.62" windows-core = "0.62"
# reads Startup apps' StartupApproved value (already in the tree through the autostart plugin)
winreg = "0.56"
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"

View file

@ -5,7 +5,7 @@ include!("src/commands_list.rs");
fn main() { fn main() {
tauri_build::try_build( tauri_build::try_build(
tauri_build::Attributes::new() tauri_build::Attributes::new()
.app_manifest(tauri_build::AppManifest::new().commands(COMMANDS)), .app_manifest(tauri_build::AppManifest::new().commands(Box::leak([COMMANDS, CARD_COMMANDS, MENU_COMMANDS].concat().into_boxed_slice()))),
) )
.expect("tauri build script failed"); .expect("tauri build script failed");
} }

View file

@ -0,0 +1,13 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "card-window",
"description": "The tray card (a small window next to the tray icon) with the app's own bundled card page only. It may listen to app events (the main window's snapshot) and call the two card commands: read the last snapshot and send a button (hide, open the main window or a route in it, refresh and mute through the main window, open a store console, quit). It never reads the stores or reaches the sidecar; every command re-checks the window label and page origin in Rust.",
"windows": ["card"],
"local": true,
"permissions": [
"core:event:allow-listen",
"core:event:allow-unlisten",
"allow-card-get",
"allow-card-action"
]
}

View file

@ -45,6 +45,7 @@
"allow-data-reveal", "allow-data-reveal",
"allow-notify", "allow-notify",
"allow-tray-update", "allow-tray-update",
"allow-card-snapshot",
"allow-app-reset", "allow-app-reset",
"allow-update-check", "allow-update-check",
"allow-update-install", "allow-update-install",

View file

@ -0,0 +1,21 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "menu-window",
"description": "The tray menu panels (menu-1, menu-2...: small frameless windows the app opens on a right click on the tray icon, one per open or pinned submenu) with the app's own bundled tray-menu page only. They may listen to app events (the live menu tree) and call the menu commands: read their panel, report their size, open, pin and close panels, pick a row, which runs the same tray action as the native menu, and start a drag of their own window (a pinned panel's header). They never read the stores or reach the sidecar; every command re-checks the window label and page origin in Rust.",
"windows": ["menu-*"],
"local": true,
"permissions": [
"core:event:allow-listen",
"core:event:allow-unlisten",
"core:window:allow-start-dragging",
"allow-menu-state",
"allow-menu-ready",
"allow-menu-open-sub",
"allow-menu-pin-sub",
"allow-menu-close-subs",
"allow-menu-close",
"allow-menu-dismiss",
"allow-menu-pin",
"allow-menu-select"
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 69 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 69 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 2 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 89 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 158 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 228 KiB

Before After
Before After

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-card-action"
description = "Enables the card_action command without any pre-configured scope."
commands.allow = ["card_action"]
[[permission]]
identifier = "deny-card-action"
description = "Denies the card_action command without any pre-configured scope."
commands.deny = ["card_action"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-card-get"
description = "Enables the card_get command without any pre-configured scope."
commands.allow = ["card_get"]
[[permission]]
identifier = "deny-card-get"
description = "Denies the card_get command without any pre-configured scope."
commands.deny = ["card_get"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-card-snapshot"
description = "Enables the card_snapshot command without any pre-configured scope."
commands.allow = ["card_snapshot"]
[[permission]]
identifier = "deny-card-snapshot"
description = "Denies the card_snapshot command without any pre-configured scope."
commands.deny = ["card_snapshot"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-close"
description = "Enables the menu_close command without any pre-configured scope."
commands.allow = ["menu_close"]
[[permission]]
identifier = "deny-menu-close"
description = "Denies the menu_close command without any pre-configured scope."
commands.deny = ["menu_close"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-close-subs"
description = "Enables the menu_close_subs command without any pre-configured scope."
commands.allow = ["menu_close_subs"]
[[permission]]
identifier = "deny-menu-close-subs"
description = "Denies the menu_close_subs command without any pre-configured scope."
commands.deny = ["menu_close_subs"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-dismiss"
description = "Enables the menu_dismiss command without any pre-configured scope."
commands.allow = ["menu_dismiss"]
[[permission]]
identifier = "deny-menu-dismiss"
description = "Denies the menu_dismiss command without any pre-configured scope."
commands.deny = ["menu_dismiss"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-open-sub"
description = "Enables the menu_open_sub command without any pre-configured scope."
commands.allow = ["menu_open_sub"]
[[permission]]
identifier = "deny-menu-open-sub"
description = "Denies the menu_open_sub command without any pre-configured scope."
commands.deny = ["menu_open_sub"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-pin"
description = "Enables the menu_pin command without any pre-configured scope."
commands.allow = ["menu_pin"]
[[permission]]
identifier = "deny-menu-pin"
description = "Denies the menu_pin command without any pre-configured scope."
commands.deny = ["menu_pin"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-pin-sub"
description = "Enables the menu_pin_sub command without any pre-configured scope."
commands.allow = ["menu_pin_sub"]
[[permission]]
identifier = "deny-menu-pin-sub"
description = "Denies the menu_pin_sub command without any pre-configured scope."
commands.deny = ["menu_pin_sub"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-ready"
description = "Enables the menu_ready command without any pre-configured scope."
commands.allow = ["menu_ready"]
[[permission]]
identifier = "deny-menu-ready"
description = "Denies the menu_ready command without any pre-configured scope."
commands.deny = ["menu_ready"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-select"
description = "Enables the menu_select command without any pre-configured scope."
commands.allow = ["menu_select"]
[[permission]]
identifier = "deny-menu-select"
description = "Denies the menu_select command without any pre-configured scope."
commands.deny = ["menu_select"]

View file

@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-menu-state"
description = "Enables the menu_state command without any pre-configured scope."
commands.allow = ["menu_state"]
[[permission]]
identifier = "deny-menu-state"
description = "Denies the menu_state command without any pre-configured scope."
commands.deny = ["menu_state"]

View file

@ -0,0 +1,188 @@
//! The tray card: a small frameless, always-on-top window that a left click on the tray icon shows next to the icon.
//!
//! It is created hidden at start (`create`) and only moved and shown on a click (`toggle`), so it opens instantly. The
//! card never reads the stores: the main window pushes a snapshot of what it already knows (`card_snapshot`, kept here
//! and forwarded as `card-snapshot`), and the card's buttons come back through `card_action`, which reuses the tray
//! menu's paths (`tray-action` read / mute-toggle, `tray-route`), so Refresh is the main window's own Refresh all.
use std::sync::Mutex;
use std::time::{Duration, Instant};
use serde_json::Value;
pub const LABEL: &str = "card";
/// Logical size of the card.
pub const WIDTH: f64 = 360.0;
pub const HEIGHT: f64 = 480.0;
/// Gap between the card and the tray icon / screen edge (logical px).
pub const GAP: f64 = 8.0;
/// A snapshot larger than this is refused (the card shows a handful of rows).
pub const MAX_SNAPSHOT: usize = 64 * 1024;
/// A rectangle in physical pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
}
impl Rect {
fn cx(&self) -> f64 { self.x + self.w / 2.0 }
fn cy(&self) -> f64 { self.y + self.h / 2.0 }
}
fn clamp(v: f64, lo: f64, hi: f64) -> f64 {
if hi < lo { lo } else { v.clamp(lo, hi) }
}
/// Top-left corner of the card (physical px) for a tray icon at `tray`, inside `work` (the monitor's work area, without
/// taskbar / menu bar / Dock). The card sits on the side of the icon that faces the screen: above a bottom taskbar,
/// below the macOS menu bar, beside a left or right taskbar; centred on the icon along the bar, and always inside the
/// work area.
pub fn place(tray: Rect, work: Rect, card_w: f64, card_h: f64, gap: f64) -> (f64, f64) {
let (cx, cy) = (tray.cx(), tray.cy());
let (right, bottom) = (work.x + work.w, work.y + work.h);
let (x, y) = if cy >= bottom {
(cx - card_w / 2.0, tray.y - card_h - gap)
} else if cy <= work.y {
(cx - card_w / 2.0, tray.y + tray.h + gap)
} else if cx <= work.x {
(tray.x + tray.w + gap, cy - card_h / 2.0)
} else if cx >= right {
(tray.x - card_w - gap, cy - card_h / 2.0)
} else if cy > work.y + work.h / 2.0 {
// icon inside the work area (auto-hidden taskbar, overflow flyout): open towards the middle
(cx - card_w / 2.0, tray.y - card_h - gap)
} else {
(cx - card_w / 2.0, tray.y + tray.h + gap)
};
(clamp(x, work.x + gap, right - card_w - gap).round(), clamp(y, work.y + gap, bottom - card_h - gap).round())
}
/// Whether a card action word is one the card may send.
pub fn valid_action(a: &str) -> bool {
matches!(a, "hide" | "open" | "route" | "refresh" | "mute" | "quit" | "external" | "ready" | "size")
}
// ---- the last snapshot ----
static SNAPSHOT: Mutex<Option<Value>> = Mutex::new(None);
/// Keeps the main window's snapshot (an object, at most MAX_SNAPSHOT bytes). False when refused.
pub fn set_snapshot(v: Value) -> bool {
if !v.is_object() || v.to_string().len() > MAX_SNAPSHOT {
return false;
}
if let Ok(mut s) = SNAPSHOT.lock() {
*s = Some(v);
}
true
}
pub fn snapshot() -> Option<Value> {
SNAPSHOT.lock().ok().and_then(|s| s.clone())
}
// ---- show / hide ----
static HIDDEN_AT: Mutex<Option<Instant>> = Mutex::new(None);
/// The card lost focus or was closed: remembered so that the click on the tray icon that caused the blur does not
/// open it again at once (a second click closes it).
pub fn note_hidden() {
if let Ok(mut h) = HIDDEN_AT.lock() {
*h = Some(Instant::now());
}
}
fn just_hidden() -> bool {
HIDDEN_AT.lock().ok().and_then(|h| *h).is_some_and(|t| t.elapsed() < Duration::from_millis(300))
}
#[cfg(desktop)]
mod window {
use super::*;
use tauri::{AppHandle, Emitter, Manager, PhysicalPosition, Runtime, WebviewUrl, WebviewWindowBuilder};
/// The hidden card window, made once at start.
pub fn create<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
let b = WebviewWindowBuilder::new(app, LABEL, WebviewUrl::App("card.html".into()))
.title("storebound")
.inner_size(WIDTH, HEIGHT)
.resizable(false)
.decorations(false)
.always_on_top(true)
.skip_taskbar(true)
.visible(false)
.focused(false)
.shadow(true);
#[cfg(not(target_os = "macos"))]
let b = b.transparent(true);
b.build()?;
Ok(())
}
/// The icon rectangle of the last show, so a size change keeps the card anchored to the icon.
static LAST_ICON: Mutex<Option<Rect>> = Mutex::new(None);
/// Card height in CSS px (what the page measured), clamped; the window keeps WIDTH.
fn height_px(h: f64) -> f64 { h.clamp(120.0, HEIGHT) }
/// Puts the card next to `tray` at its current height: its edge GAP from the icon, inside the work area.
fn anchor<R: Runtime>(app: &AppHandle<R>, w: &tauri::WebviewWindow<R>, tray: Rect, css_h: f64) {
let monitor = app.monitor_from_point(tray.x + tray.w / 2.0, tray.y + tray.h / 2.0).ok().flatten().or_else(|| w.primary_monitor().ok().flatten());
if let Some(m) = monitor {
let s = m.scale_factor();
let wa = m.work_area();
let work = Rect { x: wa.position.x as f64, y: wa.position.y as f64, w: wa.size.width as f64, h: wa.size.height as f64 };
let _ = w.set_size(tauri::PhysicalSize::new((WIDTH * s).round() as u32, (css_h * s).round() as u32));
let (x, y) = place(tray, work, WIDTH * s, css_h * s, GAP * s);
let _ = w.set_position(PhysicalPosition::new(x as i32, y as i32));
}
}
/// The page measured its height: resize the window to it and keep it anchored (the bottom edge stays above a bottom
/// taskbar, no empty band under the content).
pub fn resize<R: Runtime>(app: &AppHandle<R>, css_h: f64) {
let Some(w) = app.get_webview_window(LABEL) else { return };
let h = height_px(css_h);
if let Ok(mut c) = CURRENT_H.lock() { *c = h; }
if let Some(tray) = LAST_ICON.lock().ok().and_then(|t| *t) {
anchor(app, &w, tray, h);
}
}
static CURRENT_H: Mutex<f64> = Mutex::new(HEIGHT);
/// A left click on the tray icon: shows the card next to the icon, or hides it when it is open.
pub fn toggle<R: Runtime>(app: &AppHandle<R>, tray: Rect) {
let Some(w) = app.get_webview_window(LABEL) else { return };
if w.is_visible().unwrap_or(false) {
let _ = w.hide();
note_hidden();
return;
}
if just_hidden() {
return;
}
if let Ok(mut t) = LAST_ICON.lock() { *t = Some(tray); }
let h = CURRENT_H.lock().map(|c| *c).unwrap_or(HEIGHT);
anchor(app, &w, tray, h);
let _ = w.show();
let _ = w.set_focus();
let _ = app.emit_to(LABEL, "card-shown", ());
// the main window refreshes the parts the card shows that it keeps per app (reviews, health from the cache)
let _ = app.emit_to(crate::policy::MAIN, "card-request", ());
}
pub fn hide<R: Runtime>(app: &AppHandle<R>) {
if let Some(w) = app.get_webview_window(LABEL) {
let _ = w.hide();
note_hidden();
}
}
}
#[cfg(desktop)]
pub use window::{create, hide, resize, toggle};

View file

@ -44,6 +44,16 @@ fn guard(w: &WebviewWindow) -> Res<()> {
policy::require_main(w.label(), &url, cfg!(debug_assertions)).map_err(Fail::host) policy::require_main(w.label(), &url, cfg!(debug_assertions)).map_err(Fail::host)
} }
fn guard_card(w: &WebviewWindow) -> Res<()> {
let url = w.url().map_err(|e| Fail::host(e.to_string()))?;
policy::require_card(w.label(), &url, cfg!(debug_assertions)).map_err(Fail::host)
}
fn guard_menu(w: &WebviewWindow) -> Res<()> {
let url = w.url().map_err(|e| Fail::host(e.to_string()))?;
policy::require_menu(w.label(), &url, cfg!(debug_assertions)).map_err(Fail::host)
}
fn saved(s: &AppState) -> Res<std::sync::MutexGuard<'_, Saved>> { fn saved(s: &AppState) -> Res<std::sync::MutexGuard<'_, Saved>> {
s.saved.lock().map_err(|_| Fail::host("state poisoned")) s.saved.lock().map_err(|_| Fail::host("state poisoned"))
} }
@ -1241,6 +1251,10 @@ pub fn settings_set(window: WebviewWindow, state: State<'_, AppState>, settings:
guard(&window)?; guard(&window)?;
workspace::check_settings(&settings).map_err(Fail::host)?; workspace::check_settings(&settings).map_err(Fail::host)?;
let mut st = saved(&state)?; let mut st = saved(&state)?;
if st.settings.channel != settings.channel {
// a switched channel is checked right away by the background updater (lib.rs auto_update)
crate::updates::kick();
}
st.settings = settings.clone(); st.settings = settings.clone();
persist(&state, &st)?; persist(&state, &st)?;
drop(st); drop(st);
@ -1304,6 +1318,73 @@ pub fn tray_update(window: WebviewWindow, app: AppHandle, summary: crate::tray::
crate::tray::apply(&app, &summary).map_err(|e| Fail::host(e.to_string())) crate::tray::apply(&app, &summary).map_err(|e| Fail::host(e.to_string()))
} }
/// The main window's snapshot for the tray card (what it already read: releases, reviews, health, last read, busy).
/// Kept in the host so the card shows it the moment it opens; forwarded to the card as `card-snapshot`.
#[tauri::command]
pub fn card_snapshot(window: WebviewWindow, app: AppHandle, snapshot: Value) -> Res<()> {
guard(&window)?;
if !crate::card::set_snapshot(snapshot.clone()) {
return Err(Fail::host("card snapshot refused"));
}
let _ = app.emit_to(crate::card::LABEL, "card-snapshot", snapshot);
Ok(())
}
/// The card: the last snapshot of the main window (null before the first one).
#[tauri::command]
pub fn card_get(window: WebviewWindow) -> Res<Option<Value>> {
guard_card(&window)?;
Ok(crate::card::snapshot())
}
/// The card's buttons. `refresh` and `mute` go to the main window as the tray menu's `tray-action` (its own Refresh
/// all and mute), `route` shows the main window on a route (`tray-route`), `external` opens a store console.
#[tauri::command]
pub fn card_action(window: WebviewWindow, app: AppHandle, action: String, arg: Option<String>) -> Res<()> {
guard_card(&window)?;
if !crate::card::valid_action(&action) {
return Err(Fail::host("unknown card action"));
}
let main = || {
if let Some(w) = app.get_webview_window(policy::MAIN) {
let _ = w.unminimize();
let _ = w.show();
let _ = w.set_focus();
}
};
match action.as_str() {
"hide" => crate::card::hide(&app),
"ready" => { let _ = app.emit_to(policy::MAIN, "card-request", ()); }
"size" => {
let h: f64 = arg.as_deref().unwrap_or_default().parse().map_err(|_| Fail::host("bad size"))?;
crate::card::resize(&app, h);
}
"open" => { crate::card::hide(&app); main(); }
"refresh" => { let _ = app.emit_to(policy::MAIN, "tray-action", "read"); }
"mute" => { let _ = app.emit_to(policy::MAIN, "tray-action", "mute-toggle"); }
"quit" => app.exit(0),
"route" => {
let r = arg.unwrap_or_default();
if !crate::tray::valid_route(&r) {
return Err(Fail::host("bad route"));
}
crate::card::hide(&app);
main();
let _ = app.emit_to(policy::MAIN, "tray-route", r);
}
"external" => {
let u = url::Url::parse(arg.as_deref().unwrap_or_default()).map_err(|_| Fail::host("not a URL"))?;
if !policy::external_allowed(&u) {
return Err(Fail::host("only the store consoles open from here"));
}
crate::card::hide(&app);
app.opener().open_url(u.as_str(), None::<&str>).map_err(|e| Fail::host(e.to_string()))?;
}
_ => {}
}
Ok(())
}
/// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders /// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders
/// themselves stay), overrides, settings and saved reads. Downloaded tools stay. True when it was reset. /// themselves stay), overrides, settings and saved reads. Downloaded tools stay. True when it was reset.
#[tauri::command] #[tauri::command]
@ -1412,7 +1493,7 @@ pub struct UpdateInfo {
pub date: Option<String>, pub date: Option<String>,
} }
async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plugin_updater::Update>> { pub async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plugin_updater::Update>> {
use tauri_plugin_updater::UpdaterExt; use tauri_plugin_updater::UpdaterExt;
let url = url::Url::parse(updates::endpoint(channel)).map_err(|e| Fail::host(e.to_string()))?; let url = url::Url::parse(updates::endpoint(channel)).map_err(|e| Fail::host(e.to_string()))?;
if !updates::endpoint_allowed(&url) { if !updates::endpoint_allowed(&url) {
@ -1423,6 +1504,8 @@ async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plugin_
.endpoints(vec![url]) .endpoints(vec![url])
.map_err(|e| Fail::host(e.to_string()))? .map_err(|e| Fail::host(e.to_string()))?
.timeout(std::time::Duration::from_secs(30)) .timeout(std::time::Duration::from_secs(30))
// the no-downgrade rule (updates::should_install), also after a switch from dev back to stable
.version_comparator(|current, remote| updates::should_install(&current.to_string(), &remote.version.to_string()))
.build() .build()
.map_err(|e| Fail::host(updates::error_text(&e.to_string())))?; .map_err(|e| Fail::host(updates::error_text(&e.to_string())))?;
updater.check().await.map_err(|e| Fail::host(updates::error_text(&e.to_string()))) updater.check().await.map_err(|e| Fail::host(updates::error_text(&e.to_string())))
@ -1591,3 +1674,79 @@ pub async fn ai_fix_undo(window: WebviewWindow, run_id: String) -> Res<Vec<Strin
let rec = ai_fix::runs().lock().ok().and_then(|mut m| m.remove(&run_id)).ok_or_else(|| Fail::host("no such AI fix run"))?; let rec = ai_fix::runs().lock().ok().and_then(|mut m| m.remove(&run_id)).ok_or_else(|| Fail::host("no such AI fix run"))?;
tauri::async_runtime::spawn_blocking(move || ai_fix::undo(&rec.0, &rec.1)).await.map_err(|e| Fail::host(e.to_string()))?.map_err(Fail::host) tauri::async_runtime::spawn_blocking(move || ai_fix::undo(&rec.0, &rec.1)).await.map_err(|e| Fail::host(e.to_string()))?.map_err(Fail::host)
} }
// ---- the tray menu panels (menu_panel.rs; only `menu-*` windows) ----
/// A panel: what it shows (the whole tree and its path into it).
#[tauri::command]
pub fn menu_state(window: WebviewWindow) -> Res<Option<crate::menu_panel::PanelInfo>> {
guard_menu(&window)?;
Ok(crate::menu_panel::panel_state(&window))
}
/// A panel measured itself (CSS px): sized, placed inside the work area and shown.
#[tauri::command]
pub fn menu_ready(window: WebviewWindow, width: f64, height: f64) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::ready(&window, width, height);
Ok(())
}
/// Opens a submenu beside this panel at the row whose top is `top` (CSS px).
#[tauri::command]
pub fn menu_open_sub(window: WebviewWindow, key: String, top: f64, focus: bool) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::open_sub(&window, &key, top, focus, false);
Ok(())
}
/// Ctrl / middle click on a submenu row: opens it as its own pinned panel.
#[tauri::command]
pub fn menu_pin_sub(window: WebviewWindow, key: String, top: f64) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::open_sub(&window, &key, top, false, true);
Ok(())
}
/// The pointer moved to a plain row: this panel's submenus close.
#[tauri::command]
pub fn menu_close_subs(window: WebviewWindow) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::close_subs(&window);
Ok(())
}
/// Closes this panel (Left / Esc in a submenu, X on a pinned one).
#[tauri::command]
pub fn menu_close(window: WebviewWindow, refocus_parent: bool) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::close(&window, refocus_parent);
Ok(())
}
/// Esc on the root menu: every transient panel closes.
#[tauri::command]
pub fn menu_dismiss(window: WebviewWindow) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::dismiss(window.app_handle());
Ok(())
}
/// Pins or unpins this panel.
#[tauri::command]
pub fn menu_pin(window: WebviewWindow, pinned: bool) -> Res<()> {
guard_menu(&window)?;
crate::menu_panel::pin(&window, pinned);
Ok(())
}
/// A pick: the same action as the native tray menu (an id tray.rs knows; anything else is refused).
#[tauri::command]
pub fn menu_select(window: WebviewWindow, id: String) -> Res<()> {
guard_menu(&window)?;
if id.len() > 300 || crate::tray::action_of(&id).is_none() {
return Err(Fail::host("unknown menu item"));
}
crate::menu_panel::select(&window, id);
Ok(())
}

View file

@ -37,6 +37,7 @@ pub const COMMANDS: &[&str] = &[
"data_reveal", "data_reveal",
"notify", "notify",
"tray_update", "tray_update",
"card_snapshot",
"app_reset", "app_reset",
"update_check", "update_check",
"update_install", "update_install",
@ -52,3 +53,9 @@ pub const COMMANDS: &[&str] = &[
"ai_fix_run", "ai_fix_run",
"ai_fix_undo", "ai_fix_undo",
]; ];
/// The tray card window's commands (capabilities/card.json grants them to the `card` window only).
pub const CARD_COMMANDS: &[&str] = &["card_get", "card_action"];
/// The tray menu panels' commands (capabilities/menu.json grants them to the `menu-*` windows only).
pub const MENU_COMMANDS: &[&str] = &["menu_state", "menu_ready", "menu_open_sub", "menu_pin_sub", "menu_close_subs", "menu_close", "menu_dismiss", "menu_pin", "menu_select"];

View file

@ -3,10 +3,12 @@
pub mod accounts; pub mod accounts;
pub mod ai_fix; pub mod ai_fix;
pub mod cache; pub mod cache;
pub mod card;
pub mod commands; pub mod commands;
pub mod confirm; pub mod confirm;
pub mod downloads; pub mod downloads;
pub mod logs; pub mod logs;
pub mod menu_panel;
pub mod policy; pub mod policy;
pub mod profiles; pub mod profiles;
pub mod registry; pub mod registry;
@ -25,7 +27,6 @@ use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu, WINDOW_SUBMENU_ID
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime, WindowEvent}; use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime, WindowEvent};
use tauri_plugin_autostart::{MacosLauncher, ManagerExt}; use tauri_plugin_autostart::{MacosLauncher, ManagerExt};
use tauri_plugin_updater::UpdaterExt;
use tauri_plugin_deep_link::DeepLinkExt; use tauri_plugin_deep_link::DeepLinkExt;
/// WebKitGTK's DMABUF renderer leaves the window blank on some Linux GPU / driver / VM combinations. Turn it off unless /// WebKitGTK's DMABUF renderer leaves the window blank on some Linux GPU / driver / VM combinations. Turn it off unless
@ -43,17 +44,76 @@ fn started_hidden() -> bool {
std::env::args().any(|a| a == "--hidden") std::env::args().any(|a| a == "--hidden")
} }
/// Tray icon: a click shows the window; the menu (tray.rs) opens the window, reads the stores, lists the apps with their /// Tray icon: a left click shows the tray card (card.rs), a right click the app's own menu panels (menu_panel.rs, with
/// state, mutes notifications, checks for updates, opens Settings and quits (the only real quit on Windows and Linux, /// the tree from tray.rs: open the window, read the stores, the apps with their state, mute, updates, Settings and Quit,
/// where closing the window keeps the app running in the tray). The window refines tooltip, menu and icon after every /// the only real quit on Windows and Linux, where closing the window keeps the app running in the tray). The window
/// read (`tray_update`). /// refines tooltip, menu and icon after every read (`tray_update`). Linux trays send no clicks: the native menu,
/// rendered from the same tree, stays on the icon there (and anywhere the panels fail).
fn tray(app: &tauri::App) -> tauri::Result<()> { fn tray(app: &tauri::App) -> tauri::Result<()> {
let menu = tray::initial_menu(app.handle())?; let handle = app.handle();
let mut b = TrayIconBuilder::with_id("main").tooltip("storebound").menu(&menu).show_menu_on_left_click(false); let panels = handle.state::<menu_panel::MenuPanels>();
if let Ok(mut n) = panels.nodes.lock() {
*n = tray::initial_nodes();
}
let mut b = TrayIconBuilder::with_id("main").tooltip("storebound").show_menu_on_left_click(false);
if cfg!(target_os = "linux") {
panels.native.store(true, std::sync::atomic::Ordering::Relaxed);
b = b.menu(&tray::native_menu(handle, &tray::initial_nodes())?);
}
if let Some(icon) = app.default_window_icon() { if let Some(icon) = app.default_window_icon() {
b = b.icon(icon.clone()); b = b.icon(icon.clone());
} }
b.on_menu_event(|app, e| match tray::action_of(e.id().as_ref()) { b.on_menu_event(|app, e| dispatch_menu(app, e.id().as_ref()))
.on_tray_icon_event(|t, e| {
let TrayIconEvent::Click { button, button_state: MouseButtonState::Up, rect, position, .. } = e else { return };
let app = t.app_handle();
// both open from the icon's rectangle (not the click point): their edge sits next to the icon, above a
// bottom taskbar, so nothing starts inside the taskbar
let scale = app.get_webview_window(policy::MAIN).and_then(|w| w.scale_factor().ok()).unwrap_or(1.0);
let p = rect.position.to_physical::<f64>(scale);
let s = rect.size.to_physical::<f64>(scale);
let icon = if s.width > 0.0 && s.height > 0.0 { card::Rect { x: p.x, y: p.y, w: s.width, h: s.height } } else { card::Rect { x: position.x, y: position.y, w: 1.0, h: 1.0 } };
match button {
MouseButton::Right => menu_panel::open_root(app, menu_panel::Anchor::Tray { x: icon.x, y: icon.y, w: icon.w, h: icon.h }),
MouseButton::Left => {
if app.get_webview_window(card::LABEL).is_none() {
show_main(app);
return;
}
card::toggle(app, icon);
}
_ => {}
}
})
.build(app)?;
Ok(())
}
/// A tray menu pick (a menu panel row or the native fallback menu): tray.rs maps the id to what it does.
/// Whether the person turned storebound off in Windows' Startup apps (Settings / Task Manager), from the
/// HKCU\...\Explorer\StartupApproved\Run value named like the Run entry: its first byte is even when enabled (02, 06),
/// odd when disabled (03, 07). No value: not turned off. Pure.
pub fn startup_approved_off(value: &[u8]) -> bool {
value.first().is_some_and(|b| b & 1 == 1)
}
#[cfg(windows)]
fn startup_disabled_by_user() -> bool {
use winreg::{enums::HKEY_CURRENT_USER, RegKey};
RegKey::predef(HKEY_CURRENT_USER)
.open_subkey(r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run")
.and_then(|k| k.get_raw_value("storebound"))
.map(|v| startup_approved_off(&v.bytes))
.unwrap_or(false)
}
#[cfg(not(windows))]
fn startup_disabled_by_user() -> bool {
false
}
pub fn dispatch_menu<R: Runtime>(app: &AppHandle<R>, id: &str) {
match tray::action_of(id) {
Some(tray::Action::Open) => show_main(app), Some(tray::Action::Open) => show_main(app),
Some(tray::Action::Quit) => app.exit(0), Some(tray::Action::Quit) => app.exit(0),
Some(tray::Action::Event(word)) => { Some(tray::Action::Event(word)) => {
@ -64,41 +124,84 @@ fn tray(app: &tauri::App) -> tauri::Result<()> {
let _ = app.emit_to(policy::MAIN, "tray-route", route); let _ = app.emit_to(policy::MAIN, "tray-route", route);
} }
None => {} None => {}
})
.on_tray_icon_event(|t, e| {
if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = e {
show_main(t.app_handle());
} }
})
.build(app)?;
Ok(())
} }
/// Silent self-update: at start (after a minute) and every 30 minutes, a signed update from storebound.dev is /// Silent self-update: at start (after a minute) and every 30 minutes, a signed update from storebound.dev is
/// downloaded, installed and the app restarts with the same arguments (`--hidden` stays hidden). Errors are logged. /// downloaded, installed and the app restarts with the same arguments (`--hidden` stays hidden). Errors are logged.
/// Background updater (docs/desktop-release.md, "Dev channel"): asks the chosen channel's latest.json at start, every
/// 15 minutes, right after a resume from sleep and when Settings switched the channel; installs a strictly newer, signed
/// build silently (the plugin checks the minisign signature first), deferred while the main window is in use (at most
/// updates::MAX_DEFERS checks in a row). Every step goes to host.log as `auto-update ...`.
fn auto_update(app: AppHandle) { fn auto_update(app: AppHandle) {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(60)).await; use std::time::{Duration, Instant, SystemTime};
tokio::time::sleep(Duration::from_secs(10)).await;
let mut first = true;
let mut last_check = Instant::now();
let mut last_wall = SystemTime::now();
let mut defers = 0u32;
loop { loop {
match app.updater() { let now_wall = SystemTime::now();
Ok(u) => match u.check().await { let gap = now_wall.duration_since(last_wall).map(|d| d.as_secs()).unwrap_or(0);
Ok(Some(update)) => { last_wall = now_wall;
logs::host("info", &format!("auto-update: {} available, installing", update.version)); let kicked = updates::take_kick();
match update.download_and_install(|_, _| {}, || {}).await { if updates::check_due(first, kicked, gap, last_check.elapsed().as_secs()) {
Ok(()) => app.restart(), let why = if first { "start" } else if kicked { "channel switched" } else if gap > updates::TICK_SECS + 60 { "resume" } else { "every 15 min" };
Err(e) => logs::host("warn", &format!("auto-update: install failed: {e}")), first = false;
last_check = Instant::now();
defers = auto_update_once(&app, why, defers).await;
} }
} tokio::time::sleep(Duration::from_secs(updates::TICK_SECS)).await;
Ok(None) => {}
Err(e) => logs::host("warn", &format!("auto-update: check failed: {e}")),
},
Err(e) => logs::host("warn", &format!("auto-update: no updater: {e}")),
}
tokio::time::sleep(std::time::Duration::from_secs(30 * 60)).await;
} }
}); });
} }
/// One check of the background updater; returns the new count of deferred installs.
async fn auto_update_once(app: &AppHandle, why: &str, defers: u32) -> u32 {
let state = app.state::<commands::AppState>();
let channel = match state.saved.lock() {
Ok(s) => s.settings.channel.clone(),
Err(_) => return defers,
};
let current = env!("CARGO_PKG_VERSION");
let update = match commands::find_update(app, &channel).await {
Ok(Some(u)) => u,
Ok(None) => {
logs::host("info", &format!("auto-update ({why}): {current} is current on {channel}"));
return 0;
}
Err(e) => {
logs::host("warn", &format!("auto-update ({why}): check of {channel} failed: {}", e.message));
return defers;
}
};
if !updates::should_install(current, &update.version) {
logs::host("info", &format!("auto-update ({why}): {channel} offers {}, not newer than {current}: no downgrade", update.version));
return 0;
}
let main = app.get_webview_window(policy::MAIN);
let visible = main.as_ref().and_then(|w| w.is_visible().ok()).unwrap_or(false);
let focused = main.as_ref().and_then(|w| w.is_focused().ok()).unwrap_or(false);
if updates::defer_install(visible, focused, defers) {
logs::host("info", &format!("auto-update ({why}): {} on {channel} waits, the window is in use ({}/{})", update.version, defers + 1, updates::MAX_DEFERS));
return defers + 1;
}
logs::host("info", &format!("auto-update ({why}): installing {} from {channel} (this is {current})", update.version));
// the sidecar binary lives inside the app bundle that is about to be replaced
state.sidecar.shutdown().await;
match update.download_and_install(|_, _| {}, || {}).await {
Ok(()) => {
logs::host("info", &format!("auto-update: {} installed, restarting", update.version));
app.restart()
}
Err(e) => {
logs::host("warn", &format!("auto-update: install of {} failed: {}", update.version, updates::error_text(&e.to_string())));
0
}
}
}
fn show_main<R: Runtime>(app: &AppHandle<R>) { fn show_main<R: Runtime>(app: &AppHandle<R>) {
if let Some(w) = app.get_webview_window(policy::MAIN) { if let Some(w) = app.get_webview_window(policy::MAIN) {
let _ = w.unminimize(); let _ = w.unminimize();
@ -219,11 +322,12 @@ pub fn run() {
early_trace(); early_trace();
linux_webkit_env(); linux_webkit_env();
let app = tauri::Builder::default() let app = tauri::Builder::default()
// single-instance first: a second start (or a storebound:// link) focuses the running app instead // single-instance first: a second start (or a storebound:// link) focuses the running app instead; a second
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| show_main(app))) // logon start (--hidden: the Run entry plus a Startup folder shortcut) stays in the tray
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| if !argv.iter().any(|a| a == "--hidden") { show_main(app) }))
.plugin(tauri_plugin_deep_link::init()) .plugin(tauri_plugin_deep_link::init())
// never restore "visible": a --hidden start would otherwise pop the window up // never restore "visible": a --hidden start would otherwise pop the window up
.plugin(tauri_plugin_window_state::Builder::new().with_state_flags(tauri_plugin_window_state::StateFlags::all() & !tauri_plugin_window_state::StateFlags::VISIBLE).build()) .plugin(tauri_plugin_window_state::Builder::new().with_filter(|label| !label.starts_with(menu_panel::LABEL_PREFIX)).with_state_flags(tauri_plugin_window_state::StateFlags::all() & !tauri_plugin_window_state::StateFlags::VISIBLE).build())
.plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, Some(vec!["--hidden"]))) .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, Some(vec!["--hidden"])))
.plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
@ -271,16 +375,25 @@ pub fn run() {
if let Err(e) = commands::sync_machine(&state) { if let Err(e) = commands::sync_machine(&state) {
logs::host("warn", &format!("accounts / app folders not synced at start: {}", e.message)); logs::host("warn", &format!("accounts / app folders not synced at start: {}", e.message));
} }
// start at logon, in the tray: set once (first run); the owner can turn it off in the OS afterwards // start at logon, in the tray: rewritten on every start (Windows: the HKCU Run entry then points at the
let marker = state.data_dir.join("autostart-set"); // running exe, so a moved or updated install fixes itself)
if !marker.exists() { // ...unless the person turned it off (Windows Settings > Apps > Startup / Task Manager): that choice stands
if startup_disabled_by_user() {
logs::host("info", "autostart at logon left off (turned off in Windows Startup apps)");
} else {
match app.autolaunch().enable() { match app.autolaunch().enable() {
Ok(()) => { let _ = std::fs::write(&marker, "1"); logs::host("info", "autostart at logon enabled (--hidden, tray)"); } Ok(()) => logs::host("info", "autostart at logon set (--hidden, tray)"),
Err(e) => logs::host("warn", &format!("autostart not enabled: {e}")), Err(e) => logs::host("warn", &format!("autostart not set: {e}")),
} }
} }
app.manage(state); app.manage(state);
app.manage(menu_panel::MenuPanels::default());
tray(app)?; tray(app)?;
// pinned tray menu panels of the last session come back
menu_panel::restore(app.handle());
if let Err(e) = card::create(app.handle()) {
logs::host("warn", &format!("tray card not created: {e}"));
}
if !started_hidden() { if !started_hidden() {
show_main(app.handle()); show_main(app.handle());
} }
@ -310,6 +423,13 @@ pub fn run() {
.on_window_event(|w, e| { .on_window_event(|w, e| {
// the close button hides the window: the app keeps running in the tray (macOS: also the Dock); the tray's // the close button hides the window: the app keeps running in the tray (macOS: also the Dock); the tray's
// Quit (macOS: Cmd+Q) really quits // Quit (macOS: Cmd+Q) really quits
if w.label() == card::LABEL {
match e {
WindowEvent::Focused(false) => { let _ = w.hide(); card::note_hidden(); }
WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); let _ = w.hide(); card::note_hidden(); }
_ => {}
}
}
if w.label() == policy::MAIN { if w.label() == policy::MAIN {
if let WindowEvent::CloseRequested { api, .. } = e { if let WindowEvent::CloseRequested { api, .. } = e {
api.prevent_close(); api.prevent_close();
@ -354,6 +474,7 @@ pub fn run() {
commands::data_reveal, commands::data_reveal,
commands::notify, commands::notify,
commands::tray_update, commands::tray_update,
commands::card_snapshot,
commands::app_reset, commands::app_reset,
commands::update_check, commands::update_check,
commands::update_install, commands::update_install,
@ -368,6 +489,17 @@ pub fn run() {
commands::ai_fix_info, commands::ai_fix_info,
commands::ai_fix_run, commands::ai_fix_run,
commands::ai_fix_undo, commands::ai_fix_undo,
commands::card_get,
commands::card_action,
commands::menu_state,
commands::menu_ready,
commands::menu_open_sub,
commands::menu_pin_sub,
commands::menu_close_subs,
commands::menu_close,
commands::menu_dismiss,
commands::menu_pin,
commands::menu_select,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("storebound desktop failed to start"); .expect("storebound desktop failed to start");

View file

@ -0,0 +1,749 @@
//! The tray's right-click menu, drawn by the app itself instead of the OS menu (tray-menu.html, src/traymenu/).
//!
//! - One tree: tray.rs builds the menu as `Entry`s, turned here into `Node`s. Every submenu has a stable key (its label
//! without the live part), so an open or pinned panel finds its submenu again after the values change.
//! - One window per panel: the root menu and each submenu are their own frameless, always-on-top `menu-N` windows. The
//! page measures itself and calls `menu_ready`; Rust sizes, places (inside the monitor's work area) and shows it.
//! - The panel book (`Book`, pure, tests/menu_panel.rs) records which panels are open, which are pinned and whose child
//! each one is. Transient panels close together (focus left all of them, Esc, a pick); pinned ones stay, can be
//! dragged, step aside so they never cover each other and come back after a restart (`menuPins` in state.json).
//! - Live: every `tray_update` pushes the tree to the open panels (`menu-model`), which update in place. Nothing polls.
//! - Idle: a closed panel is destroyed, never hidden.
//! - Fallback: when a panel window cannot be built or never reports ready, the native tray menu (rendered from the same
//! tree) comes back. Linux always uses it (its tray sends no click events).
//!
//! The top half is pure and covered by tests/menu_panel.rs.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::tray::Entry;
pub const LABEL_PREFIX: &str = "menu-";
pub const PAGE: &str = "tray-menu.html";
pub const MODEL_EVENT: &str = "menu-model";
pub const PANEL_EVENT: &str = "menu-panel";
/// Gap to the work area's edges (physical px at scale 1).
pub const GAP: f64 = 8.0;
/// The estimated size of a panel before it measured itself (logical px).
pub const EST: (f64, f64) = (280.0, 220.0);
// ---------------------------------------------------------------- model
#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Node {
Item { id: String, label: String, enabled: bool },
Sep,
Sub { key: String, label: String, items: Vec<Node> },
}
/// A submenu's stable key: its label without status glyphs and without the live part after ':' / '·' / '('
/// ("Apps (3)" -> "apps", "Apps · 2 need you" -> "apps"). Pinned panels are found again by these keys.
pub fn sub_key(label: &str) -> String {
let head = label.split([':', '\u{00B7}', '(']).next().unwrap_or("");
let mut out = String::new();
for c in head.chars() {
if c.is_alphanumeric() {
out.extend(c.to_lowercase());
} else if (c == ' ' || c == '-' || c == '_') && !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
let out = out.trim_end_matches('-').to_string();
if out.is_empty() { "sub".into() } else { out }
}
/// Sibling submenus with the same key get "-2", "-3"...
pub fn unique_keys(mut nodes: Vec<Node>) -> Vec<Node> {
let mut seen: BTreeMap<String, u32> = BTreeMap::new();
for n in nodes.iter_mut() {
if let Node::Sub { key, .. } = n {
let count = seen.entry(key.clone()).or_insert(0);
*count += 1;
if *count > 1 {
*key = format!("{key}-{count}");
}
}
}
nodes
}
/// The tray menu entries as panel nodes. A submenu keeps the fixed key tray.rs gives it (so a translated label never
/// changes it), else the key comes from its label.
pub fn from_entries(entries: &[Entry]) -> Vec<Node> {
let nodes = entries
.iter()
.map(|e| match e {
Entry::Item { id, label, enabled } => Node::Item { id: id.clone(), label: label.clone(), enabled: *enabled },
Entry::Separator => Node::Sep,
Entry::Sub { key, label, items } => Node::Sub { key: if key.is_empty() { sub_key(label) } else { sub_key(key) }, label: label.clone(), items: from_entries(items) },
})
.collect();
unique_keys(nodes)
}
/// The items of the submenu at `path` (empty path: the root) and its label.
pub fn find<'a>(nodes: &'a [Node], path: &[String]) -> Option<(&'a [Node], Option<&'a str>)> {
let mut current = nodes;
let mut label = None;
for key in path {
let (items, l) = current.iter().find_map(|n| match n {
Node::Sub { key: k, label: l, items } if k == key => Some((items.as_slice(), l.as_str())),
_ => None,
})?;
current = items;
label = Some(l);
}
Some((current, label))
}
// ---------------------------------------------------------------- placement
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Anchor {
/// The tray click point (physical).
Point { x: f64, y: f64 },
/// The tray icon's rectangle (physical): the root opens from the icon's edge that faces the screen, like the card.
Tray { x: f64, y: f64, w: f64, h: f64 },
/// Beside a parent panel: its left and right edge and the row's top (physical).
Beside { left: f64, right: f64, top: f64 },
/// A remembered top-left (pinned panels).
At { x: f64, y: f64 },
}
/// x, y, width, height (physical px).
pub type Rect = (f64, f64, f64, f64);
/// Keeps a panel of size w x h fully inside the work area (with `GAP`).
pub fn clamp_into(x: f64, y: f64, w: f64, h: f64, work: Rect) -> (f64, f64) {
let (wx, wy, ww, wh) = work;
(x.clamp(wx + GAP, (wx + ww - w - GAP).max(wx + GAP)), y.clamp(wy + GAP, (wy + wh - h - GAP).max(wy + GAP)))
}
/// Where a panel of `size` goes for `anchor`, inside the work area: the root opens away from the taskbar / menu bar the
/// click is near, a submenu beside its parent (flipped left at the screen edge), a pinned panel at its spot.
pub fn place_menu(anchor: Anchor, size: (f64, f64), work: Rect) -> (f64, f64) {
let (w, h) = size;
let (wx, wy, ww, wh) = work;
let (x, y) = match anchor {
Anchor::Point { x, y } => (if x + w > wx + ww { x - w } else { x }, if y + h > wy + wh { y - h } else { y }),
// same rule as the card: the panel's edge sits GAP from the icon, never over the taskbar
Anchor::Tray { x, y, w: iw, h: ih } => return crate::card::place(crate::card::Rect { x, y, w: iw, h: ih }, crate::card::Rect { x: wx, y: wy, w: ww, h: wh }, w, h, GAP),
Anchor::Beside { left, right, top } => (if right + w <= wx + ww - GAP { right - 2.0 } else { left - w + 2.0 }, top - 5.0),
Anchor::At { x, y } => (x, y),
};
clamp_into(x, y, w, h, work)
}
pub fn overlaps(a: Rect, b: Rect) -> bool {
a.0 < b.0 + b.2 && b.0 < a.0 + a.2 && a.1 < b.1 + b.3 && b.1 < a.1 + a.3
}
/// A spot for a newly pinned panel that covers no other pinned panel: below whatever it overlaps, then the next column.
/// Gives up after a while (a screen full of pins) and returns the clamped wish.
pub fn free_spot(want: Rect, others: &[Rect], work: Rect) -> (f64, f64) {
let (mut x, mut y, w, h) = want;
for _ in 0..64 {
let Some(hit) = others.iter().find(|o| overlaps((x, y, w, h), **o)) else {
return clamp_into(x, y, w, h, work);
};
y = hit.1 + hit.3 + GAP;
if y + h > work.1 + work.3 {
y = work.1 + GAP;
x += w + GAP;
if x + w > work.0 + work.2 {
x = work.0 + GAP;
}
}
}
clamp_into(want.0, want.1, w, h, work)
}
// ---------------------------------------------------------------- panel book
#[derive(Clone, Debug, PartialEq)]
pub struct Panel {
pub path: Vec<String>,
pub pinned: bool,
pub parent: Option<String>,
pub anchor: Anchor,
/// Measured and shown once.
pub shown: bool,
/// Physical top-left once shown (kept for pins).
pub pos: Option<(f64, f64)>,
/// Opened from the keyboard: takes focus and starts on its first row.
pub focus: bool,
}
/// A pinned panel as state.json keeps it (`menuPins`).
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct PinRecord {
pub path: Vec<String>,
pub x: i32,
pub y: i32,
}
/// Which panels are open, which are pinned, who is whose child.
#[derive(Default, Debug)]
pub struct Book {
pub panels: BTreeMap<String, Panel>,
next: u32,
}
impl Book {
fn add(&mut self, path: Vec<String>, pinned: bool, parent: Option<String>, anchor: Anchor) -> String {
self.next += 1;
let label = format!("{LABEL_PREFIX}{}", self.next);
self.panels.insert(label.clone(), Panel { path, pinned, parent, anchor, shown: false, pos: None, focus: false });
label
}
fn remove_all(&mut self, labels: &[String]) {
for l in labels {
self.panels.remove(l);
}
}
pub fn transient(&self) -> Vec<String> {
self.panels.iter().filter(|(_, p)| !p.pinned).map(|(l, _)| l.clone()).collect()
}
/// Transient panels below `label` (children first).
pub fn descendants(&self, label: &str) -> Vec<String> {
let mut out = Vec::new();
let mut frontier = vec![label.to_string()];
while let Some(l) = frontier.pop() {
for (child, p) in &self.panels {
if p.parent.as_deref() == Some(l.as_str()) && !p.pinned && !out.contains(child) {
out.push(child.clone());
frontier.push(child.clone());
}
}
}
out
}
/// A fresh root menu: every transient panel closes, pinned ones stay. Returns the new label and the closed ones.
pub fn open_root(&mut self, anchor: Anchor) -> (String, Vec<String>) {
let closes = self.transient();
self.remove_all(&closes);
(self.add(vec![], false, None, anchor), closes)
}
/// Opens submenu `key` of `parent`; its other transient children close. None when that submenu already is the open
/// child, or the parent is gone. `pinned`: torn off as its own pinned panel (one pinned copy per submenu).
pub fn open_sub(&mut self, parent: &str, key: &str, anchor: Anchor, pinned: bool) -> Option<(String, Vec<String>)> {
let mut path = self.panels.get(parent)?.path.clone();
path.push(key.to_string());
if !pinned && self.panels.values().any(|p| p.parent.as_deref() == Some(parent) && !p.pinned && p.path == path) {
return None;
}
let mut closes = self.descendants(parent);
self.remove_all(&closes);
if pinned {
let old: Vec<String> = self.panels.iter().filter(|(_, p)| p.pinned && p.path == path).map(|(l, _)| l.clone()).collect();
for l in old {
closes.extend(self.close(&l));
}
return Some((self.add(path, true, None, anchor), closes));
}
Some((self.add(path, false, Some(parent.to_string()), anchor), closes))
}
/// Closes `label` and its transient children.
pub fn close(&mut self, label: &str) -> Vec<String> {
if !self.panels.contains_key(label) {
return vec![];
}
let mut out = self.descendants(label);
out.push(label.to_string());
self.remove_all(&out);
out
}
/// Every transient panel closes (Esc on the root, a pick, focus left the menus).
pub fn dismiss(&mut self) -> Vec<String> {
let t = self.transient();
self.remove_all(&t);
t
}
/// Pin or unpin. Pinning detaches the panel from its chain: the transient panels that are not its own children
/// close (returned). A second pinned copy of the same submenu closes too.
pub fn pin(&mut self, label: &str, on: bool) -> Vec<String> {
let Some(p) = self.panels.get(label) else { return vec![] };
let path = p.path.clone();
if !on {
if let Some(p) = self.panels.get_mut(label) {
p.pinned = false;
}
return vec![];
}
let mut closes: Vec<String> = self.panels.iter().filter(|(l, p)| p.pinned && p.path == path && l.as_str() != label).map(|(l, _)| l.clone()).collect();
if let Some(p) = self.panels.get_mut(label) {
p.pinned = true;
p.parent = None;
}
let mine = self.descendants(label);
closes.extend(self.transient().into_iter().filter(|l| l != label && !mine.contains(l)));
self.remove_all(&closes);
closes
}
/// The tree changed: transient panels whose submenu is gone close (with their children). Pinned ones stay and show
/// that their submenu is gone until it comes back (an app that is read again) or they are closed.
pub fn prune(&mut self, nodes: &[Node]) -> Vec<String> {
let gone: Vec<String> = self.panels.iter().filter(|(_, p)| !p.pinned && find(nodes, &p.path).is_none()).map(|(l, _)| l.clone()).collect();
let mut out = Vec::new();
for l in gone {
if self.panels.contains_key(&l) {
out.extend(self.close(&l));
}
}
out
}
/// The pinned panels to save (only placed ones; in label order, so the order is stable).
pub fn pins(&self) -> Vec<PinRecord> {
self.panels
.values()
.filter(|p| p.pinned)
.filter_map(|p| p.pos.map(|(x, y)| PinRecord { path: p.path.clone(), x: x.round() as i32, y: y.round() as i32 }))
.collect()
}
/// Recreates pinned panels from a saved list (duplicates and more than `MAX_PINS` dropped).
pub fn restore(&mut self, pins: &[PinRecord]) -> Vec<String> {
let mut out = Vec::new();
for r in pins.iter().take(MAX_PINS) {
if self.panels.values().any(|p| p.pinned && p.path == r.path) || r.path.len() > 8 {
continue;
}
let (x, y) = (r.x as f64, r.y as f64);
let l = self.add(r.path.clone(), true, None, Anchor::At { x, y });
if let Some(p) = self.panels.get_mut(&l) {
p.pos = Some((x, y));
}
out.push(l);
}
out
}
}
/// At most this many pinned panels are restored after a restart.
pub const MAX_PINS: usize = 12;
/// A panel label the app made (`menu-` and a number), for the window / command checks.
pub fn is_menu_label(label: &str) -> bool {
label.strip_prefix(LABEL_PREFIX).is_some_and(|n| !n.is_empty() && n.len() <= 9 && n.chars().all(|c| c.is_ascii_digit()))
}
// ---------------------------------------------------------------- runtime
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PanelInfo {
pub label: String,
pub path: Vec<String>,
pub pinned: bool,
pub has_parent: bool,
pub focus_first: bool,
pub nodes: Vec<Node>,
}
/// The panels' shared state (managed by the app).
#[derive(Default)]
pub struct MenuPanels {
pub book: Mutex<Book>,
pub nodes: Mutex<Vec<Node>>,
/// The native menu took over (a panel failed, or Linux).
pub native: AtomicBool,
/// Bumped on every move of a pinned panel; the save runs once the moves stop.
moves: AtomicU64,
}
#[cfg(desktop)]
mod runtime {
use super::*;
use tauri::{AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
fn state(app: &AppHandle) -> tauri::State<'_, MenuPanels> {
app.state::<MenuPanels>()
}
fn book<R>(app: &AppHandle, f: impl FnOnce(&mut Book) -> R) -> R {
let s = state(app);
let mut b = s.book.lock().unwrap_or_else(|e| e.into_inner());
f(&mut b)
}
fn nodes(app: &AppHandle) -> Vec<Node> {
state(app).nodes.lock().map(|n| n.clone()).unwrap_or_default()
}
pub fn native_fallback(app: &AppHandle) -> bool {
state(app).native.load(Ordering::Relaxed)
}
/// Puts the native menu (from the current tree) on the tray: the fallback, and Linux.
pub fn set_native(app: &AppHandle) {
let Some(tray) = app.tray_by_id("main") else { return };
match crate::tray::native_menu(app, &nodes(app)) {
Ok(m) => {
let _ = tray.set_menu(Some(m));
}
Err(e) => crate::logs::host("warn", &format!("native tray menu not built: {e}")),
}
}
/// Writes the pinned panels into state.json (`menuPins`).
fn save_pins(app: &AppHandle) {
let pins = book(app, |b| b.pins());
let Some(s) = app.try_state::<crate::commands::AppState>() else { return };
let Ok(mut st) = s.saved.lock() else { return };
if st.menu_pins == pins {
return;
}
st.menu_pins = pins;
if let Err(e) = crate::store::save(&s.data_dir, &st) {
crate::logs::host("warn", &format!("menu pins not saved: {e}"));
}
}
/// Stores the latest tree and pushes it to every open panel (they update in place). Panels of a submenu that is gone
/// close when transient. Cheap when nothing changed or no panel is open.
pub fn set_nodes(app: &AppHandle, next: Vec<Node>) {
let changed = {
let s = state(app);
let mut g = s.nodes.lock().unwrap_or_else(|e| e.into_inner());
let changed = *g != next;
*g = next.clone();
changed
};
if !changed {
return;
}
let (closes, open) = book(app, |b| (b.prune(&next), b.panels.keys().cloned().collect::<Vec<_>>()));
destroy(app, &closes);
for l in open {
let _ = app.emit_to(l.as_str(), MODEL_EVENT, &next);
}
if native_fallback(app) {
set_native(app);
}
}
fn destroy(app: &AppHandle, labels: &[String]) {
for l in labels {
if let Some(w) = app.get_webview_window(l) {
let _ = w.destroy();
}
}
}
fn build_window(app: &AppHandle, label: &str) -> tauri::Result<WebviewWindow> {
let b = WebviewWindowBuilder::new(app, label, WebviewUrl::App(PAGE.into()))
.title("storebound")
.inner_size(EST.0, EST.1)
.decorations(false)
.always_on_top(true)
.skip_taskbar(true)
.resizable(false)
.shadow(true)
.visible(false)
.focused(false);
#[cfg(not(target_os = "macos"))]
let b = b.transparent(true);
let window = b.build()?;
#[cfg(target_os = "macos")]
let _ = window.set_visible_on_all_workspaces(true);
let handle = app.clone();
let me = label.to_string();
window.on_window_event(move |event| match event {
tauri::WindowEvent::Focused(false) => {
let handle = handle.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(160));
close_transient_unless_focused(&handle);
});
}
tauri::WindowEvent::Moved(pos) => {
let pinned = book(&handle, |b| match b.panels.get_mut(&me) {
Some(p) if p.shown => {
p.pos = Some((pos.x as f64, pos.y as f64));
p.pinned
}
_ => false,
});
if pinned {
// a drag sends many moves: save once they stop
let n = state(&handle).moves.fetch_add(1, Ordering::Relaxed) + 1;
let handle = handle.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(400));
if state(&handle).moves.load(Ordering::Relaxed) == n {
save_pins(&handle);
}
});
}
}
_ => {}
});
Ok(window)
}
/// Focus left a menu window: every transient panel closes unless one of them has focus now.
fn close_transient_unless_focused(app: &AppHandle) {
let transient = book(app, |b| b.transient());
if transient.iter().any(|l| app.get_webview_window(l).and_then(|w| w.is_focused().ok()).unwrap_or(false)) {
return;
}
book(app, |b| {
for l in &transient {
b.panels.remove(l);
}
});
destroy(app, &transient);
}
/// The panels cannot be shown: the native menu goes on the tray and opens once now.
fn native_popup(app: &AppHandle) {
if !state(app).native.swap(true, Ordering::Relaxed) {
crate::logs::host("warn", "tray menu panels unavailable: the native menu is used");
}
set_native(app);
let handle = app.clone();
let _ = app.run_on_main_thread(move || {
if let (Some(w), Ok(menu)) = (handle.get_webview_window(crate::policy::MAIN), crate::tray::native_menu(&handle, &nodes(&handle))) {
let _ = w.popup_menu(&menu);
}
});
}
/// A right click on the tray icon: a fresh root menu next to the icon (`anchor`: Anchor::Tray, physical px).
pub fn open_root(app: &AppHandle, anchor: Anchor) {
if native_fallback(app) {
return; // the native menu is on the tray and opens by itself
}
let (label, closes) = book(app, |b| b.open_root(anchor));
destroy(app, &closes);
let handle = app.clone();
std::thread::spawn(move || {
if let Err(e) = build_window(&handle, &label) {
crate::logs::host("warn", &format!("tray menu panel not built: {e}"));
book(&handle, |b| b.panels.remove(&label));
native_popup(&handle);
return;
}
std::thread::sleep(Duration::from_millis(2500));
if book(&handle, |b| b.panels.get(&label).map(|p| p.shown)) == Some(false) {
crate::logs::host("warn", "tray menu panel never reported ready");
let closes = book(&handle, |b| b.close(&label));
destroy(&handle, &closes);
native_popup(&handle);
}
});
}
/// Brings back the pinned panels of the last session (state.json `menuPins`).
pub fn restore(app: &AppHandle) {
let pins = app.try_state::<crate::commands::AppState>().and_then(|s| s.saved.lock().ok().map(|st| st.menu_pins.clone())).unwrap_or_default();
if pins.is_empty() || native_fallback(app) {
return;
}
let labels = book(app, |b| b.restore(&pins));
let handle = app.clone();
std::thread::spawn(move || {
for l in labels {
if build_window(&handle, &l).is_err() {
book(&handle, |b| b.panels.remove(&l));
}
}
});
}
fn work_area(app: &AppHandle, x: f64, y: f64) -> Option<Rect> {
let m = app.monitor_from_point(x, y).ok().flatten().or_else(|| app.primary_monitor().ok().flatten())?;
let w = m.work_area();
Some((w.position.x as f64, w.position.y as f64, w.size.width as f64, w.size.height as f64))
}
fn anchor_point(a: Anchor) -> (f64, f64) {
match a {
Anchor::Point { x, y } | Anchor::At { x, y } => (x, y),
Anchor::Tray { x, y, w, h } => (x + w / 2.0, y + h / 2.0),
Anchor::Beside { right, top, .. } => (right, top),
}
}
fn outer_rect(w: &WebviewWindow) -> Option<Rect> {
let p = w.outer_position().ok()?;
let s = w.outer_size().ok()?;
Some((p.x as f64, p.y as f64, s.width as f64, s.height as f64))
}
fn pinned_rects(app: &AppHandle, skip: &str) -> Vec<Rect> {
let labels: Vec<String> = book(app, |b| b.panels.iter().filter(|(l, p)| p.pinned && l.as_str() != skip).map(|(l, _)| l.clone()).collect());
labels.iter().filter_map(|l| app.get_webview_window(l).and_then(|w| outer_rect(&w))).collect()
}
// ---- what the panel page calls (commands.rs checks the window first) ----
pub fn panel_state(window: &WebviewWindow) -> Option<PanelInfo> {
let app = window.app_handle();
let p = book(app, |b| b.panels.get(window.label()).cloned())?;
Some(PanelInfo { label: window.label().into(), path: p.path, pinned: p.pinned, has_parent: p.parent.is_some(), focus_first: p.focus, nodes: nodes(app) })
}
/// The panel measured itself (CSS px): size it, place it inside the work area, show it the first time.
pub fn ready(window: &WebviewWindow, width: f64, height: f64) {
let app = window.app_handle().clone();
let Some(panel) = book(&app, |b| b.panels.get(window.label()).cloned()) else { return };
let scale = window.scale_factor().unwrap_or(1.0);
let size = ((width.clamp(120.0, 600.0) * scale).ceil(), (height.clamp(40.0, 900.0) * scale).ceil());
let (ax, ay) = panel.pos.unwrap_or_else(|| anchor_point(panel.anchor));
let Some(work) = work_area(&app, ax, ay) else { return };
let (x, y) = if panel.shown {
let (x, y, _, _) = outer_rect(window).unwrap_or((ax, ay, 0.0, 0.0));
clamp_into(x, y, size.0, size.1, work)
} else if let Some((x, y)) = panel.pos {
clamp_into(x, y, size.0, size.1, work)
} else {
place_menu(panel.anchor, size, work)
};
let _ = window.set_size(PhysicalSize::new(size.0 as u32, size.1 as u32));
let _ = window.set_position(PhysicalPosition::new(x as i32, y as i32));
if !panel.shown {
book(&app, |b| {
if let Some(p) = b.panels.get_mut(window.label()) {
p.shown = true;
p.pos = Some((x, y));
}
});
let _ = window.show();
if panel.focus || (panel.parent.is_none() && !panel.pinned) {
let _ = window.set_focus();
}
if panel.pinned {
save_pins(&app);
}
}
}
/// Opens submenu `key` beside this panel at the row whose top is `top` (CSS px). `pinned`: torn off (Ctrl / middle
/// click), placed so it covers no other pinned panel.
pub fn open_sub(window: &WebviewWindow, key: &str, top: f64, focus: bool, pinned: bool) {
let app = window.app_handle().clone();
let Some((wx, wy, ww, _)) = outer_rect(window) else { return };
let scale = window.scale_factor().unwrap_or(1.0);
let anchor = Anchor::Beside { left: wx, right: wx + ww, top: wy + top.max(0.0) * scale };
let Some((label, closes)) = book(&app, |b| b.open_sub(window.label(), key, anchor, pinned)) else { return };
destroy(&app, &closes);
if pinned {
let others = pinned_rects(&app, &label);
if let Some(work) = work_area(&app, wx, wy) {
let est = (EST.0 * scale, EST.1 * scale);
let (x, y) = place_menu(anchor, est, work);
let spot = free_spot((x, y, est.0, est.1), &others, work);
book(&app, |b| {
if let Some(p) = b.panels.get_mut(&label) {
p.pos = Some(spot);
}
});
}
}
book(&app, |b| {
if let Some(p) = b.panels.get_mut(&label) {
p.focus = focus;
}
});
let handle = app.clone();
std::thread::spawn(move || {
if build_window(&handle, &label).is_err() {
book(&handle, |b| b.panels.remove(&label));
}
});
}
/// The pointer moved to a plain row: this panel's transient submenus close.
pub fn close_subs(window: &WebviewWindow) {
let app = window.app_handle().clone();
let closes = book(&app, |b| {
let d = b.descendants(window.label());
for l in &d {
b.panels.remove(l);
}
d
});
destroy(&app, &closes);
}
/// Closes this panel (Left / Esc in a submenu, X on a pinned one).
pub fn close(window: &WebviewWindow, refocus_parent: bool) {
let app = window.app_handle().clone();
let (closes, parent, was_pinned) = book(&app, |b| {
let p = b.panels.get(window.label()).cloned();
(b.close(window.label()), p.as_ref().and_then(|p| p.parent.clone()), p.is_some_and(|p| p.pinned))
});
if refocus_parent {
if let Some(w) = parent.and_then(|p| app.get_webview_window(&p)) {
let _ = w.set_focus();
let _ = app.emit_to(w.label(), PANEL_EVENT, "focus");
}
}
destroy(&app, &closes);
if was_pinned {
save_pins(&app);
}
}
/// Esc on the root menu: every transient panel closes.
pub fn dismiss(app: &AppHandle) {
let closes = book(app, |b| b.dismiss());
destroy(app, &closes);
}
/// Pin or unpin this panel. Pinning steps it aside from the other pinned panels.
pub fn pin(window: &WebviewWindow, on: bool) {
let app = window.app_handle().clone();
let label = window.label().to_string();
let closes = book(&app, |b| b.pin(&label, on));
destroy(&app, &closes);
if on {
let others = pinned_rects(&app, &label);
if let Some(me) = outer_rect(window) {
if let Some(work) = work_area(&app, me.0, me.1) {
let (x, y) = free_spot(me, &others, work);
if (x, y) != (me.0, me.1) {
let _ = window.set_position(PhysicalPosition::new(x as i32, y as i32));
}
book(&app, |b| {
if let Some(p) = b.panels.get_mut(&label) {
p.pos = Some((x, y));
}
});
}
}
}
let _ = app.emit_to(label.as_str(), PANEL_EVENT, if on { "pinned" } else { "unpinned" });
save_pins(&app);
}
/// A pick: the same action as the native menu. Transient panels close; pinned ones stay and update in place.
pub fn select(window: &WebviewWindow, id: String) {
let app = window.app_handle().clone();
let pinned = book(&app, |b| b.panels.get(window.label()).map(|p| p.pinned).unwrap_or(false));
if !pinned {
dismiss(&app);
}
let handle = app.clone();
let _ = app.run_on_main_thread(move || crate::dispatch_menu(&handle, &id));
}
}
#[cfg(desktop)]
pub use runtime::*;

View file

@ -43,6 +43,30 @@ pub fn require_main(label: &str, url: &Url, dev: bool) -> Result<(), String> {
Ok(()) Ok(())
} }
/// The tray card window (card.rs): it may call only the card commands (`card_get`, `card_action`).
pub const CARD: &str = "card";
pub fn require_card(label: &str, url: &Url, dev: bool) -> Result<(), String> {
if label != CARD {
return Err(format!("not allowed from window '{label}'"));
}
if !is_local_origin(url, dev) {
return Err("not allowed from this page".into());
}
Ok(())
}
/// The tray menu panels (`menu-1`, `menu-2`... menu_panel.rs): they may call only the menu commands.
pub fn require_menu(label: &str, url: &Url, dev: bool) -> Result<(), String> {
if !crate::menu_panel::is_menu_label(label) {
return Err(format!("not allowed from window '{label}'"));
}
if !is_local_origin(url, dev) {
return Err("not allowed from this page".into());
}
Ok(())
}
/// Method kinds the sidecar announces in its `session.hello` descriptors. /// Method kinds the sidecar announces in its `session.hello` descriptors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind { pub enum Kind {

View file

@ -45,11 +45,14 @@ pub struct State {
pub overrides: Overrides, pub overrides: Overrides,
#[serde(default)] #[serde(default)]
pub settings: Settings, pub settings: Settings,
/// Pinned tray menu panels and where they sit (menu_panel.rs); restored at start.
#[serde(default, rename = "menuPins", skip_serializing_if = "Vec::is_empty")]
pub menu_pins: Vec<crate::menu_panel::PinRecord>,
} }
impl Default for State { impl Default for State {
fn default() -> State { fn default() -> State {
State { version: VERSION, projects: vec![], accounts: vec![], studios: vec![], overrides: Overrides::default(), settings: Settings::default() } State { version: VERSION, projects: vec![], accounts: vec![], studios: vec![], overrides: Overrides::default(), settings: Settings::default(), menu_pins: vec![] }
} }
} }
@ -121,6 +124,7 @@ pub fn migrate(mut v: Value) -> (State, u32, Vec<String>) {
studios: list(&o, "studios", &mut notes), studios: list(&o, "studios", &mut notes),
overrides: one(&o, "overrides", &mut notes), overrides: one(&o, "overrides", &mut notes),
settings: one(&o, "settings", &mut notes), settings: one(&o, "settings", &mut notes),
menu_pins: list(&o, "menuPins", &mut notes),
}; };
// two entries with one id (hand-edited or merged files): the first one wins // two entries with one id (hand-edited or merged files): the first one wins
let mut seen = std::collections::HashSet::new(); let mut seen = std::collections::HashSet::new();

View file

@ -1,7 +1,7 @@
//! The tray: tooltip, attention icon, context menu and the "where to go" memory of the last notification. //! The tray: tooltip, attention icon, context menu and the "where to go" memory of the last notification.
//! //!
//! The window pushes a small summary after every store read (`tray_update`); this module turns it into a menu model //! The window pushes a small summary after every store read (`tray_update`); this module turns it into a menu model
//! (pure, tested in tests/tray.rs), rebuilds the menu, sets the tooltip and swaps the icon for one with a red dot while //! (pure, tested in tests/tray.rs), pushes it to the menu panels (menu_panel.rs), sets the tooltip and swaps the icon for one with a red dot while
//! something needs the owner. Menu clicks come back as events to the window: `tray-route` (a route as JSON) and //! something needs the owner. Menu clicks come back as events to the window: `tray-route` (a route as JSON) and
//! `tray-action` (`read`, `mute-toggle`). //! `tray-action` (`read`, `mute-toggle`).
//! //!
@ -14,7 +14,9 @@ use std::time::{Duration, Instant};
use serde::Deserialize; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
use tauri::image::Image; use tauri::image::Image;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu}; use tauri::menu::{IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
use crate::menu_panel::{from_entries, Node};
use tauri::{AppHandle, Runtime}; use tauri::{AppHandle, Runtime};
pub const ID_OPEN: &str = "tray-open"; pub const ID_OPEN: &str = "tray-open";
@ -88,7 +90,8 @@ pub struct TraySummary {
pub enum Entry { pub enum Entry {
Item { id: String, label: String, enabled: bool }, Item { id: String, label: String, enabled: bool },
Separator, Separator,
Sub { label: String, items: Vec<Entry> }, /// `key`: the submenu's fixed key (menu_panel::sub_key), the same in every language.
Sub { key: String, label: String, items: Vec<Entry> },
} }
fn clean(s: &str, max: usize) -> String { fn clean(s: &str, max: usize) -> String {
@ -132,7 +135,7 @@ pub fn menu_model(s: &TraySummary) -> Vec<Entry> {
item(ID_OPEN, &l.open), item(ID_OPEN, &l.open),
item(ID_READ, &l.read_now), item(ID_READ, &l.read_now),
Entry::Separator, Entry::Separator,
Entry::Sub { label: clean(&l.apps, 40), items: apps }, Entry::Sub { key: "apps".into(), label: clean(&l.apps, 40), items: apps },
Entry::Separator, Entry::Separator,
item(ID_MUTE, if s.muted { &l.unmute } else { &l.mute }), item(ID_MUTE, if s.muted { &l.unmute } else { &l.mute }),
item(ID_UPDATE, &l.update), item(ID_UPDATE, &l.update),
@ -233,40 +236,45 @@ pub fn take_pending() -> Option<String> {
static LAST: Mutex<Option<String>> = Mutex::new(None); static LAST: Mutex<Option<String>> = Mutex::new(None);
fn build_menu<R: Runtime>(app: &AppHandle<R>, model: &[Entry]) -> tauri::Result<Menu<R>> { /// The native menu items for a panel tree (the fallback, and Linux), nested to any depth.
let menu = Menu::new(app)?; fn native_items<R: Runtime>(app: &AppHandle<R>, nodes: &[Node]) -> tauri::Result<Vec<Box<dyn IsMenuItem<R>>>> {
for e in model { let mut out: Vec<Box<dyn IsMenuItem<R>>> = Vec::new();
match e { for n in nodes {
Entry::Item { id, label, enabled } => menu.append(&MenuItem::with_id(app, id, label, *enabled, None::<&str>)?)?, match n {
Entry::Separator => menu.append(&PredefinedMenuItem::separator(app)?)?, Node::Item { id, label, enabled } => out.push(Box::new(MenuItem::with_id(app, id, label, *enabled, None::<&str>)?)),
Entry::Sub { label, items } => { Node::Sep => out.push(Box::new(PredefinedMenuItem::separator(app)?)),
let sub = Submenu::new(app, label, true)?; Node::Sub { label, items, .. } => {
for it in items { let children = native_items(app, items)?;
if let Entry::Item { id, label, enabled } = it { let refs: Vec<&dyn IsMenuItem<R>> = children.iter().map(|b| b.as_ref()).collect();
sub.append(&MenuItem::with_id(app, id, label, *enabled, None::<&str>)?)?; out.push(Box::new(Submenu::with_items(app, label, true, &refs)?));
}
}
menu.append(&sub)?;
} }
} }
} }
Ok(menu) Ok(out)
} }
/// The menu shown before the window has sent anything (English words). /// The native tray menu, rendered from the same tree as the panels.
pub fn initial_menu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Menu<R>> { pub fn native_menu<R: Runtime>(app: &AppHandle<R>, nodes: &[Node]) -> tauri::Result<Menu<R>> {
build_menu(app, &menu_model(&TraySummary::default())) let items = native_items(app, nodes)?;
let refs: Vec<&dyn IsMenuItem<R>> = items.iter().map(|b| b.as_ref()).collect();
Menu::with_items(app, &refs)
} }
/// Applies a summary: tooltip, menu and icon of the tray with id `main`. Skips the work when nothing changed. /// The tree before the window has sent anything (English words).
pub fn apply<R: Runtime>(app: &AppHandle<R>, s: &TraySummary) -> tauri::Result<()> { pub fn initial_nodes() -> Vec<Node> {
from_entries(&menu_model(&TraySummary::default()))
}
/// Applies a summary: tooltip and icon of the tray with id `main`, and the menu tree, which goes live to the open menu
/// panels (and to the native menu when that is in use). Skips the work when nothing changed.
pub fn apply(app: &AppHandle, s: &TraySummary) -> tauri::Result<()> {
let Some(tray) = app.tray_by_id("main") else { return Ok(()) }; let Some(tray) = app.tray_by_id("main") else { return Ok(()) };
let key = format!("{s:?}"); let key = format!("{s:?}");
if LAST.lock().ok().is_some_and(|l| l.as_deref() == Some(key.as_str())) { if LAST.lock().ok().is_some_and(|l| l.as_deref() == Some(key.as_str())) {
return Ok(()); return Ok(());
} }
tray.set_tooltip(Some(tooltip_text(s)))?; tray.set_tooltip(Some(tooltip_text(s)))?;
tray.set_menu(Some(build_menu(app, &menu_model(s))?))?; crate::menu_panel::set_nodes(app, from_entries(&menu_model(s)));
if let Some(icon) = app.default_window_icon() { if let Some(icon) = app.default_window_icon() {
let img = if s.attention > 0 { Image::new_owned(with_attention_dot(icon.rgba(), icon.width(), icon.height()), icon.width(), icon.height()) } else { icon.clone() }; let img = if s.attention > 0 { Image::new_owned(with_attention_dot(icon.rgba(), icon.width(), icon.height()), icon.width(), icon.height()) } else { icon.clone() };
tray.set_icon(Some(img))?; tray.set_icon(Some(img))?;

View file

@ -1,22 +1,111 @@
//! Signed updates from storebound.dev. The updater plugin checks `latest.json` of the chosen channel, downloads the //! Signed updates from storebound.dev. The updater plugin checks `latest.json` of the chosen channel, downloads the
//! platform's bundle and refuses it unless its minisign signature matches the public key in tauri.conf.json (the //! platform's bundle and refuses it unless its minisign signature matches the public key in tauri.conf.json (the
//! private key never leaves the release machine, ~/.storebound-keys). Nothing installs without the owner's click in //! private key never leaves the release machine, ~/.storebound-keys). Nothing installs without the owner's click in
//! a native dialog (commands::update_install). Pure parts here so tests can pin them. //! a native dialog (commands::update_install), or by the background updater (lib.rs auto_update). Pure parts here so tests can pin them.
use std::sync::atomic::{AtomicBool, Ordering};
use url::Url; use url::Url;
/// Set when Settings > Updates switched the channel: the background updater checks on its next tick.
pub static KICK: AtomicBool = AtomicBool::new(false);
pub fn kick() {
KICK.store(true, Ordering::SeqCst);
}
pub fn take_kick() -> bool {
KICK.swap(false, Ordering::SeqCst)
}
/// `latest.json` of each channel (static files on storebound.dev, published by tools/desktop-release.ts). /// `latest.json` of each channel (static files on storebound.dev, published by tools/desktop-release.ts).
pub const STABLE: &str = "https://storebound.dev/desktop/latest.json"; pub const STABLE: &str = "https://storebound.dev/desktop/latest.json";
pub const BETA: &str = "https://storebound.dev/desktop/beta/latest.json"; pub const BETA: &str = "https://storebound.dev/desktop/beta/latest.json";
/// Every push to main (Forgejo ci `dev` job, signed on the VDS): `<next patch>-dev.<UTC yyyymmddHHMMSS>`.
pub const DEV: &str = "https://storebound.dev/desktop/dev/latest.json";
/// The channels Settings > Updates accepts (beta is kept for saved states; the window offers stable and dev).
pub const CHANNELS: &[&str] = &["stable", "dev", "beta"];
/// The endpoint of a channel (Settings > Updates); anything unknown is the stable channel. /// The endpoint of a channel (Settings > Updates); anything unknown is the stable channel.
pub fn endpoint(channel: &str) -> &'static str { pub fn endpoint(channel: &str) -> &'static str {
if channel == "beta" { match channel {
BETA "beta" => BETA,
} else { "dev" => DEV,
STABLE _ => STABLE,
} }
} }
/// How often the background updater asks the channel (plus once at start and right after a resume from sleep).
pub const CHECK_EVERY_SECS: u64 = 15 * 60;
/// The background loop's tick; a wall-clock jump of more than this plus a minute between two ticks is a resume.
pub const TICK_SECS: u64 = 5;
/// An install waits while the main window is visible and focused, at most this many checks in a row (so an app that
/// stays open still updates).
pub const MAX_DEFERS: u32 = 4;
/// A semver version as (major, minor, patch) and its prerelease identifiers; None when it is not one.
fn parse(v: &str) -> Option<([u64; 3], Vec<String>)> {
let v = v.trim().trim_start_matches('v');
let v = v.split('+').next()?;
let (core, pre) = match v.split_once('-') {
Some((c, p)) => (c, p.split('.').map(str::to_string).collect::<Vec<_>>()),
None => (v, Vec::new()),
};
let mut n = core.split('.').map(|x| x.parse::<u64>().ok());
let r = [n.next()??, n.next()??, n.next()??];
if n.next().is_some() || pre.iter().any(String::is_empty) {
return None;
}
Some((r, pre))
}
/// semver 2.0 precedence, a > b: a release is above its own prereleases (0.8.48 > 0.8.48-dev.20261023120000), numeric
/// identifiers compare as numbers and sort below alphanumeric ones, a longer prerelease is above its prefix.
pub fn newer(a: &str, b: &str) -> bool {
use std::cmp::Ordering::{Equal, Greater, Less};
let (Some((ac, ap)), Some((bc, bp))) = (parse(a), parse(b)) else { return false };
match ac.cmp(&bc) {
Greater => return true,
Less => return false,
Equal => {}
}
match (ap.is_empty(), bp.is_empty()) {
(true, true) | (false, true) => return false,
(true, false) => return true,
_ => {}
}
for (x, y) in ap.iter().zip(bp.iter()) {
let o = match (x.parse::<u64>(), y.parse::<u64>()) {
(Ok(i), Ok(j)) => i.cmp(&j),
(Ok(_), Err(_)) => Less,
(Err(_), Ok(_)) => Greater,
_ => x.cmp(y),
};
if o != Equal {
return o == Greater;
}
}
ap.len() > bp.len()
}
/// The no-downgrade rule: an update installs only when the channel's version is strictly newer than this build. A dev
/// install switched back to stable stays on its dev build until a stable release passes it.
pub fn should_install(current: &str, offered: &str) -> bool {
newer(offered, current)
}
/// The background updater defers an install while the owner works in the main window (visible and focused), at most
/// MAX_DEFERS checks in a row. A hidden window can report focus, so only a visible one counts.
pub fn defer_install(visible: bool, focused: bool, defers_so_far: u32) -> bool {
visible && focused && defers_so_far < MAX_DEFERS
}
/// Whether the background updater asks the channel now: the first tick, a kick (channel switched), a resume from sleep
/// (the wall clock moved much further than one tick), or CHECK_EVERY_SECS since the last check.
pub fn check_due(first: bool, kicked: bool, wall_gap_secs: u64, since_check_secs: u64) -> bool {
first || kicked || wall_gap_secs > TICK_SECS + 60 || since_check_secs >= CHECK_EVERY_SECS
}
/// Only storebound.dev over HTTPS, without port or user info, may serve updates. /// Only storebound.dev over HTTPS, without port or user info, may serve updates.
pub fn endpoint_allowed(url: &Url) -> bool { pub fn endpoint_allowed(url: &Url) -> bool {
url.scheme() == "https" && url.host_str() == Some("storebound.dev") && url.port().is_none() && url.username().is_empty() && url.password().is_none() && url.path().starts_with("/desktop/") url.scheme() == "https" && url.host_str() == Some("storebound.dev") && url.port().is_none() && url.username().is_empty() && url.password().is_none() && url.path().starts_with("/desktop/")

View file

@ -310,7 +310,7 @@ pub struct Settings {
pub refresh: RefreshSettings, pub refresh: RefreshSettings,
pub cache: CacheSettings, pub cache: CacheSettings,
pub notify: NotifySettings, pub notify: NotifySettings,
/// Update channel (placeholder until the updater ships): stable | beta. /// Update channel (Settings > Updates): stable | dev (beta kept for saved states). crate::updates::endpoint.
pub channel: String, pub channel: String,
} }
@ -360,8 +360,8 @@ pub fn check_settings(s: &Settings) -> Result<(), String> {
if !valid_hhmm(&s.notify.quiet_hours.from) || !valid_hhmm(&s.notify.quiet_hours.to) { if !valid_hhmm(&s.notify.quiet_hours.from) || !valid_hhmm(&s.notify.quiet_hours.to) {
return Err("quiet hours: times as HH:MM (00:00 to 23:59)".into()); return Err("quiet hours: times as HH:MM (00:00 to 23:59)".into());
} }
if !["stable", "beta"].contains(&s.channel.as_str()) { if !crate::updates::CHANNELS.contains(&s.channel.as_str()) {
return Err("channel: stable or beta".into()); return Err("channel: stable or dev".into());
} }
Ok(()) Ok(())
} }

View file

@ -2,7 +2,7 @@
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "storebound", "productName": "storebound",
"mainBinaryName": "storebound-desktop", "mainBinaryName": "storebound-desktop",
"version": "0.8.40", "version": "0.8.78",
"identifier": "dev.storebound.desktop", "identifier": "dev.storebound.desktop",
"build": { "build": {
"frontendDist": "../dist", "frontendDist": "../dist",
@ -50,7 +50,7 @@
"form-action": "'none'" "form-action": "'none'"
}, },
"freezePrototype": true, "freezePrototype": true,
"capabilities": ["main-window"] "capabilities": ["main-window", "card-window", "menu-window"]
} }
}, },
"bundle": { "bundle": {
@ -88,6 +88,7 @@
}, },
"updater": { "updater": {
"endpoints": ["https://storebound.dev/desktop/latest.json"], "endpoints": ["https://storebound.dev/desktop/latest.json"],
"windows": { "installMode": "quiet" },
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ0Rjc4QTc4RDlFRjM4MkEKUldRcU9PL1plSXIzUkJtb2x0L2Z4MTA4bTg5UU5FVW5kUlRGcnVjangwQ0JNb2VGYjcveGhydlcK" "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ0Rjc4QTc4RDlFRjM4MkEKUldRcU9PL1plSXIzUkJtb2x0L2Z4MTA4bTg5UU5FVW5kUlRGcnVjangwQ0JNb2VGYjcveGhydlcK"
} }
} }

View file

@ -3,6 +3,7 @@
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
#[cfg(unix)]
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use storebound_desktop::ai_fix::*; use storebound_desktop::ai_fix::*;

View file

@ -0,0 +1,77 @@
//! The tray card's placement next to the tray icon, always inside the monitor's work area.
use storebound_desktop::card::*;
const W: f64 = 360.0;
const H: f64 = 480.0;
fn r(x: f64, y: f64, w: f64, h: f64) -> Rect { Rect { x, y, w, h } }
fn inside(p: (f64, f64), work: Rect) {
assert!(p.0 >= work.x && p.0 + W <= work.x + work.w, "x {p:?} outside {work:?}");
assert!(p.1 >= work.y && p.1 + H <= work.y + work.h, "y {p:?} outside {work:?}");
}
#[test]
fn windows_bottom_taskbar_opens_above_the_icon() {
let work = r(0.0, 0.0, 1920.0, 1032.0);
let p = place(r(1700.0, 1040.0, 24.0, 32.0), work, W, H, 8.0);
assert_eq!(p, (1532.0, 1032.0 - H - 8.0));
inside(p, work);
}
#[test]
fn icon_in_the_corner_is_clamped_into_the_work_area() {
let work = r(0.0, 0.0, 1920.0, 1032.0);
let p = place(r(1900.0, 1040.0, 24.0, 32.0), work, W, H, 8.0);
assert_eq!(p.0, 1920.0 - W - 8.0);
inside(p, work);
}
#[test]
fn macos_menu_bar_opens_below_the_icon() {
let work = r(0.0, 25.0, 1440.0, 875.0);
let p = place(r(1200.0, 0.0, 22.0, 24.0), work, W, H, 8.0);
assert_eq!(p.1, 33.0);
inside(p, work);
}
#[test]
fn side_taskbars_open_beside_the_icon() {
let work = r(60.0, 0.0, 1860.0, 1080.0);
let left = place(r(10.0, 900.0, 40.0, 40.0), work, W, H, 8.0);
assert_eq!(left.0, 68.0);
inside(left, work);
let work = r(0.0, 0.0, 1860.0, 1080.0);
let right = place(r(1870.0, 100.0, 40.0, 40.0), work, W, H, 8.0);
assert_eq!(right.0, 1860.0 - W - 8.0);
inside(right, work);
}
#[test]
fn second_monitor_with_negative_origin() {
let work = r(-2560.0, 0.0, 2560.0, 1400.0);
let p = place(r(-200.0, 1410.0, 24.0, 30.0), work, W, H, 8.0);
inside(p, work);
}
#[test]
fn icon_inside_the_work_area_and_a_tiny_screen() {
let work = r(0.0, 0.0, 1920.0, 1080.0);
inside(place(r(900.0, 1000.0, 24.0, 24.0), work, W, H, 8.0), work);
inside(place(r(900.0, 20.0, 24.0, 24.0), work, W, H, 8.0), work);
// smaller than the card: top-left of the work area, no panic
let tiny = r(0.0, 0.0, 300.0, 300.0);
assert_eq!(place(r(100.0, 310.0, 20.0, 20.0), tiny, W, H, 8.0), (8.0, 8.0));
}
#[test]
fn actions_and_snapshots_are_checked() {
for a in ["hide", "open", "route", "refresh", "mute", "quit", "external", "ready"] {
assert!(valid_action(a));
}
assert!(!valid_action("sidecar_call"));
assert!(!set_snapshot(serde_json::json!([1, 2])));
assert!(!set_snapshot(serde_json::json!({ "x": "y".repeat(MAX_SNAPSHOT) })));
assert!(set_snapshot(serde_json::json!({ "busy": false })));
assert_eq!(snapshot().unwrap()["busy"], false);
}

View file

@ -41,10 +41,13 @@ fn updater_has_a_real_minisign_key_and_only_storebound_dev() {
assert_eq!(c["plugins"]["updater"]["endpoints"], serde_json::json!([updates::STABLE])); assert_eq!(c["plugins"]["updater"]["endpoints"], serde_json::json!([updates::STABLE]));
// updater bundles are signed by tools/desktop-release.ts on the release Mac, never by a CI runner // updater bundles are signed by tools/desktop-release.ts on the release Mac, never by a CI runner
assert_eq!(c["bundle"]["createUpdaterArtifacts"], false); assert_eq!(c["bundle"]["createUpdaterArtifacts"], false);
for ch in ["stable", "beta", "nightly", ""] { assert_eq!(c["plugins"]["updater"]["windows"]["installMode"], "quiet");
for ch in ["stable", "beta", "dev", "nightly", ""] {
assert!(updates::endpoint_allowed(&Url::parse(updates::endpoint(ch)).unwrap()), "{ch}"); assert!(updates::endpoint_allowed(&Url::parse(updates::endpoint(ch)).unwrap()), "{ch}");
} }
assert_eq!(updates::endpoint("beta"), updates::BETA); assert_eq!(updates::endpoint("beta"), updates::BETA);
assert_eq!(updates::endpoint("dev"), updates::DEV);
assert_eq!(updates::DEV, "https://storebound.dev/desktop/dev/latest.json");
assert_eq!(updates::endpoint("anything"), updates::STABLE); assert_eq!(updates::endpoint("anything"), updates::STABLE);
for bad in ["http://storebound.dev/desktop/latest.json", "https://storebound.dev:8443/desktop/latest.json", "https://evil.test/desktop/latest.json", "https://storebound.dev/latest.json"] { for bad in ["http://storebound.dev/desktop/latest.json", "https://storebound.dev:8443/desktop/latest.json", "https://evil.test/desktop/latest.json", "https://storebound.dev/latest.json"] {
assert!(!updates::endpoint_allowed(&Url::parse(bad).unwrap()), "{bad}"); assert!(!updates::endpoint_allowed(&Url::parse(bad).unwrap()), "{bad}");
@ -103,3 +106,49 @@ fn deep_links_to_folders_ask_before_adding() {
let body = &cmds[at..]; let body = &cmds[at..];
assert!(body.find("confirm_dialog_with(").unwrap() < body.find("download_and_install(").unwrap()); assert!(body.find("confirm_dialog_with(").unwrap() < body.find("download_and_install(").unwrap());
} }
#[test]
fn dev_versions_sort_and_never_downgrade() {
// a dev build of the next patch is above the current stable, below that next stable, and later stamps go up
assert!(updates::newer("0.8.48-dev.20261023120000", "0.8.47"));
assert!(updates::newer("0.8.48", "0.8.48-dev.20261023120000"));
assert!(updates::newer("0.8.48-dev.20261023120001", "0.8.48-dev.20261023120000"));
assert!(updates::newer("0.8.48-dev.20261024000000", "0.8.48-dev.9"), "numeric identifiers compare as numbers");
assert!(updates::newer("0.8.49-dev.1", "0.8.48"));
assert!(updates::newer("0.10.0", "0.9.9"));
assert!(!updates::newer("0.8.48", "0.8.48"));
assert!(!updates::newer("nonsense", "0.8.48"));
// switched from dev back to stable: stays on the dev build until a stable release passes it
assert!(!updates::should_install("0.8.48-dev.20261023120000", "0.8.47"));
assert!(updates::should_install("0.8.48-dev.20261023120000", "0.8.48"));
assert!(updates::should_install("0.8.47", "0.8.48-dev.20261023120000"));
assert!(!updates::should_install("0.8.48-dev.20261023120000", "0.8.48-dev.20261023120000"));
}
#[test]
fn background_updater_schedule_and_defer() {
assert!(updates::check_due(true, false, 0, 0), "at start");
assert!(updates::check_due(false, true, 0, 0), "channel switched");
assert!(updates::check_due(false, false, 3600, 5), "resume from sleep");
assert!(updates::check_due(false, false, 5, updates::CHECK_EVERY_SECS));
assert!(!updates::check_due(false, false, 5, 60));
assert_eq!(updates::CHECK_EVERY_SECS, 900);
assert!(updates::defer_install(true, true, 0));
assert!(!updates::defer_install(true, true, updates::MAX_DEFERS), "an open window still updates after a few checks");
assert!(!updates::defer_install(false, true, 0), "a hidden window can report focus");
assert!(!updates::defer_install(true, false, 0));
let _ = updates::take_kick();
updates::kick();
assert!(updates::take_kick());
assert!(!updates::take_kick());
}
#[test]
fn startup_apps_choice_is_read_from_startup_approved() {
use storebound_desktop::startup_approved_off;
assert!(!startup_approved_off(&[0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
assert!(!startup_approved_off(&[0x06, 0, 0, 0]));
assert!(startup_approved_off(&[0x03, 0, 0, 0, 0x20, 0xD1, 0xD3, 0xB1, 0xF0, 0xB3, 0xDC, 0x01]));
assert!(startup_approved_off(&[0x07]));
assert!(!startup_approved_off(&[]));
}

View file

@ -0,0 +1,214 @@
//! The tray menu panels' pure half: the tree and its stable keys, live updates, placement inside the work area, the
//! panel book (transient vs pinned, parents, restore after a restart).
use storebound_desktop::menu_panel::*;
use storebound_desktop::store::State;
use storebound_desktop::tray::{menu_model, Entry, TrayApp, TrayLabels, TraySummary};
const WORK: Rect = (0.0, 0.0, 1920.0, 1040.0);
const AT: Anchor = Anchor::At { x: 0.0, y: 0.0 };
fn summary(state: &str, apps_label: &str) -> TraySummary {
TraySummary {
apps: vec![TrayApp { key: "k1".into(), name: "First".into(), state: state.into() }, TrayApp { key: "k2".into(), name: "Second".into(), state: String::new() }],
labels: TrayLabels { apps: apps_label.into(), ..TrayLabels::default() },
..TraySummary::default()
}
}
fn tree() -> Vec<Node> {
from_entries(&[
Entry::Item { id: "open".into(), label: "Open".into(), enabled: true },
Entry::Separator,
Entry::Sub { key: String::new(), label: "Fleet".into(), items: vec![Entry::Sub { key: String::new(), label: "Recently lowered".into(), items: vec![] }] },
Entry::Sub { key: String::new(), label: "Profile: Work".into(), items: vec![] },
])
}
#[test]
fn keys_ignore_live_parts_and_stay_unique() {
assert_eq!(sub_key("Profile: Work"), "profile");
assert_eq!(sub_key("\u{25CF} First \u{00B7} ok"), "first");
assert_eq!(sub_key("Queue (1 running, 2 queued)"), "queue");
assert_eq!(sub_key("\u{2716}"), "sub");
let nodes = unique_keys(vec![Node::Sub { key: "a".into(), label: "A".into(), items: vec![] }, Node::Sub { key: "a".into(), label: "A".into(), items: vec![] }]);
assert!(matches!(&nodes[1], Node::Sub { key, .. } if key == "a-2"));
}
#[test]
fn find_walks_keys() {
let t = tree();
let (items, label) = find(&t, &["fleet".into(), "recently-lowered".into()]).unwrap();
assert_eq!((items.len(), label), (0, Some("Recently lowered")));
assert!(find(&t, &["nope".into()]).is_none());
assert_eq!(find(&t, &[]).unwrap().0.len(), 4);
}
#[test]
fn the_tray_tree_keeps_its_apps_key_in_every_language_and_value() {
let en = from_entries(&menu_model(&summary("App Store: In review", "Apps")));
let tr = from_entries(&menu_model(&summary("App Store: Live", "Uygulamalar")));
let key = |n: &[Node]| n.iter().find_map(|n| if let Node::Sub { key, .. } = n { Some(key.clone()) } else { None }).unwrap();
assert_eq!(key(&en), "apps");
assert_eq!(key(&tr), "apps");
// a live value changed: the tree differs (so it is pushed), the open Apps panel still resolves
assert_ne!(en, tr);
let (items, _) = find(&tr, &["apps".into()]).unwrap();
assert!(matches!(&items[0], Node::Item { id, label, .. } if id == "tray-app:k1" && label.contains("Live")));
// the same summary twice: the same tree (nothing is pushed)
assert_eq!(from_entries(&menu_model(&summary("x", "Apps"))), from_entries(&menu_model(&summary("x", "Apps"))));
}
#[test]
fn the_tree_serializes_as_the_panel_page_reads_it() {
let v = serde_json::to_value(tree()).unwrap();
assert_eq!(v[0], serde_json::json!({ "kind": "item", "id": "open", "label": "Open", "enabled": true }));
assert_eq!(v[1], serde_json::json!({ "kind": "sep" }));
assert_eq!(v[2]["kind"], "sub");
assert_eq!(v[2]["key"], "fleet");
}
#[test]
fn root_opens_away_from_the_taskbar_and_stays_inside() {
// bottom taskbar, icon at the right: above and left of the click
let (x, y) = place_menu(Anchor::Point { x: 1900.0, y: 1060.0 }, (300.0, 400.0), WORK);
assert!(x + 300.0 <= 1920.0 - GAP && y + 400.0 <= 1040.0 - GAP && x >= 0.0 && y >= 0.0);
// macOS menu bar at the top: below it
let (_, y) = place_menu(Anchor::Point { x: 1800.0, y: 0.0 }, (300.0, 400.0), (0.0, 25.0, 1920.0, 1055.0));
assert!(y >= 25.0 + GAP);
// a second monitor left of the primary (negative x)
let (x, _) = place_menu(Anchor::Point { x: -10.0, y: 500.0 }, (300.0, 400.0), (-1920.0, 0.0, 1920.0, 1080.0));
assert!(x + 300.0 <= -GAP + 0.001 && x >= -1920.0);
// a panel taller than the work area: pinned to the top edge, never above it
let (_, y) = place_menu(Anchor::Point { x: 100.0, y: 100.0 }, (300.0, 2000.0), WORK);
assert_eq!(y, GAP);
}
#[test]
fn tray_root_sits_just_above_the_icon_never_over_the_taskbar() {
// icon in a bottom taskbar (the icon is below the work area): bottom edge exactly GAP above the icon's top
let icon = Anchor::Tray { x: 1800.0, y: 1044.0, w: 32.0, h: 32.0 };
let (_, y) = place_menu(icon, (260.0, 300.0), WORK);
assert_eq!(y + 300.0, 1040.0 - GAP);
// even when the reported work area wrongly includes the taskbar, the panel stays above the icon
let (_, y) = place_menu(icon, (260.0, 300.0), (0.0, 0.0, 1920.0, 1080.0));
assert!(y + 300.0 <= 1044.0 - GAP);
}
#[test]
fn submenus_open_beside_and_flip_left_at_the_edge() {
let (x, _) = place_menu(Anchor::Beside { left: 1600.0, right: 1880.0, top: 100.0 }, (280.0, 200.0), WORK);
assert!(x + 280.0 <= 1602.0);
let (x, y) = place_menu(Anchor::Beside { left: 100.0, right: 380.0, top: 100.0 }, (280.0, 200.0), WORK);
assert!((378.0..=380.0).contains(&x) && (90.0..=100.0).contains(&y));
// a row near the bottom: the submenu moves up into the work area
let (_, y) = place_menu(Anchor::Beside { left: 100.0, right: 380.0, top: 1000.0 }, (280.0, 300.0), WORK);
assert!(y + 300.0 <= 1040.0 - GAP);
}
#[test]
fn pinned_panels_step_aside_and_stay_inside() {
let others = [(100.0, 100.0, 280.0, 300.0), (100.0, 408.0, 280.0, 300.0)];
let (x, y) = free_spot((120.0, 120.0, 280.0, 300.0), &others, WORK);
assert!(others.iter().all(|o| !overlaps((x, y, 280.0, 300.0), *o)));
assert!(x >= 0.0 && y >= 0.0 && x + 280.0 <= 1920.0 && y + 300.0 <= 1040.0);
// no room left below: the next column
let col = [(8.0, 8.0, 280.0, 1000.0)];
let (x, _) = free_spot((8.0, 8.0, 280.0, 300.0), &col, WORK);
assert!(x >= 288.0);
// nothing in the way: where it was
assert_eq!(free_spot((500.0, 500.0, 280.0, 300.0), &others, WORK), (500.0, 500.0));
}
#[test]
fn several_menus_open_and_pinned_ones_survive_a_new_menu() {
let mut b = Book::default();
let (root, _) = b.open_root(Anchor::Point { x: 0.0, y: 0.0 });
let (fleet, _) = b.open_sub(&root, "fleet", AT, false).unwrap();
assert!(b.open_sub(&root, "fleet", AT, false).is_none(), "the same submenu again is a no-op");
let (deep, _) = b.open_sub(&fleet, "recently-lowered", AT, false).unwrap();
assert_eq!(b.descendants(&root).len(), 2);
// pinning the Fleet panel detaches it; the root closes, its own child stays its own
let closes = b.pin(&fleet, true);
assert_eq!(closes, vec![root.clone()]);
assert!(b.panels[&fleet].pinned && b.panels[&fleet].parent.is_none());
assert_eq!(b.descendants(&fleet), vec![deep.clone()]);
let (root2, closes) = b.open_root(Anchor::Point { x: 0.0, y: 0.0 });
assert_eq!(closes, vec![deep]);
assert!(b.panels.contains_key(&fleet));
assert_eq!(b.transient(), vec![root2.clone()]);
// a pick / Esc: transient panels go, the pinned one stays
assert_eq!(b.dismiss(), vec![root2]);
assert_eq!(b.panels.len(), 1);
// unpinned, it behaves like a menu again and goes with the next one
b.pin(&fleet, false);
let (_, closes) = b.open_root(Anchor::Point { x: 0.0, y: 0.0 });
assert!(closes.contains(&fleet));
}
#[test]
fn a_torn_off_submenu_keeps_one_pinned_copy() {
let mut b = Book::default();
let (root, _) = b.open_root(Anchor::Point { x: 0.0, y: 0.0 });
let (p1, _) = b.open_sub(&root, "fleet", AT, true).unwrap();
let (p2, closes) = b.open_sub(&root, "fleet", AT, true).unwrap();
assert!(closes.contains(&p1) && b.panels[&p2].pinned && !b.panels.contains_key(&p1));
assert_eq!(b.panels[&p2].path, vec!["fleet".to_string()]);
// the root stays open (a tear-off is not a pick)
assert!(b.panels.contains_key(&root));
// closing a panel that is already gone does nothing
assert!(b.close("menu-99").is_empty());
}
#[test]
fn a_live_update_closes_nothing_that_still_exists() {
let mut b = Book::default();
let (root, _) = b.open_root(Anchor::Point { x: 0.0, y: 0.0 });
let (profile, _) = b.open_sub(&root, "profile", AT, true).unwrap();
let (fleet, _) = b.open_sub(&root, "fleet", AT, false).unwrap();
assert!(b.prune(&tree()).is_empty());
// the Fleet submenu is gone from the tree: its transient panel closes, the pinned Profile panel stays even when its
// submenu goes too (it shows that it is gone)
let smaller = from_entries(&[Entry::Item { id: "open".into(), label: "Open".into(), enabled: true }]);
assert_eq!(b.prune(&smaller), vec![fleet]);
assert!(b.panels.contains_key(&root) && b.panels.contains_key(&profile));
}
#[test]
fn pins_are_saved_in_the_state_and_restored_after_a_restart() {
let mut b = Book::default();
let (root, _) = b.open_root(Anchor::Point { x: 0.0, y: 0.0 });
let (p, _) = b.open_sub(&root, "apps", AT, true).unwrap();
// not placed yet: nothing to save
assert!(b.pins().is_empty());
b.panels.get_mut(&p).unwrap().pos = Some((40.4, 50.6));
let pins = b.pins();
assert_eq!(pins, vec![PinRecord { path: vec!["apps".into()], x: 40, y: 51 }]);
// through state.json
let st = State { menu_pins: pins.clone(), ..State::default() };
let text = serde_json::to_string(&st).unwrap();
assert!(text.contains("\"menuPins\""));
let back: State = serde_json::from_str(&text).unwrap();
assert_eq!(back.menu_pins, pins);
// an empty list is not written at all (older files stay as they were)
assert!(!serde_json::to_string(&State::default()).unwrap().contains("menuPins"));
let mut fresh = Book::default();
let mut saved = back.menu_pins.clone();
saved.push(saved[0].clone()); // a duplicate is dropped
let labels = fresh.restore(&saved);
assert_eq!(labels.len(), 1);
let r = &fresh.panels[&labels[0]];
assert!(r.pinned && r.path == vec!["apps".to_string()] && r.pos == Some((40.0, 51.0)) && r.parent.is_none());
// a restored pin survives the next menu
let (_, closes) = fresh.open_root(Anchor::Point { x: 0.0, y: 0.0 });
assert!(closes.is_empty());
let many: Vec<PinRecord> = (0..40).map(|i| PinRecord { path: vec![format!("s{i}")], x: 0, y: 0 }).collect();
assert_eq!(Book::default().restore(&many).len(), MAX_PINS);
}
#[test]
fn panel_labels_are_menu_and_a_number() {
assert!(is_menu_label("menu-1") && is_menu_label("menu-204"));
for bad in ["menu-", "menu-a", "card", "main", "menu-1-2", "xmenu-1"] {
assert!(!is_menu_label(bad), "{bad}");
}
}

View file

@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
use serde_json::{json, Value}; use serde_json::{json, Value};
use storebound_desktop::policy::*; use storebound_desktop::policy::*;
use storebound_desktop::COMMANDS; use storebound_desktop::{CARD_COMMANDS, COMMANDS, MENU_COMMANDS};
use url::Url; use url::Url;
fn root() -> PathBuf { fn root() -> PathBuf {
@ -24,9 +24,10 @@ fn u(s: &str) -> Url {
#[test] #[test]
fn one_capability_for_the_main_window_with_exactly_the_app_commands() { fn one_capability_for_the_main_window_with_exactly_the_app_commands() {
let dir = root().join("capabilities"); let dir = root().join("capabilities");
let files: Vec<PathBuf> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).collect(); let mut files: Vec<PathBuf> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).collect();
assert_eq!(files.len(), 1, "one capability file expected, found {files:?}"); files.sort();
let cap = read_json(&files[0]); assert_eq!(files.len(), 3, "main, card and menu capability files expected, found {files:?}");
let cap = read_json(&dir.join("main.json"));
assert_eq!(cap["identifier"], "main-window"); assert_eq!(cap["identifier"], "main-window");
assert_eq!(cap["windows"], json!(["main"])); assert_eq!(cap["windows"], json!(["main"]));
assert!(cap.get("webviews").is_none(), "no webview-scoped grants"); assert!(cap.get("webviews").is_none(), "no webview-scoped grants");
@ -46,6 +47,69 @@ fn one_capability_for_the_main_window_with_exactly_the_app_commands() {
} }
} }
#[test]
fn the_card_window_gets_only_the_card_commands() {
let cap = read_json(&root().join("capabilities/card.json"));
assert_eq!(cap["identifier"], "card-window");
assert_eq!(cap["windows"], json!(["card"]));
assert!(cap.get("webviews").is_none() && cap.get("remote").is_none());
assert_ne!(cap["local"], json!(false));
let got: BTreeSet<String> = cap["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_string()).collect();
let mut want: BTreeSet<String> = CARD_COMMANDS.iter().map(|c| format!("allow-{}", c.replace('_', "-"))).collect();
want.insert("core:event:allow-listen".into());
want.insert("core:event:allow-unlisten".into());
assert_eq!(got, want);
let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap();
for c in CARD_COMMANDS {
let at = cmds.find(&format!("pub fn {c}(")).unwrap_or_else(|| panic!("{c} not in commands.rs"));
let body = &cmds[at..];
let open = body.find('{').unwrap();
assert!(body[open + 1..].trim_start().starts_with("guard_card(&window)?;"), "{c} must start with guard_card(&window)?");
}
assert!(require_card("card", &u("tauri://localhost/card.html"), false).is_ok());
assert!(require_card("main", &u("tauri://localhost/"), false).is_err());
assert!(require_main("card", &u("tauri://localhost/card.html"), false).is_err());
}
#[test]
fn the_menu_panels_get_only_the_menu_commands() {
let cap = read_json(&root().join("capabilities/menu.json"));
assert_eq!(cap["identifier"], "menu-window");
assert_eq!(cap["windows"], json!(["menu-*"]));
assert!(cap.get("webviews").is_none() && cap.get("remote").is_none());
assert_ne!(cap["local"], json!(false));
let got: BTreeSet<String> = cap["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_string()).collect();
let mut want: BTreeSet<String> = MENU_COMMANDS.iter().map(|c| format!("allow-{}", c.replace('_', "-"))).collect();
want.insert("core:event:allow-listen".into());
want.insert("core:event:allow-unlisten".into());
// a pinned panel is dragged by its header (data-tauri-drag-region): only its own window
want.insert("core:window:allow-start-dragging".into());
assert_eq!(got, want);
// the menu commands never leak into the main or card capability
for other in ["main.json", "card.json"] {
let cap = read_json(&root().join("capabilities").join(other));
let perms = cap["permissions"].to_string();
for c in MENU_COMMANDS {
assert!(!perms.contains(&format!("\"allow-{}\"", c.replace('_', "-"))), "{c} granted in {other}");
}
}
let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap();
for c in MENU_COMMANDS {
let at = cmds.find(&format!("pub fn {c}(")).unwrap_or_else(|| panic!("{c} not in commands.rs"));
let body = &cmds[at..];
let open = body.find('{').unwrap();
assert!(body[open + 1..].trim_start().starts_with("guard_menu(&window)?;"), "{c} must start with guard_menu(&window)?");
}
assert!(require_menu("menu-1", &u("tauri://localhost/tray-menu.html"), false).is_ok());
assert!(require_menu("menu-12", &u("http://tauri.localhost/tray-menu.html"), false).is_ok());
for bad in ["main", "card", "menu-", "menu-x", "menu-1a", "menus-1"] {
assert!(require_menu(bad, &u("tauri://localhost/tray-menu.html"), false).is_err(), "{bad}");
}
assert!(require_menu("menu-1", &u("https://example.com/tray-menu.html"), false).is_err());
assert!(require_main("menu-1", &u("tauri://localhost/tray-menu.html"), false).is_err());
assert!(require_card("menu-1", &u("tauri://localhost/tray-menu.html"), false).is_err());
}
#[test] #[test]
fn every_registered_command_is_in_the_list_and_nothing_else() { fn every_registered_command_is_in_the_list_and_nothing_else() {
let lib = fs::read_to_string(root().join("src/lib.rs")).unwrap(); let lib = fs::read_to_string(root().join("src/lib.rs")).unwrap();
@ -56,7 +120,7 @@ fn every_registered_command_is_in_the_list_and_nothing_else() {
.map(|s| s.trim().trim_start_matches("commands::").to_string()) .map(|s| s.trim().trim_start_matches("commands::").to_string())
.filter(|s| !s.is_empty()) .filter(|s| !s.is_empty())
.collect(); .collect();
assert_eq!(registered, COMMANDS.iter().map(|s| s.to_string()).collect::<Vec<_>>()); assert_eq!(registered, COMMANDS.iter().chain(CARD_COMMANDS).chain(MENU_COMMANDS).map(|s| s.to_string()).collect::<Vec<_>>());
// every command checks the caller first // every command checks the caller first
let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap(); let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap();
for c in COMMANDS { for c in COMMANDS {
@ -84,7 +148,7 @@ fn csp_is_strict_and_the_config_has_no_backdoors() {
assert!(!v.contains("unsafe-eval") && !v.contains("unsafe-inline") && !v.contains('*'), "{k}: {v}"); assert!(!v.contains("unsafe-eval") && !v.contains("unsafe-inline") && !v.contains('*'), "{k}: {v}");
assert!(!v.contains("https:") && !v.contains("http://") || v == "ipc: http://ipc.localhost", "{k}: no remote sources: {v}"); assert!(!v.contains("https:") && !v.contains("http://") || v == "ipc: http://ipc.localhost", "{k}: no remote sources: {v}");
} }
assert_eq!(conf["app"]["security"]["capabilities"], json!(["main-window"])); assert_eq!(conf["app"]["security"]["capabilities"], json!(["main-window", "card-window", "menu-window"]));
assert_eq!(conf["app"]["security"]["freezePrototype"], json!(true)); assert_eq!(conf["app"]["security"]["freezePrototype"], json!(true));
assert!(conf["app"].get("withGlobalTauri").is_none() || conf["app"]["withGlobalTauri"] == json!(false)); assert!(conf["app"].get("withGlobalTauri").is_none() || conf["app"]["withGlobalTauri"] == json!(false));
let windows = conf["app"]["windows"].as_array().unwrap(); let windows = conf["app"]["windows"].as_array().unwrap();

View file

@ -23,7 +23,7 @@ fn ids(m: &[Entry]) -> Vec<String> {
fn menu_has_every_entry_in_order() { fn menu_has_every_entry_in_order() {
let m = menu_model(&summary()); let m = menu_model(&summary());
assert_eq!(ids(&m), vec![ID_OPEN, ID_READ, ID_MUTE, ID_UPDATE, ID_SETTINGS, ID_QUIT]); assert_eq!(ids(&m), vec![ID_OPEN, ID_READ, ID_MUTE, ID_UPDATE, ID_SETTINGS, ID_QUIT]);
let Entry::Sub { label, items } = &m[3] else { panic!("the Apps submenu comes after the first separator") }; let Entry::Sub { label, items, .. } = &m[3] else { panic!("the Apps submenu comes after the first separator") };
assert_eq!(label, "Apps"); assert_eq!(label, "Apps");
assert_eq!(items.len(), 2); assert_eq!(items.len(), 2);
let Entry::Item { id, label, enabled } = &items[0] else { panic!() }; let Entry::Item { id, label, enabled } = &items[0] else { panic!() };
@ -90,7 +90,7 @@ fn only_known_small_routes_are_remembered() {
#[test] #[test]
fn attention_dot_changes_only_the_corner() { fn attention_dot_changes_only_the_corner() {
let (w, h) = (32u32, 32u32); let (w, h) = (32u32, 32u32);
let base: Vec<u8> = std::iter::repeat([10u8, 20, 30, 255]).take((w * h) as usize).flatten().collect(); let base: Vec<u8> = std::iter::repeat_n([10u8, 20, 30, 255], (w * h) as usize).flatten().collect();
let out = with_attention_dot(&base, w, h); let out = with_attention_dot(&base, w, h);
assert_eq!(out.len(), base.len()); assert_eq!(out.len(), base.len());
let at = |v: &[u8], x: u32, y: u32| -> [u8; 4] { let i = ((y * w + x) * 4) as usize; [v[i], v[i + 1], v[i + 2], v[i + 3]] }; let at = |v: &[u8], x: u32, y: u32| -> [u8; 4] { let i = ((y * w + x) * 4) as usize; [v[i], v[i + 1], v[i + 2], v[i + 3]] };

View file

@ -1,4 +1,5 @@
// Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh), // Shell: sidebar (apps grouped by what they need: attention, in progress, live, not on a store yet; one status line
// each; a studio filter; the workspace as a compact footer row), top bar (breadcrumbs, last read, refresh),
// the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. // the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide.
import { DryRunPreview } from './ui/DryRunPreview'; import { DryRunPreview } from './ui/DryRunPreview';
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
@ -6,8 +7,8 @@ import { FIXTURES, onDeepLink, onDeepLinkFolder, onTrayRoute } from './api';
import { devSwitch } from './dev/switches'; import { devSwitch } from './dev/switches';
import { type Key, t } from './i18n'; import { type Key, t } from './i18n';
import { ago, num } from './lib/format'; import { ago, num } from './lib/format';
import { groupByStudio, type UnifiedApp } from './lib/identity'; import type { UnifiedApp } from './lib/identity';
import { NavCtx, parseRouteJson, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav'; import { NavCtx, parseRouteJson, parseStart, type Route, sameRoute, SECTION_ICON, SECTION_KEY, sectionOf, sectionsFor, subsOf, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav';
import { usePrefs } from './prefs-ctx'; import { usePrefs } from './prefs-ctx';
import { Accounts } from './screens/Accounts'; import { Accounts } from './screens/Accounts';
import { AppFolders } from './screens/AppFolders'; import { AppFolders } from './screens/AppFolders';
@ -18,7 +19,7 @@ import { useShowIgnored } from './lib/show-ignored';
import { Onboarding } from './screens/Onboarding'; import { Onboarding } from './screens/Onboarding';
import { Portfolio } from './screens/Portfolio'; import { Portfolio } from './screens/Portfolio';
import { Settings } from './screens/Settings'; import { Settings } from './screens/Settings';
import { useData } from './store'; import { useData, useReadState } from './store';
import { Icon, type IconName, Mark } from './ui/icons'; import { Icon, type IconName, Mark } from './ui/icons';
import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit'; import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit';
import { type Command, Palette } from './ui/Palette'; import { type Command, Palette } from './ui/Palette';
@ -28,16 +29,18 @@ import { Toasts } from './ui/Toasts';
import { useContextMenu } from './ui/ContextMenu'; import { useContextMenu } from './ui/ContextMenu';
import { appMenu } from './ui/app-menu'; import { appMenu } from './ui/app-menu';
import { isEditable, isItem, type MenuInput } from './ui/menu-logic'; import { isEditable, isItem, type MenuInput } from './ui/menu-logic';
import { worstTone } from './ui/ds'; import { attention, isGameSummary, SIDE_GROUPS, type SideGroup, sideStatus } from './lib/model';
import { attention } from './lib/model';
const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' }; const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' };
export const WS_KEY: Record<WorkspaceScreen, Key> = { apps: 'nav.apps', accounts: 'nav.accounts', ignored: 'nav.ignored', dependencies: 'nav.dependencies', settings: 'nav.settings' }; export const WS_KEY: Record<WorkspaceScreen, Key> = { apps: 'nav.apps', accounts: 'nav.accounts', ignored: 'nav.ignored', dependencies: 'nav.dependencies', settings: 'nav.settings' };
const SIDE_KEY = 'storebound.side.v1'; const SIDE_KEY = 'storebound.side.v1';
const STUDIO_KEY = 'storebound.side.studio.v1';
function loadCollapsed(): string[] { function loadCollapsed(): string[] {
try { const v = JSON.parse(localStorage.getItem(SIDE_KEY) ?? '[]') as unknown; return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; } try { const v = JSON.parse(localStorage.getItem(SIDE_KEY) ?? '[]') as unknown; return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; }
} }
function loadStudio(): string | null { try { return localStorage.getItem(STUDIO_KEY); } catch { return null; } }
const GROUP_KEY: Record<SideGroup | 'ignored', Key> = { attention: 'side.gAttention', progress: 'side.gProgress', live: 'side.gLive', draft: 'side.gDraft', ignored: 'nav.ignored' };
export function App({ onTheme }: { onTheme: () => void }) { export function App({ onTheme }: { onTheme: () => void }) {
const d = useData(); const d = useData();
@ -47,23 +50,38 @@ export function App({ onTheme }: { onTheme: () => void }) {
const [welcome, setWelcome] = useState(false); const [welcome, setWelcome] = useState(false);
const [started, setStarted] = useState(false); const [started, setStarted] = useState(false);
const [collapsed, setCollapsed] = useState<string[]>(loadCollapsed); const [collapsed, setCollapsed] = useState<string[]>(loadCollapsed);
const [studioFilter, setStudioFilterState] = useState<string | null>(loadStudio);
const setStudioFilter = (v: string | null) => { setStudioFilterState(v); try { if (v) localStorage.setItem(STUDIO_KEY, v); else localStorage.removeItem(STUDIO_KEY); } catch { /* private mode */ } };
const exports = useExportItems(); const exports = useExportItems();
const runExport = useRunExport(); const runExport = useRunExport();
const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []); const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []);
const visible = useMemo(() => d.apps.filter(a => !a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]); const visible = useMemo(() => d.apps.filter(a => !a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]);
// Refresh all is busy while any read it covers is in flight (its own pass, a card's refresh, Check again, auto-read)
const allReads = useReadState({ tags: ['all'] });
const [showIgnored, setShowIgnored] = useShowIgnored(); const [showIgnored, setShowIgnored] = useShowIgnored();
const ignoredApps = useMemo(() => d.apps.filter(a => a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]); const ignoredApps = useMemo(() => d.apps.filter(a => a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]);
const listed = showIgnored ? [...visible, ...ignoredApps] : visible; const gameOf = useCallback((a: UnifiedApp) => isGameSummary(d.statusFor(a)?.summary), [d]);
const groups = d.studios.length ? groupByStudio(listed.map(a => ({ app: a })), d.studios) : [{ studio: null as string | null, rows: listed.map(a => ({ app: a })) }]; const tabsOf = useCallback((a: UnifiedApp) => tabsFor(!!a.project, gameOf(a)), [gameOf]);
// Alt+Up / Alt+Down: the previous / next app in sidebar order (keeps the tab when the other app has it) // the sidebar: apps by what they need (attention, in progress, live, not on a store yet), one status line each
const sideOrder = groups.flatMap(x => x.rows.map(r => r.app)); const studioOn = studioFilter && (studioFilter === 'none' || d.studios.some(s => s.id === studioFilter)) ? studioFilter : null;
const inStudio = useCallback((a: UnifiedApp) => !studioOn || (studioOn === 'none' ? !a.studio : a.studio === studioOn), [studioOn]);
const sideRows = useMemo(() => visible.filter(inStudio).map(a => {
const e = d.statusFor(a), l = d.liveFor(a);
return { app: a, st: sideStatus({ att: attention(a.key, a.name, e, l), all: l?.release.all ?? [], read: !!l || e?.release.source === 'live', missing: !!a.project?.missing, storeOnly: !a.project }) };
}), [visible, d, inStudio]);
const groups: { id: SideGroup | 'ignored'; rows: typeof sideRows }[] = [
...SIDE_GROUPS.map(g => ({ id: g, rows: sideRows.filter(r => r.st.group === g) })).filter(g => g.rows.length),
...(showIgnored && ignoredApps.length ? [{ id: 'ignored' as const, rows: ignoredApps.filter(inStudio).map(a => ({ app: a, st: { group: 'draft' as SideGroup, text: t('side.ignored'), tone: 'neutral' as const } })) }] : []),
];
// Alt+Up / Alt+Down: the previous / next app in sidebar order (keeps the place when the other app has it)
const sideOrder = groups.flatMap(x => (collapsed.includes(`g:${x.id}`) ? [] : x.rows.map(r => r.app)));
const stepApp = useCallback((dir: 1 | -1) => { const stepApp = useCallback((dir: 1 | -1) => {
if (!sideOrder.length) return; if (!sideOrder.length) return;
const i = route.screen === 'app' ? sideOrder.findIndex(a => a.key === route.appId) : -1; const i = route.screen === 'app' ? sideOrder.findIndex(a => a.key === route.appId) : -1;
const next = sideOrder[i < 0 ? (dir === 1 ? 0 : sideOrder.length - 1) : (i + dir + sideOrder.length) % sideOrder.length]!; const next = sideOrder[i < 0 ? (dir === 1 ? 0 : sideOrder.length - 1) : (i + dir + sideOrder.length) % sideOrder.length]!;
go({ screen: 'app', appId: next.key, tab: route.screen === 'app' && tabsFor(!!next.project).includes(route.tab) ? route.tab : 'releases' }); go({ screen: 'app', appId: next.key, tab: route.screen === 'app' && tabsOf(next).includes(route.tab) ? route.tab : 'releases' });
}, [sideOrder, route, go]); }, [sideOrder, route, go, tabsOf]);
const toggleGroup = (id: string) => setCollapsed(c => { const toggleGroup = (id: string) => setCollapsed(c => {
const next = c.includes(id) ? c.filter(x => x !== id) : [...c, id]; const next = c.includes(id) ? c.filter(x => x !== id) : [...c, id];
try { localStorage.setItem(SIDE_KEY, JSON.stringify(next)); } catch { /* private mode */ } try { localStorage.setItem(SIDE_KEY, JSON.stringify(next)); } catch { /* private mode */ }
@ -92,9 +110,12 @@ export function App({ onTheme }: { onTheme: () => void }) {
}, [go, d.reload]); }, [go, d.reload]);
const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined; const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined;
const tabs = app ? tabsFor(!!app.project) : []; const game = app ? gameOf(app) : false;
const tabs = app ? tabsOf(app) : [];
const sections = app ? sectionsFor(!!app.project, game) : [];
// keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-6 workspace, Cmd/Ctrl+Shift+[ ] app tabs // keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-6 workspace, 1-5 (no modifier) the app's sections,
// Cmd/Ctrl+Shift+[ ] the previous / next section
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey; const mod = e.metaKey || e.ctrlKey;
@ -107,15 +128,20 @@ export function App({ onTheme }: { onTheme: () => void }) {
go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! }); go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! });
return; return;
} }
if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app' && tabs.length) { if (!mod && !e.shiftKey && !e.altKey && /^[1-9]$/.test(e.key) && route.screen === 'app' && app && !isEditable(e.target as HTMLInputElement) && !document.querySelector('.ds-menu, .ds-dialog')) {
const sec = sections[Number(e.key) - 1];
if (sec) { e.preventDefault(); go({ ...route, tab: subsOf(sec, !!app.project, game)[0]! }); }
return;
}
if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app' && app && sections.length) {
e.preventDefault(); e.preventDefault();
const i = tabs.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1); const i = sections.indexOf(sectionOf(route.tab)) + (e.key === ']' || e.key === '}' ? 1 : -1);
go({ ...route, tab: tabs[(i + tabs.length) % tabs.length]! }); go({ ...route, tab: subsOf(sections[(i + sections.length) % sections.length]!, !!app.project, game)[0]! });
} }
}; };
window.addEventListener('keydown', onKey); window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey);
}, [palette, welcome, route, go, tabs, stepApp]); }, [palette, welcome, route, go, app, sections, game, stepApp]);
const closeWelcome = useCallback(() => { const closeWelcome = useCallback(() => {
setWelcome(false); setWelcome(false);
@ -129,13 +155,18 @@ export function App({ onTheme }: { onTheme: () => void }) {
const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions'), exp: t('palette.gExport') }; const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions'), exp: t('palette.gExport') };
const studioName = (a: UnifiedApp) => d.studios.find(s => s.id === a.studio)?.name; const studioName = (a: UnifiedApp) => d.studios.find(s => s.id === a.studio)?.name;
for (const a of visible) c.push({ id: `app-${a.key}`, group: G.apps, title: a.name, hint: studioName(a) ?? t('palette.openApp'), keywords: `${a.ios?.app.bundleId ?? ''} ${a.android?.app.id ?? ''} ${a.project?.name ?? ''}`, app: { name: a.name, icon: d.iconFor(a) }, for (const a of visible) c.push({ id: `app-${a.key}`, group: G.apps, title: a.name, hint: studioName(a) ?? t('palette.openApp'), keywords: `${a.ios?.app.bundleId ?? ''} ${a.android?.app.id ?? ''} ${a.project?.name ?? ''}`, app: { name: a.name, icon: d.iconFor(a) },
run: () => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' }) }); run: () => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsOf(a).includes(route.tab) ? route.tab : 'releases' }) });
c.push({ id: 'go-next-app', group: G.go, title: t('palette.nextApp'), icon: 'arrowRight', hint: 'Alt ↓', keywords: 'next app down j', run: () => stepApp(1) }); c.push({ id: 'go-next-app', group: G.go, title: t('palette.nextApp'), icon: 'arrowRight', hint: 'Alt ↓', keywords: 'next app down j', run: () => stepApp(1) });
c.push({ id: 'go-prev-app', group: G.go, title: t('palette.prevApp'), icon: 'arrowLeft', hint: 'Alt ↑', keywords: 'previous app up k', run: () => stepApp(-1) }); c.push({ id: 'go-prev-app', group: G.go, title: t('palette.prevApp'), icon: 'arrowLeft', hint: 'Alt ↑', keywords: 'previous app up k', run: () => stepApp(-1) });
c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) }); c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) });
WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) })); WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) }));
for (const s of d.studios) c.push({ id: `studio-${s.id}`, group: G.go, title: s.name, icon: 'building', keywords: 'studio', hint: t('palette.studio'), run: () => go({ screen: 'accounts', section: s.id }) }); for (const s of d.studios) c.push({ id: `studio-${s.id}`, group: G.go, title: s.name, icon: 'building', keywords: 'studio', hint: t('palette.studio'), run: () => go({ screen: 'accounts', section: s.id }) });
if (app) for (const tab of tabs) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.key, tab }) }); // every section of the open app (1-5) and every sub view in it
if (app) sections.forEach((sec, i) => {
const subs = subsOf(sec, !!app.project, game);
c.push({ id: `sec-${sec}`, group: G.tabs, title: `${app.name} · ${t(SECTION_KEY[sec])}`, icon: SECTION_ICON[sec], hint: String(i + 1), keywords: subs.map(x => t(TAB_KEY[x])).join(' '), run: () => go({ screen: 'app', appId: app.key, tab: subs[0]! }) });
if (subs.length > 1) for (const tab of subs) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(SECTION_KEY[sec])} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.key, tab }) });
});
// the app's own menu (consoles, folder, copy ids, reads, ignore, unpair) as commands: every right-click action is // the app's own menu (consoles, folder, copy ids, reads, ignore, unpair) as commands: every right-click action is
// also one Ctrl+K away; opening a tab is already above // also one Ctrl+K away; opening a tab is already above
if (app) { if (app) {
@ -164,10 +195,10 @@ export function App({ onTheme }: { onTheme: () => void }) {
c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme }); c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme });
c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) }); c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) });
return c; return c;
}, [d, visible, app, tabs, route, go, onTheme, exports, runExport, showIgnored, stepApp, prefs, update]); }, [d, visible, app, sections, game, route, go, onTheme, exports, runExport, showIgnored, stepApp, prefs, update, tabsOf]);
const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }] const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }]
: route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }] : route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(SECTION_KEY[sectionOf(route.tab)]), to: app ? { screen: 'app', appId: app.key, tab: subsOf(sectionOf(route.tab), !!app.project, game)[0] ?? route.tab } : undefined }, ...(app && subsOf(sectionOf(route.tab), !!app.project, game).length > 1 ? [{ label: t(TAB_KEY[route.tab]) }] : [])]
: [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }]; : [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }];
const lastRead = d.live?.at ?? null; const lastRead = d.live?.at ?? null;
// the app on screen is read first by the background reader // the app on screen is read first by the background reader
@ -178,26 +209,19 @@ export function App({ onTheme }: { onTheme: () => void }) {
const ignoredCount = d.apps.filter(a => a.ignored).length + d.overrides.ignored.filter(i => i.startsWith('account:')).length; const ignoredCount = d.apps.filter(a => a.ignored).length + d.overrides.ignored.filter(i => i.startsWith('account:')).length;
const menu = useContextMenu(); const menu = useContextMenu();
const appItem = (a: UnifiedApp) => { const appItem = (a: UnifiedApp, st: { text: string; tone: string }) => (
const e = d.statusFor(a);
const missing = !!a.project?.missing;
const tone = missing ? 'bad' : (worstTone(attention(a.key, a.name, e, d.liveFor(a))) ?? (e ? 'ok' : null));
const bad = missing ? 1 : (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
return (
<div role="listitem" key={a.key}> <div role="listitem" key={a.key}>
<button {...menu(() => appMenu(a, d, nav, { showIgnored }))} className={`nav nav-app${a.ignored ? ' is-ignored' : ''}`} aria-current={current({ screen: 'app', appId: a.key, tab: 'releases' })} <button {...menu(() => appMenu(a, d, nav, { showIgnored }), `app:${a.key}`)} className={`nav nav-app has-line${a.ignored ? ' is-ignored' : ''}`} aria-current={current({ screen: 'app', appId: a.key, tab: 'releases' })}
onClick={() => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' })}> onClick={() => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsOf(a).includes(route.tab) ? route.tab : 'releases' })}
<span className="ds-side-ic"><AppIcon name={a.name} src={d.iconFor(a)} />{tone && <span className={`ds-sdot ${tone}`} role="img" aria-label={tone === 'bad' ? t('pf.blocker') : tone === 'warn' ? t('pf.warning') : t('pf.note')} />}</span> title={`${a.name} · ${st.text}`}>
<span className="grow">{a.name}</span> <span className="ds-side-ic"><AppIcon name={a.name} src={d.iconFor(a)} />{(st.tone === 'bad' || st.tone === 'warn') && <span className={`ds-sdot ${st.tone}`} role="img" aria-label={st.tone === 'bad' ? t('pf.blocker') : t('pf.warning')} />}</span>
{a.ignored && <span className="so-dot" title={t('ignored.rowHint')}><Icon name="eyeOff" /></span>} <span className="grow side-t"><span className="side-n">{a.name}</span><span className={`side-s ${st.tone}`} data-testid="side-status">{st.text}</span></span>
{!a.ignored && a.ignoredStores.length > 0 && <span className="so-dot" title={t('ignored.sideHint', { stores: a.ignoredStores.map(k => (k === 'ios' ? 'App Store' : 'Google Play')).join(', ') })}><Icon name="eyeOff" /></span>} {!a.ignored && a.ignoredStores.length > 0 && <span className="so-dot" title={t('ignored.sideHint', { stores: a.ignoredStores.map(k => (k === 'ios' ? 'App Store' : 'Google Play')).join(', ') })}><Icon name="eyeOff" /></span>}
{!a.project && <span className="so-dot" title={t('apps.storeOnlyHint')}><Icon name="cloud" /></span>} {!a.project && <span className="so-dot" title={t('apps.storeOnlyHint')}><Icon name="cloud" /></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> </button>
</div> </div>
); );
}; const WS_ROW: (WorkspaceScreen | 'portfolio')[] = ['portfolio', ...WORKSPACE];
return ( return (
<NavCtx.Provider value={nav}> <NavCtx.Provider value={nav}>
@ -211,36 +235,41 @@ export function App({ onTheme }: { onTheme: () => void }) {
</button> </button>
</div> </div>
<div className="side-scroll"> <div className="side-scroll">
<button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => go({ screen: 'portfolio' })}> <div className="side-label" id="apps-label"><span>{t('nav.appsLabel')} <span className="count">{visible.length}</span></span>
<Icon name="portfolio" weight={current({ screen: 'portfolio' }) ? 'fill' : 'regular'} /><span className="grow">{t('nav.portfolio')}</span><span className="count">{visible.length}</span>
</button>
<div className="side-label" id="apps-label"><span>{d.studios.length ? t('nav.studiosLabel') : t('nav.appsLabel')}</span>
<button onClick={() => go({ screen: 'apps' })} aria-label={t('action.addFolder')} title={t('action.addFolder')}><Icon name="plus" /></button> <button onClick={() => go({ screen: 'apps' })} aria-label={t('action.addFolder')} title={t('action.addFolder')}><Icon name="plus" /></button>
</div> </div>
{d.studios.length > 1 && (
<div className="side-studios" role="group" aria-label={t('side.studioFilter')}>
<button aria-pressed={!studioOn} onClick={() => setStudioFilter(null)}>{t('side.allStudios')}</button>
{d.studios.map(s => <button key={s.id} aria-pressed={studioOn === s.id} onClick={() => setStudioFilter(studioOn === s.id ? null : s.id)}><StudioMark studio={s} size="sm" />{s.name}</button>)}
</div>
)}
{groups.map(g => { {groups.map(g => {
const s = d.studios.find(x => x.id === g.studio) ?? null; const gid = `g:${g.id}`;
const gid = g.studio ?? 'none';
const open = !collapsed.includes(gid); const open = !collapsed.includes(gid);
if (!d.studios.length) return <div role="list" aria-labelledby="apps-label" key={gid}>{g.rows.map(r => appItem(r.app))}</div>;
return ( return (
<div className="side-group" key={gid}> <div className="side-group" key={gid} data-group={g.id}>
<button className="side-group-head" aria-expanded={open} aria-controls={`sg-${gid}`} onClick={() => toggleGroup(gid)}> <button className="side-group-head" aria-expanded={open} aria-controls={`sg-${g.id}`} onClick={() => toggleGroup(gid)}>
<Icon name="chevronRight" className="chev" /><StudioMark studio={s} size="sm" /><span className="grow">{s?.name ?? t('studio.none')}</span><span className="count">{g.rows.length}</span> <Icon name="chevronRight" className="chev" /><span className="grow">{t(GROUP_KEY[g.id])}</span><span className="count">{g.rows.length}</span>
</button> </button>
{open && <div role="list" id={`sg-${gid}`} aria-label={s?.name ?? t('studio.none')}>{g.rows.map(r => appItem(r.app))}</div>} {open && <div role="list" id={`sg-${g.id}`} aria-label={t(GROUP_KEY[g.id])}>{g.rows.map(r => appItem(r.app, r.st))}</div>}
</div> </div>
); );
})} })}
{!visible.length && !showIgnored && <p className="side-empty">{t('nav.noApps')}</p>} {!visible.length && !showIgnored && <p className="side-empty">{t('nav.noApps')}</p>}
{ignoredApps.length > 0 && <button className="link side-ignored-toggle" aria-pressed={showIgnored} onClick={() => setShowIgnored(!showIgnored)} data-testid="toggle-ignored">{showIgnored ? t('ignored.hide', { count: ignoredApps.length }) : t('ignored.show', { count: ignoredApps.length })}</button>} {ignoredApps.length > 0 && <button className="link side-ignored-toggle" aria-pressed={showIgnored} onClick={() => setShowIgnored(!showIgnored)} data-testid="toggle-ignored">{showIgnored ? t('ignored.hide', { count: ignoredApps.length }) : t('ignored.show', { count: ignoredApps.length })}</button>}
<div className="side-label"><span>{t('nav.workspace')}</span></div> </div>
{WORKSPACE.map((s, i) => ( <div className="side-ws" role="group" aria-label={t('nav.workspace')}>
<button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${t(WS_KEY[s])} (${MOD} ${i + 2})`}> {WS_ROW.map((s, i) => {
<Icon name={WS_ICON[s]} weight={current({ screen: s }) ? 'fill' : 'regular'} /><span className="grow">{t(WS_KEY[s])}</span> const label = s === 'portfolio' ? t('nav.portfolio') : t(WS_KEY[s]);
{s === 'accounts' && <span className="count">{d.accounts.length}</span>} const n = s === 'accounts' ? d.accounts.length : s === 'ignored' ? ignoredCount : 0;
{s === 'ignored' && ignoredCount > 0 && <span className="count">{ignoredCount}</span>} return (
<button key={s} className="nav-ws" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${label} (${MOD} ${i + 1})`} aria-label={label} data-screen={s}>
<Icon name={s === 'portfolio' ? 'portfolio' : WS_ICON[s]} weight={current({ screen: s }) ? 'fill' : 'regular'} />
{n > 0 && <span className="ws-n">{n}</span>}
</button> </button>
))} );
})}
</div> </div>
<div className="side-foot" aria-live="polite"> <div className="side-foot" aria-live="polite">
<div className="row"><i className={`dot ${d.sidecar?.running ? 'ok' : d.sidecarError ? 'bad' : ''}`} /> <div className="row"><i className={`dot ${d.sidecar?.running ? 'ok' : d.sidecarError ? 'bad' : ''}`} />
@ -262,8 +291,8 @@ export function App({ onTheme }: { onTheme: () => void }) {
<span className="spacer" /> <span className="spacer" />
{FIXTURES && <span className="dev-pill" title={t('dev.fixturesHint')}>{t('dev.fixtures')}</span>} {FIXTURES && <span className="dev-pill" title={t('dev.fixturesHint')}>{t('dev.fixtures')}</span>}
<span className="stamp"><Icon name="clock" />{lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')}</span> <span className="stamp"><Icon name="clock" />{lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')}</span>
<button className="btn btn-sm" onClick={() => { d.readAll(true).catch(() => {}); }} disabled={!visible.length} title={t('action.refreshAllHint')} data-testid="refresh-all"> <button className="btn btn-sm" onClick={() => { d.readAll(true).catch(() => {}); }} disabled={!visible.length || allReads.busy} aria-busy={allReads.busy} title={allReads.busy ? t('read.busyShared') : t('action.refreshAllHint')} data-testid="refresh-all">
<Icon name="refresh" className={d.reader.running ? 'spin' : undefined} />{t('action.refreshAll')} <Icon name="refresh" className={allReads.busy ? 'spin' : undefined} />{t('action.refreshAll')}
</button> </button>
<ExportMenu /> <ExportMenu />
</header> </header>

View file

@ -36,7 +36,8 @@ export interface Settings {
cache: { keepDays: 0 | 7 | 30 | 90 | 365 }; cache: { keepDays: 0 | 7 | 30 | 90 | 365 };
/** reviewState: other state changes (submitted, in review); rejected / approved / live: own toggles; crash also covers a halted rollout. quietHours: no notification between from and to (HH:MM, may cross midnight). */ /** reviewState: other state changes (submitted, in review); rejected / approved / live: own toggles; crash also covers a halted rollout. quietHours: no notification between from and to (HH:MM, may cross midnight). */
notify: { reviewState: boolean; rejected: boolean; approved: boolean; live: boolean; lowReviews: boolean; crash: boolean; quietHours: { enabled: boolean; from: string; to: string } }; notify: { reviewState: boolean; rejected: boolean; approved: boolean; live: boolean; lowReviews: boolean; crash: boolean; quietHours: { enabled: boolean; from: string; to: string } };
channel: 'stable' | 'beta'; /** Update channel: stable (npm releases) or dev (every push to main); beta is kept for saved states. */
channel: 'stable' | 'dev' | 'beta';
} }
export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true, autoRead: true, everyMinutes: 15 }, cache: { keepDays: 30 }, notify: { reviewState: true, rejected: true, approved: true, live: true, lowReviews: true, crash: true, quietHours: { enabled: false, from: '23:00', to: '08:00' } }, 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, rejected: true, approved: true, live: true, lowReviews: true, crash: true, quietHours: { enabled: false, from: '23:00', to: '08:00' } }, channel: 'stable' };
export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings } export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings }
@ -47,7 +48,7 @@ export interface CacheEntry<T = unknown> { value: T; at: string }
export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string } export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string }
export interface DownloadEvent { job: string; tool: string; stage: 'resolve' | 'download' | 'verify' | 'unpack' | 'install' | 'done' | 'error' | 'cancelled'; received: number; total: number | null; message?: string } export interface DownloadEvent { job: string; tool: string; stage: 'resolve' | 'download' | 'verify' | 'unpack' | 'install' | 'done' | 'error' | 'cancelled'; received: number; total: number | null; message?: string }
export type { IconResult as Icon }; export type { IconResult as Icon };
export interface UpdateInfo { current: string; channel: 'stable' | 'beta'; available: string | null; notes: string | null; date: string | null } export interface UpdateInfo { current: string; channel: 'stable' | 'dev' | 'beta'; available: string | null; notes: string | null; date: string | null }
/** What a failed command rejects with (sidecar.rs `Fail`). */ /** What a failed command rejects with (sidecar.rs `Fail`). */
export interface Fail { code: number; message: string; data?: unknown } export interface Fail { code: number; message: string; data?: unknown }

View file

@ -0,0 +1,178 @@
// The tray card: store status at a glance next to the tray icon. It only draws the main window's snapshot (card_get /
// `card-snapshot`) and sends its buttons back (card_action); Refresh is the main window's own Refresh all.
import { ArrowsClockwiseIcon } from '@phosphor-icons/react/dist/csr/ArrowsClockwise';
import { ArrowSquareOutIcon } from '@phosphor-icons/react/dist/csr/ArrowSquareOut';
import { BellSlashIcon } from '@phosphor-icons/react/dist/csr/BellSlash';
import { BellIcon } from '@phosphor-icons/react/dist/csr/Bell';
import { DotsThreeIcon } from '@phosphor-icons/react/dist/csr/DotsThree';
import { PowerIcon } from '@phosphor-icons/react/dist/csr/Power';
import { StarIcon } from '@phosphor-icons/react/dist/csr/Star';
import { WarningOctagonIcon } from '@phosphor-icons/react/dist/csr/WarningOctagon';
import { PulseIcon } from '@phosphor-icons/react/dist/csr/Pulse';
import { AppWindowIcon } from '@phosphor-icons/react/dist/csr/AppWindow';
import { useCallback, useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
import type { CardApp, CardRelease, CardSnapshot, CardStore } from './model';
import { ago, cardT, type CardKey, type CardLang } from './text';
export interface CardHost {
get: () => Promise<CardSnapshot | null>;
onSnapshot: (fn: (s: CardSnapshot) => void) => () => void;
onShown: (fn: () => void) => () => void;
action: (action: 'hide' | 'open' | 'route' | 'refresh' | 'mute' | 'quit' | 'external' | 'ready' | 'size', arg?: string) => void;
}
const route = (app: string, tab: 'releases' | 'reviews' | 'health') => JSON.stringify({ screen: 'app', appId: app, tab });
export function Card({ host, lang }: { host: CardHost; lang: CardLang }) {
const T = useCallback((k: CardKey, v?: Record<string, string | number>) => cardT(lang, k, v), [lang]);
const [s, setS] = useState<CardSnapshot | null>(null);
const [menu, setMenu] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [shown, setShown] = useState(0);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
host.get().then(x => { if (x) setS(x); }).catch(() => {});
const a = host.onSnapshot(setS);
const b = host.onShown(() => { setNow(Date.now()); setMenu(false); setShown(n => n + 1); });
host.action('ready');
const tm = setInterval(() => setNow(Date.now()), 30_000);
return () => { a(); b(); clearInterval(tm); };
}, [host]);
// the window is as tall as the card: report the height whenever it changes (the host re-anchors it above the icon)
useEffect(() => {
const el = root.current;
if (!el || typeof ResizeObserver === 'undefined') return;
let last = 0;
const ro = new ResizeObserver(() => {
const h = Math.ceil(el.getBoundingClientRect().height);
if (h > 0 && h !== last) { last = h; host.action('size', String(h)); }
});
ro.observe(el);
return () => ro.disconnect();
}, [host]);
// every show: fade in, focus the first control (keyboard users start at Refresh)
useEffect(() => { (root.current?.querySelector<HTMLElement>('button:not([disabled])') ?? root.current)?.focus(); }, [shown, !!s]);
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') { e.preventDefault(); if (menu) setMenu(false); else host.action('hide'); return; }
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
const all = [...(root.current?.querySelectorAll<HTMLElement>('button:not([disabled])') ?? [])];
const i = all.indexOf(document.activeElement as HTMLElement);
const n = all[(i + (e.key === 'ArrowDown' ? 1 : -1) + all.length) % all.length];
if (n) { e.preventDefault(); n.focus(); }
}
};
const store = (st: CardStore) => T(st === 'ios' ? 'appStore' : 'playStore');
const phase = (r: CardRelease) => (r.phase === 'rollout' ? (r.fraction != null && r.fraction < 1 ? T('rolloutPct', { pct: Math.round(r.fraction * 100) }) : T('rollout')) : T(r.phase));
const link = (key: string): CardApp | undefined => s?.links.find(l => l.key === key);
const busy = !!s?.busy;
const calm = s && !s.rejections.length && !s.releases.length && !s.health.length && !s.reviews.low.length;
return (
<div className="tc" ref={root} onKeyDown={onKey} data-shown={shown} tabIndex={-1} role="dialog" aria-label={T('title')}>
<header className="tc-head">
<div className="tc-title">
<strong>{T('title')}</strong>
<span className="tc-meta">{s?.muted && <span className="tc-muted"><BellSlashIcon size={12} weight="bold" />{T('muted')}</span>}{T('lastRead', { ago: ago(lang, s?.at ?? null, now) })}</span>
</div>
<button className="tc-btn tc-primary" data-first onClick={() => host.action('refresh')} disabled={busy} aria-busy={busy} data-testid="card-refresh">
<ArrowsClockwiseIcon size={14} weight="bold" className={busy ? 'spin' : undefined} />{busy ? T('refreshing') : T('refresh')}
</button>
<button className="tc-icon" onClick={() => setMenu(m => !m)} aria-haspopup="menu" aria-expanded={menu} aria-label={T('more')} title={T('more')}><DotsThreeIcon size={18} weight="bold" /></button>
{menu && (
<div className="tc-menu" role="menu">
<button role="menuitem" onClick={() => host.action('open')}><AppWindowIcon size={15} />{T('openMain')}</button>
<button role="menuitem" onClick={() => { host.action('mute'); setMenu(false); }}>{s?.muted ? <BellIcon size={15} /> : <BellSlashIcon size={15} />}{s?.muted ? T('unmute') : T('mute')}</button>
<hr />
<button role="menuitem" onClick={() => host.action('quit')}><PowerIcon size={15} />{T('quit')}</button>
</div>
)}
</header>
<div className="tc-body">
{!s && <p className="tc-empty">{T('noData')}</p>}
{s && calm && <p className="tc-empty">{s.at ? T('calm') : T('noData')}</p>}
{!!s?.rejections.length && (
<Section title={T('rejections')} tone="bad">
{s.rejections.map(r => (
<Row key={`${r.app}:${r.store}:${r.version}`} hue={r.hue} name={r.name} tone="bad" onOpen={() => host.action('route', route(r.app, 'releases'))} openLabel={T('openApp', { name: r.name })}
line={<><WarningOctagonIcon size={13} weight="fill" />{T('rejected')} · {store(r.store)}{r.version ? ` ${r.version}` : ''}</>} sub={r.reason}
consoles={consoles(link(r.app), r.store, host, T)} />
))}
</Section>
)}
{!!s?.releases.length && (
<Section title={T('moving')}>
{s.releases.map(r => (
<Row key={`${r.app}:${r.store}:${r.version}`} hue={r.hue} name={r.name} tone={r.phase === 'halted' ? 'bad' : r.phase === 'approved' ? 'ok' : r.phase === 'review' ? 'info' : 'accent'}
onOpen={() => host.action('route', route(r.app, 'releases'))} openLabel={T('openApp', { name: r.name })}
line={<>{phase(r)} · {store(r.store)}{r.version ? ` ${r.version}` : ''}</>}
bar={r.phase === 'rollout' && r.fraction != null && r.fraction < 1 ? r.fraction : null}
consoles={consoles(link(r.app), r.store, host, T)} />
))}
</Section>
)}
{!!s?.health.length && (
<Section title={T('health')} tone="warn">
{s.health.map(h => (
<Row key={h.app} hue={h.hue} name={h.name} tone="warn" onOpen={() => host.action('route', route(h.app, 'health'))} openLabel={T('openApp', { name: h.name })}
line={<><PulseIcon size={13} weight="bold" />{h.kinds.length > 1 ? T('crashAnr') : T(h.kinds[0]!)}</>} consoles={consoles(link(h.app), 'android', host, T)} />
))}
</Section>
)}
{s && s.at && (
<Section title={T('reviews')} aside={s.reviews.recent ? T('recent', { n: s.reviews.recent }) : T('recentNone')}>
{s.reviews.low.map(r => (
<button key={`${r.app}:${r.date}:${r.text}`} className="tc-review" onClick={() => host.action('route', route(r.app, 'reviews'))}>
<span className="tc-stars" aria-label={T('stars', { n: r.rating })}>{[1, 2, 3, 4, 5].map(i => <StarIcon key={i} size={11} weight={i <= r.rating ? 'fill' : 'regular'} />)}</span>
<span className="tc-rname">{r.name}</span>
<span className="tc-rtext">{r.text}</span>
</button>
))}
</Section>
)}
</div>
{s?.build && <footer className="tc-foot" data-testid="card-build">{T('build', { version: s.build.version, channel: T(s.build.channel === 'dev' ? 'chDev' : s.build.channel === 'beta' ? 'chBeta' : 'chStable') })}</footer>}
</div>
);
}
function consoles(l: CardApp | undefined, st: CardStore, host: CardHost, T: (k: CardKey) => string): ReactNode {
const url = st === 'ios' ? l?.asc : l?.play;
if (!url) return null;
return <button className="tc-ext" onClick={e => { e.stopPropagation(); host.action('external', url); }} title={T(st === 'ios' ? 'asc' : 'play')} aria-label={T(st === 'ios' ? 'asc' : 'play')}><ArrowSquareOutIcon size={14} /></button>;
}
function Section({ title, tone, aside, children }: { title: string; tone?: 'bad' | 'warn'; aside?: string; children: ReactNode }) {
return (
<section className={`tc-sec${tone ? ` tc-${tone}` : ''}`}>
<h2><span>{title}</span>{aside && <em>{aside}</em>}</h2>
{children}
</section>
);
}
function Row({ hue, name, line, sub, tone, bar, onOpen, openLabel, consoles }: { hue: number; name: string; line: ReactNode; sub?: string | null; tone: string; bar?: number | null; onOpen: () => void; openLabel: string; consoles: ReactNode }) {
return (
<div className={`tc-row tone-${tone}`}>
<button className="tc-open" onClick={onOpen} aria-label={openLabel}>
<span className="tc-ic" style={{ '--tint-h': hue } as React.CSSProperties} aria-hidden>{initials(name)}</span>
<span className="tc-txt">
<span className="tc-name">{name}</span>
<span className="tc-line">{line}</span>
{sub && <span className="tc-sub">{sub}</span>}
{bar != null && <span className="tc-bar" aria-hidden><i style={{ width: `${Math.max(2, Math.round(bar * 100))}%` }} /></span>}
</span>
</button>
{consoles}
</div>
);
}
const initials = (n: string) => n.split(/\s+/).filter(Boolean).slice(0, 2).map(w => w[0]!.toUpperCase()).join('') || '?';

View file

@ -0,0 +1,66 @@
// Main window side of the tray card: turns what this window already knows (live releases, the last cached reviews and
// health per app, the shared read state of Refresh all, mute) into a CardSnapshot and hands it to the host
// (card_snapshot), which keeps it for the card. No reads of its own: reviews and health come from the cache that the
// window's reads fill, and the card's Refresh arrives as the tray's `tray-action` read (store.tsx), i.e. Refresh all.
import { useEffect, useMemo, useRef, useState } from 'react';
import { api } from '../api';
import type { HealthSnapshot, Review } from '../lib/model';
import { hueOf } from '../lib/model';
import { useData, useReadState } from '../store';
import { playUrlFor } from '../ui/app-menu';
import { cardApi, inTauri as hasHost } from './card-api';
import { cardSnapshot, type CardInput } from './model';
const inTauri = hasHost();
const ascUrl = (id: string | null | undefined) => (id ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(id)}/distribution` : 'https://appstoreconnect.apple.com/apps');
export function TrayCardBridge() {
const d = useData();
const all = useReadState({ tags: ['all'] });
const [extra, setExtra] = useState<Record<string, { reviews: Review[] | null; health: HealthSnapshot | null }>>({});
const [ask, setAsk] = useState(0);
const visible = useMemo(() => d.apps.filter(a => !a.ignored), [d.apps]);
// the card opened (or a read pass ended): the last cached reviews and health of every app
useEffect(() => {
if (!inTauri) return;
return cardApi.onRequest(() => setAsk(n => n + 1));
}, []);
const wasBusy = useRef(all.busy);
useEffect(() => { if (wasBusy.current && !all.busy) setAsk(n => n + 1); wasBusy.current = all.busy; }, [all.busy]);
useEffect(() => {
if (!inTauri || !d.ready) return;
let live = true;
Promise.all(visible.map(async a => {
const [r, h] = await Promise.all([
api.cached<{ data?: Review[] }>('reviews.list', a.target, { days: 30 }).catch(() => null),
api.cached<{ data?: HealthSnapshot }>('health', a.target, {}).catch(() => null),
]);
return [a.key, { reviews: Array.isArray(r?.value.data) ? r.value.data : null, health: (h?.value.data as HealthSnapshot | undefined) ?? null }] as const;
})).then(rows => { if (live) setExtra(Object.fromEntries(rows)); }).catch(() => {});
return () => { live = false; };
}, [ask, d.ready, visible]);
const snap = useMemo(() => {
const inputs: CardInput[] = visible.map(a => {
const st = d.liveFor(a) ?? d.statusFor(a);
const ios = st?.app?.platforms.ios ?? (a.ios ? { ascAppId: a.ios.app.id } : null);
return {
key: a.key, name: a.name, hue: hueOf(a.name), status: st,
reviews: extra[a.key]?.reviews ?? null, health: extra[a.key]?.health ?? null,
asc: ios ? ascUrl(ios.ascAppId) : null, play: st?.app?.platforms.android || a.android ? playUrlFor(d, a) : null,
};
});
return cardSnapshot(inputs, { at: d.live?.value.at ?? d.portfolio?.at ?? null, busy: all.busy, muted: d.muteUntil > Date.now(), build: d.info ? { version: d.info.version, channel: d.settings.channel } : null });
}, [visible, d, extra, all.busy]);
const last = useRef('');
useEffect(() => {
if (!inTauri || !d.ready) return;
const json = JSON.stringify(snap);
if (json === last.current) return;
last.current = json;
cardApi.push(snap).catch(() => {});
}, [snap, d.ready]);
return null;
}

View file

@ -0,0 +1,25 @@
// The tray card's host calls (the card page's counterpart of src/api.ts, kept apart so the card bundle stays small).
// Main window: card_snapshot + the `card-request` event. Card window: card_get, card_action and its two events.
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import type { CardSnapshot } from './model';
export type CardAction = 'hide' | 'open' | 'route' | 'refresh' | 'mute' | 'quit' | 'external' | 'ready' | 'size';
export const inTauri = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
function sub<T>(ev: string, fn: (p: T) => void): () => void {
const un = listen<T>(ev, e => fn(e.payload));
return () => { un.then(f => f()).catch(() => {}); };
}
export const cardApi = {
/** Main window: hands the host the card's snapshot (the host forwards it as `card-snapshot`). */
push: (snapshot: CardSnapshot) => invoke<void>('card_snapshot', { snapshot }),
/** Main window: the card opened; refresh what is kept per app. */
onRequest: (fn: () => void) => sub<null>('card-request', () => fn()),
get: () => invoke<CardSnapshot | null>('card_get'),
onSnapshot: (fn: (s: CardSnapshot) => void) => sub<CardSnapshot>('card-snapshot', fn),
onShown: (fn: () => void) => sub<null>('card-shown', () => fn()),
action: (action: CardAction, arg?: string) => { invoke('card_action', { action, arg: arg ?? null }).catch(() => {}); },
};

View file

@ -0,0 +1,59 @@
/* The tray card (card.html): v2 language, 360 wide and as tall as its content (at most 480: the body scrolls), rounded, its own surface; fades in over 120 ms on every show. */
html:has(body.tc-page), body.tc-page { margin: 0; height: 100%; background: transparent; overflow: hidden; }
body.tc-page { font: var(--ds-t-body)/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; color: var(--ink); }
body.tc-page #card { height: auto; }
body.tc-page.tc-in .tc { animation: tc-in 120ms ease-out; }
:root[data-motion="reduce"] body.tc-page.tc-in .tc { animation: none; }
@keyframes tc-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
.tc { box-sizing: border-box; height: auto; max-height: 480px; display: flex; flex-direction: column; border-radius: var(--ds-r-lg);
border: 1px solid var(--ds-stroke); background: radial-gradient(120% 60% at 100% 0%, color-mix(in srgb, var(--accent-solid) 10%, transparent), transparent 60%), var(--ds-raised); overflow: hidden; outline: none; }
.tc-head { position: relative; display: flex; align-items: center; gap: 8px; padding: 14px 12px 12px 16px; border-bottom: 1px solid var(--ds-stroke); }
.tc-title { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.tc-title strong { font-size: var(--ds-t-h3); font-weight: var(--ds-w-title); letter-spacing: -.01em; }
.tc-meta { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: var(--ds-t-micro); }
.tc-muted { display: inline-flex; align-items: center; gap: 3px; color: var(--warn-ink); background: var(--warn-bg); border-radius: var(--ds-r-pill); padding: 0 6px; }
.tc button { font: inherit; color: inherit; cursor: pointer; }
.tc button:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.tc-btn { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 12px; border-radius: var(--ds-r-pill); border: 0; font-weight: var(--ds-w-strong); font-size: var(--ds-t-meta); }
.tc .tc-primary { background: var(--ds-grad); color: #fff; box-shadow: var(--ds-e1); }
.tc-primary[disabled] { opacity: .7; cursor: default; }
.tc-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: var(--ds-r-pill); border: 1px solid var(--ds-stroke); background: var(--ds-surface); }
.tc-icon:hover, .tc-icon[aria-expanded="true"] { background: var(--hover); }
.tc-menu { position: absolute; z-index: 3; right: 12px; top: 50px; min-width: 230px; padding: 5px; border-radius: var(--ds-r); background: var(--ds-raised); border: 1px solid var(--ds-stroke); box-shadow: var(--ds-e3); }
.tc-menu button { display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 9px; border: 0; background: none; border-radius: var(--ds-r-xs); text-align: left; font-size: var(--ds-t-meta); }
.tc-menu button:hover, .tc-menu button:focus-visible { background: var(--hover); outline: none; }
.tc-menu hr { border: 0; border-top: 1px solid var(--ds-stroke); margin: 4px 2px; }
.tc-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 6px 10px 12px; scrollbar-width: thin; }
.tc-empty { margin: 28px 16px; text-align: center; color: var(--muted); }
.tc-sec { margin-top: 8px; }
.tc-sec h2 { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin: 6px 6px 4px; font-size: var(--ds-t-micro); font-weight: var(--ds-w-strong); text-transform: uppercase; letter-spacing: .07em; color: var(--muted); }
.tc-sec h2 em { font-style: normal; text-transform: none; letter-spacing: 0; font-weight: 500; color: var(--faint); }
.tc-sec.tc-bad { background: var(--bad-bg); border: 1px solid color-mix(in srgb, var(--bad-solid) 30%, transparent); border-radius: var(--ds-r); padding: 2px 4px 4px; }
.tc-sec.tc-bad h2 { color: var(--bad-ink); }
.tc-row { display: flex; align-items: center; gap: 2px; border-radius: var(--ds-r-sm); }
.tc-row:hover { background: color-mix(in srgb, var(--hover) 80%, transparent); }
.tc-open { flex: 1; min-width: 0; display: flex; gap: 10px; align-items: flex-start; padding: 7px 6px; border: 0; background: none; text-align: left; border-radius: var(--ds-r-sm); }
.tc-ic { --tint: hsl(var(--tint-h) var(--ds-tint-s) var(--ds-tint-l)); flex: none; display: grid; place-items: center; width: 28px; height: 28px; border-radius: 8px; font-size: 10px; font-weight: 700; color: #fff; background: linear-gradient(135deg, var(--tint), hsl(calc(var(--tint-h) + 30) var(--ds-tint-s) 45%)); }
.tc-txt { min-width: 0; display: flex; flex-direction: column; gap: 1px; flex: 1; }
.tc-name { font-weight: var(--ds-w-strong); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tc-line { display: inline-flex; align-items: center; gap: 4px; font-size: var(--ds-t-meta); color: var(--ink-2); }
.tone-bad .tc-line { color: var(--bad-ink); font-weight: var(--ds-w-strong); }
.tone-ok .tc-line { color: var(--ok-ink); }
.tone-info .tc-line { color: var(--info-ink); }
.tone-warn .tc-line { color: var(--warn-ink); }
.tone-accent .tc-line { color: var(--accent); }
.tc-sub { font-size: var(--ds-t-micro); color: var(--muted); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.tc-bar { margin-top: 4px; height: 4px; border-radius: 4px; background: var(--ds-inset); overflow: hidden; }
.tc-bar i { display: block; height: 100%; background: var(--ds-grad); border-radius: 4px; }
.tc-ext { flex: none; display: grid; place-items: center; width: 28px; height: 28px; margin-right: 4px; border: 0; background: none; color: var(--muted); border-radius: var(--ds-r-xs); }
.tc-ext:hover { background: var(--hover); color: var(--ink); }
.tc-review { display: grid; grid-template-columns: auto 1fr; gap: 1px 8px; width: 100%; padding: 7px 6px; border: 0; background: none; text-align: left; border-radius: var(--ds-r-sm); }
.tc-review:hover { background: var(--hover); }
.tc-stars { display: inline-flex; gap: 1px; align-items: center; color: var(--warn-solid); }
.tc-rname { font-weight: var(--ds-w-strong); font-size: var(--ds-t-meta); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tc-rtext { grid-column: 1 / -1; font-size: var(--ds-t-meta); color: var(--ink-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tc-foot { padding: 6px 12px 8px; color: var(--muted); font-size: var(--ds-t-micro); border-top: 1px solid var(--ds-stroke); font-variant-numeric: tabular-nums; }

View file

@ -0,0 +1,25 @@
// Dev only: a card snapshot for the plain browser (no Tauri host), so the card can be looked at in `vite` alone.
import type { CardSnapshot } from './model';
const ago = (min: number) => new Date(Date.now() - min * 60_000).toISOString();
export const CARD_FIXTURE: CardSnapshot = {
at: ago(4), busy: false, muted: false, apps: 6,
rejections: [{ app: 'a1', name: 'Prism Puddle', hue: 280, store: 'ios', version: '2.4.0', reason: 'Guideline 2.1 - Performance - App Completeness: the app crashed on launch on iPad Air (5th generation).' }],
releases: [
{ app: 'a2', name: 'Tidy Tiles', hue: 160, store: 'ios', version: '1.8.2', phase: 'review', fraction: null },
{ app: 'a3', name: 'Moss Runner', hue: 30, store: 'ios', version: '3.0.0', phase: 'approved', fraction: null },
{ app: 'a2', name: 'Tidy Tiles', hue: 160, store: 'android', version: '1.8.1', phase: 'rollout', fraction: 0.2 },
],
reviews: { recent: 14, low: [
{ app: 'a2', name: 'Tidy Tiles', store: 'play', rating: 1, text: 'Lost my progress · After the update every level is locked again.', date: ago(90) },
{ app: 'a3', name: 'Moss Runner', store: 'apple', rating: 2, text: 'Too many ads between runs', date: ago(600) },
] },
health: [{ app: 'a4', name: 'Sample Blocks', hue: 210, kinds: ['crash'] }],
links: [
{ key: 'a1', name: 'Prism Puddle', hue: 280, asc: 'https://appstoreconnect.apple.com/apps', play: null },
{ key: 'a2', name: 'Tidy Tiles', hue: 160, asc: 'https://appstoreconnect.apple.com/apps', play: 'https://play.google.com/console' },
{ key: 'a3', name: 'Moss Runner', hue: 30, asc: 'https://appstoreconnect.apple.com/apps', play: null },
{ key: 'a4', name: 'Sample Blocks', hue: 210, asc: null, play: 'https://play.google.com/console' },
],
};

View file

@ -0,0 +1,53 @@
// The tray card window's entry (card.html): theme and language from the same prefs as the main window, the host
// through Tauri (or a fixture in a plain dev browser).
import { createRoot } from 'react-dom/client';
import { applyPrefs, loadPrefs, resolveLang } from '../prefs';
import { Card, type CardHost } from './Card';
import { cardApi, inTauri } from './card-api';
import type { CardSnapshot } from './model';
import '../styles.css';
import '../design.css';
import './card.css';
const sys = () => (typeof navigator !== 'undefined' ? navigator.language : 'en');
function prefs() {
const p = loadPrefs();
if (import.meta.env.DEV) {
const q = new URLSearchParams(location.search);
const th = q.get('theme'), lg = q.get('lang');
if (th === 'light' || th === 'dark') p.theme = th;
if (lg === 'en' || lg === 'tr') p.lang = lg;
}
applyPrefs(p, document.documentElement, sys());
return resolveLang(p.lang, sys());
}
async function devHost(): Promise<CardHost> {
const { CARD_FIXTURE } = await import('./fixture');
const q = new URLSearchParams(location.search);
const snap: CardSnapshot = q.get('empty')
? { ...CARD_FIXTURE, rejections: [], releases: [], health: [], reviews: { recent: 0, low: [] } }
: { ...CARD_FIXTURE, busy: !!q.get('busy') };
return { get: async () => snap, onSnapshot: () => () => {}, onShown: () => () => {}, action: (a, arg) => console.info('card action', a, arg ?? '') };
}
const tauriHost: CardHost = cardApi;
void (async () => {
let lang = prefs();
const host = inTauri() ? tauriHost : await devHost();
const root = createRoot(document.getElementById('card')!);
const render = () => root.render(<Card key={lang} host={host} lang={lang} />);
render();
const relang = () => { const l = prefs(); if (l !== lang) { lang = l; render(); } };
// theme or language changed in the main window (same origin: shared localStorage)
window.addEventListener('storage', relang);
host.onShown(() => {
relang();
document.body.classList.remove('tc-in');
void document.body.offsetWidth;
document.body.classList.add('tc-in');
});
document.body.classList.add('tc-in');
})();

View file

@ -0,0 +1,89 @@
// The tray card's data: what the main window already knows, boiled down to the few rows the card shows. Pure (the
// main window's bridge calls it, tests/card-model.test.ts pins it); the card itself only draws a CardSnapshot.
import type { AppStatus } from '../api';
import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from '../lib/model';
export type CardStore = 'ios' | 'android';
/** A release that moves or waits: in review, rolling out (with its share), approved and waiting for release, halted. */
export interface CardRelease { app: string; name: string; hue: number; store: CardStore; version: string | null; phase: 'review' | 'rollout' | 'approved' | 'halted'; fraction: number | null }
export interface CardRejection { app: string; name: string; hue: number; store: CardStore; version: string | null; reason: string | null }
export interface CardLowReview { app: string; name: string; store: 'apple' | 'play'; rating: number; text: string; date: string }
export interface CardHealth { app: string; name: string; hue: number; kinds: ('crash' | 'anr')[] }
export interface CardApp { key: string; name: string; hue: number; asc: string | null; play: string | null }
export interface CardSnapshot {
/** Last store read of the main window (ISO), null before any. */
at: string | null;
/** The main window's Refresh all is running (its shared read state). */
busy: boolean;
muted: boolean;
apps: number;
rejections: CardRejection[];
releases: CardRelease[];
reviews: { recent: number; low: CardLowReview[] };
health: CardHealth[];
/** Apps with something on the card, for the quick actions (console links). */
links: CardApp[];
/** This app's version and update channel (Settings > Updates), shown at the card's foot. */
build?: { version: string; channel: string } | null;
}
export interface CardInput {
key: string; name: string; hue: number; status: AppStatus | undefined;
reviews?: Review[] | null; health?: HealthSnapshot | null;
asc?: string | null; play?: string | null;
}
export const RECENT_DAYS = 7;
export const LOW_DAYS = 14;
export const MAX_ROWS = 6;
export const MAX_LOW = 3;
const DAY = 86_400_000;
const one = (s: string, max: number): string => { const x = s.replace(/\s+/g, ' ').trim(); return x.length > max ? `${x.slice(0, max - 1)}…` : x; };
/** Crash / ANR rates over the Play bad behavior threshold right now. */
export function healthAlerts(h: HealthSnapshot | null | undefined): ('crash' | 'anr')[] {
if (!h?.play || isError(h.play)) return [];
const out: ('crash' | 'anr')[] = [];
if (healthSeries(h.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash).tone === 'bad') out.push('crash');
if (healthSeries(h.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr).tone === 'bad') out.push('anr');
return out;
}
export function cardSnapshot(apps: CardInput[], o: { at: string | null; busy: boolean; muted: boolean; now?: number; build?: { version: string; channel: string } | null }): CardSnapshot {
const now = o.now ?? Date.now();
const rejections: CardRejection[] = [], releases: CardRelease[] = [], low: CardLowReview[] = [], health: CardHealth[] = [];
const touched = new Set<string>();
let recent = 0;
for (const a of apps) {
for (const r of a.status?.release.all ?? []) {
if (r.phase === 'rejected') { rejections.push({ app: a.key, name: a.name, hue: a.hue, store: r.store, version: r.version, reason: r.reason ? one(r.reason, 140) : null }); touched.add(a.key); }
else if (r.phase === 'review' || r.phase === 'sent' || r.phase === 'rollout' || r.phase === 'approved' || r.phase === 'halted') {
releases.push({ app: a.key, name: a.name, hue: a.hue, store: r.store, version: r.version, phase: r.phase === 'sent' ? 'review' : r.phase, fraction: r.phase === 'rollout' ? r.fraction : null });
touched.add(a.key);
}
}
for (const rv of a.reviews ?? []) {
const age = now - Date.parse(rv.date);
if (!(age > -DAY)) continue; // unreadable date, or far in the future
if (age <= RECENT_DAYS * DAY) recent++;
if (rv.rating <= 2 && age <= LOW_DAYS * DAY) {
low.push({ app: a.key, name: a.name, store: rv.store, rating: rv.rating, text: one([rv.title, rv.body].filter(Boolean).join(' · '), 110), date: rv.date });
touched.add(a.key);
}
}
const kinds = healthAlerts(a.health);
if (kinds.length) { health.push({ app: a.key, name: a.name, hue: a.hue, kinds }); touched.add(a.key); }
}
// halted first (it needs the owner), then review, waiting for release, rolling out
const order = { halted: 0, review: 1, approved: 2, rollout: 3 } as const;
releases.sort((x, y) => order[x.phase] - order[y.phase] || x.name.localeCompare(y.name));
low.sort((x, y) => y.date.localeCompare(x.date));
return {
at: o.at, busy: o.busy, muted: o.muted, apps: apps.length,
rejections: rejections.slice(0, MAX_ROWS), releases: releases.slice(0, MAX_ROWS),
reviews: { recent, low: low.slice(0, MAX_LOW) }, health: health.slice(0, MAX_ROWS),
links: apps.filter(a => touched.has(a.key)).map(a => ({ key: a.key, name: a.name, hue: a.hue, asc: a.asc ?? null, play: a.play ?? null })),
build: o.build ?? null,
};
}

View file

@ -0,0 +1,111 @@
// The tray card's words in every language the app has (en, tr; same keys, tr typed against en). Kept apart from the
// main catalogs so the card bundle stays small.
export const en = {
title: 'Store status',
rejected: 'Rejected',
rejections: 'Needs you',
moving: 'Releases on the move',
review: 'In review',
rollout: 'Rolling out',
rolloutPct: 'Rolling out {pct}%',
approved: 'Waiting for release',
halted: 'Rollout halted',
reviews: 'Reviews',
recent: '{n} new in the last 7 days',
recentNone: 'No new reviews in the last 7 days',
health: 'Crash and ANR alerts',
crash: 'Crash rate over the bad behavior threshold',
anr: 'ANR rate over the bad behavior threshold',
crashAnr: 'Crash and ANR rates over the bad behavior threshold',
calm: 'All quiet: nothing in review, rolling out or waiting on you.',
noData: 'No store read yet. Refresh reads every app.',
lastRead: 'Read {ago}',
never: 'never',
justNow: 'just now',
min: '{n} min ago',
hour: '{n} h ago',
day: '{n} d ago',
refresh: 'Refresh',
refreshing: 'Reading…',
openMain: 'Open storebound',
build: 'storebound {version} · {channel} channel',
chStable: 'stable',
chDev: 'dev',
chBeta: 'beta',
more: 'More',
mute: 'Mute notifications for 1 hour',
unmute: 'Unmute notifications',
muted: 'Muted',
quit: 'Quit storebound',
openApp: 'Open {name}',
asc: 'App Store Connect',
play: 'Play Console',
appStore: 'App Store',
playStore: 'Play',
stars: '{n} of 5 stars',
};
export type CardKey = keyof typeof en;
export const tr: Record<CardKey, string> = {
title: 'Mağaza durumu',
rejected: 'Reddedildi',
rejections: 'Seni bekliyor',
moving: 'İlerleyen sürümler',
review: 'İncelemede',
rollout: 'Yayılıyor',
rolloutPct: '%{pct} yayılıyor',
approved: 'Yayın bekliyor',
halted: 'Yayılım durduruldu',
reviews: 'Yorumlar',
recent: 'Son 7 günde {n} yeni',
recentNone: 'Son 7 günde yeni yorum yok',
health: 'Çökme ve ANR uyarıları',
crash: 'Çökme oranı kötü davranış eşiğinin üstünde',
anr: 'ANR oranı kötü davranış eşiğinin üstünde',
crashAnr: 'Çökme ve ANR oranları kötü davranış eşiğinin üstünde',
calm: 'Her şey sakin: incelemede, yayılan ya da seni bekleyen bir şey yok.',
noData: 'Henüz mağaza okunmadı. Yenile her uygulamayı okur.',
lastRead: '{ago} okundu',
never: 'hiç',
justNow: 'az önce',
min: '{n} dk önce',
hour: '{n} sa önce',
day: '{n} gün önce',
refresh: 'Yenile',
refreshing: 'Okunuyor…',
openMain: 'storebound\'u aç',
build: 'storebound {version} · {channel} kanalı',
chStable: 'kararlı',
chDev: 'geliştirme',
chBeta: 'beta',
more: 'Diğer',
mute: 'Bildirimleri 1 saat sustur',
unmute: 'Bildirimleri aç',
muted: 'Sessiz',
quit: 'storebound\'dan çık',
openApp: '{name} uygulamasını aç',
asc: 'App Store Connect',
play: 'Play Console',
appStore: 'App Store',
playStore: 'Play',
stars: '5 üzerinden {n} yıldız',
};
export const CARD_TEXT = { en, tr } as const;
export type CardLang = keyof typeof CARD_TEXT;
export function cardT(lang: CardLang, key: CardKey, vars?: Record<string, string | number>): string {
const s = CARD_TEXT[lang][key] ?? en[key];
return vars ? s.replace(/\{(\w+)\}/g, (m, k: string) => (vars[k] === undefined ? m : String(vars[k]))) : s;
}
/** "3 min ago" style age of the last read. */
export function ago(lang: CardLang, at: string | null, now: number): string {
if (!at) return cardT(lang, 'never');
const m = Math.floor((now - Date.parse(at)) / 60_000);
if (!Number.isFinite(m)) return cardT(lang, 'never');
if (m < 1) return cardT(lang, 'justNow');
if (m < 60) return cardT(lang, 'min', { n: m });
if (m < 48 * 60) return cardT(lang, 'hour', { n: Math.floor(m / 60) });
return cardT(lang, 'day', { n: Math.floor(m / 1440) });
}

View file

@ -229,6 +229,19 @@
.ds-menu-k { max-width: 150px; overflow: hidden; text-overflow: ellipsis; margin-left: 18px; color: var(--faint); font-size: var(--ds-t-micro); letter-spacing: .02em; font-variant-numeric: tabular-nums; } .ds-menu-k { max-width: 150px; overflow: hidden; text-overflow: ellipsis; margin-left: 18px; color: var(--faint); font-size: var(--ds-t-micro); letter-spacing: .02em; font-variant-numeric: tabular-nums; }
.ds-menu-sub { width: 12px; height: 12px; color: var(--faint); margin-left: 10px; } .ds-menu-sub { width: 12px; height: 12px; color: var(--faint); margin-left: 10px; }
.ds-menu-sep { height: 1px; margin: 5px 6px; background: var(--ds-stroke); } .ds-menu-sep { height: 1px; margin: 5px 6px; background: var(--ds-stroke); }
/* menu header: the pin button (a normal menu or submenu), a pinned panel's title, unpin, close and drag handle */
.ds-menu-head { display: flex; align-items: center; gap: 2px; height: 24px; padding: 0 0 0 9px; margin-bottom: 1px; }
.ds-menu-head.pinned { cursor: grab; touch-action: none; }
.ds-menu-head.pinned:active { cursor: grabbing; }
.ds-menu-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--ds-t-micro);
font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--faint); }
.ds-menu-btn { flex: none; width: 22px; height: 22px; display: grid; place-items: center; padding: 0; border: 0; border-radius: 6px;
background: transparent; color: var(--faint); cursor: pointer; }
.ds-menu-btn svg { width: 13px; height: 13px; }
.ds-menu-btn:hover, .ds-menu-btn:focus-visible { background: var(--ds-inset); color: var(--ink); outline: none; }
.ds-menu-btn.on { color: var(--accent); }
.ds-menu.pinned { border-color: color-mix(in srgb, var(--accent) 45%, var(--ds-stroke-strong)); transition: opacity 120ms var(--ease); }
.ds-menu-gone { max-width: 240px; padding: 6px 10px 8px; color: var(--muted); font-size: var(--ds-t-micro); white-space: normal; }
@media (prefers-reduced-motion: reduce) { .ds-menu { transition: none; transform: none; } } @media (prefers-reduced-motion: reduce) { .ds-menu { transition: none; transform: none; } }
:root[data-motion="reduce"] .ds-menu { transition: none; transform: none; } :root[data-motion="reduce"] .ds-menu { transition: none; transform: none; }
/* headings focused by code (dialog / wizard step titles) for screen readers: no ring */ /* headings focused by code (dialog / wizard step titles) for screen readers: no ring */
@ -245,3 +258,45 @@
.table-wrap .table tbody tr:hover > :first-child, .ds-table-wrap .table tbody tr:hover > :first-child { background: color-mix(in srgb, var(--tint, var(--accent-solid)) 6%, var(--ds-surface, var(--surface))); } .table-wrap .table tbody tr:hover > :first-child, .ds-table-wrap .table tbody tr:hover > :first-child { background: color-mix(in srgb, var(--tint, var(--accent-solid)) 6%, var(--ds-surface, var(--surface))); }
/* Settings > Appearance > Tables: compact */ /* Settings > Appearance > Tables: compact */
:root[data-density="compact"] .table th, :root[data-density="compact"] .table td { padding-top: 5px; padding-bottom: 5px; padding-left: 8px; padding-right: 8px; font-size: 12.5px; } :root[data-density="compact"] .table th, :root[data-density="compact"] .table td { padding-top: 5px; padding-bottom: 5px; padding-left: 8px; padding-right: 8px; font-size: 12.5px; }
/* ---------- App sections (docs IA): section header, next step, sub views ---------- */
.ds-tab-k { font: 600 10px/1 var(--mono, ui-monospace, monospace); min-width: 16px; height: 16px; display: inline-grid; place-items: center; border-radius: 4px; color: var(--muted); border: 1px solid var(--ds-stroke); background: var(--ds-surface); margin-left: 2px; opacity: .75; }
.ds-tab[aria-selected="true"] .ds-tab-k { opacity: 1; }
.sec-head { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-areas: "t next" "subs subs"; gap: 10px 16px; align-items: center; padding: 2px 4px 4px; }
.sec-head-t { grid-area: t; min-width: 0; }
.sec-head-name { display: flex; align-items: center; gap: 8px; margin: 0; font-size: var(--ds-t-h2, 18px); font-weight: 700; letter-spacing: -.01em; }
.sec-head-name svg { width: 18px; height: 18px; color: var(--tint, var(--accent-solid)); }
.sec-head-for { margin: 2px 0 0; color: var(--muted); font-size: var(--t-meta); }
.sec-next { grid-area: next; display: inline-flex; align-items: center; gap: 8px; padding: 6px 6px 6px 12px; min-height: 32px; box-sizing: border-box; border-radius: var(--ds-r); border: 1px solid var(--ds-stroke); background: var(--ds-surface); font-weight: 600; font-size: var(--t-meta); max-width: 560px; }
.sec-next > svg { width: 15px; height: 15px; flex: none; }
.sec-next-t { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sec-next:not(:has(.btn)) { padding-right: 12px; }
.sec-next.tone-bad { background: var(--bad-bg); color: var(--bad-ink); border-color: transparent; }
.sec-next.tone-warn { background: var(--warn-bg); color: var(--warn-ink); border-color: transparent; }
.sec-next.tone-ok > svg { color: var(--ok-solid); }
.sec-next.tone-info > svg { color: var(--accent-solid); }
.sec-next .btn { flex: none; }
.sec-subs { grid-area: subs; justify-self: start; }
.sec-subs .ed-dot { margin-left: 2px; }
@media (max-width: 1100px) { .sec-head { grid-template-columns: 1fr; grid-template-areas: "t" "next" "subs"; } .sec-next { justify-self: start; } }
/* ---------- Sidebar: attention groups, one status line per app, workspace footer ---------- */
.nav-app.has-line { height: auto; min-height: 40px; padding-top: 4px; padding-bottom: 4px; align-items: center; }
.nav-app .side-t { display: grid; min-width: 0; line-height: 1.2; }
.nav-app .side-n { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.nav-app .side-s { font-size: 11px; font-weight: 500; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.nav-app .side-s.bad { color: var(--bad-ink); } .nav-app .side-s.warn { color: var(--warn-ink); } .nav-app .side-s.ok { color: var(--ok-ink); }
:root[data-theme="dark"] .nav-app .side-s.bad { color: color-mix(in srgb, var(--bad-solid) 70%, white); }
:root[data-theme="dark"] .nav-app .side-s.warn { color: color-mix(in srgb, var(--warn-solid) 70%, white); }
:root[data-theme="dark"] .nav-app .side-s.ok { color: color-mix(in srgb, var(--ok-solid) 70%, white); }
.side-studios { display: flex; flex-wrap: wrap; gap: 4px; margin: 6px 6px 2px; }
.side-studios button { all: unset; cursor: pointer; display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 8px; border-radius: 99px; font-size: 11px; font-weight: 600; color: var(--muted); border: 1px solid var(--line); }
.side-studios button[aria-pressed="true"] { color: var(--ink); background: var(--surface); box-shadow: var(--shadow-1); }
.side-studios button:focus-visible { outline: 2px solid var(--focus); }
.side-ws { display: flex; gap: 2px; padding: 6px 8px; border-top: 1px solid var(--line); }
.side-ws button { all: unset; cursor: pointer; position: relative; flex: 1; height: 30px; display: grid; place-items: center; border-radius: 7px; color: var(--muted); }
.side-ws button:hover { background: var(--hover); color: var(--ink); }
.side-ws button[aria-current="page"] { background: var(--surface); color: var(--ink); box-shadow: var(--shadow-1); }
.side-ws button:focus-visible { outline: 2px solid var(--focus); }
.side-ws svg { width: 17px; height: 17px; }
.side-ws .ws-n { position: absolute; top: 2px; right: 4px; font-size: 9.5px; font-weight: 700; color: var(--muted); font-variant-numeric: tabular-nums; }

View file

@ -9,6 +9,7 @@ import { buildReport } from '../../../../cli/lib/report';
import { buildApps, type Overrides } from '../lib/identity'; import { buildApps, type Overrides } from '../lib/identity';
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model';
import { editableFixture, liveFixture } from './editor-fixtures'; import { editableFixture, liveFixture } from './editor-fixtures';
import { serviceDisabledMessage } from './error-fixtures';
import { APPLE_STATUS_READY, APPLE_STATUS_UNRESOLVED, consolePlan, consoleVerify, ownerDry, PLAY_STATUS } from './submit-fixtures'; import { APPLE_STATUS_READY, APPLE_STATUS_UNRESOLVED, consolePlan, consoleVerify, ownerDry, PLAY_STATUS } from './submit-fixtures';
import { ANALYTICS, ASO, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more'; import { ANALYTICS, ASO, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more';
import { TOOLBOX } from '../../../../cli/lib/desktop-coverage'; import { TOOLBOX } from '../../../../cli/lib/desktop-coverage';
@ -429,6 +430,16 @@ const GAMES_PRISM = {
play: { appId: '123456789012', resource: '123456789012 (android/app/src/main/res/values/games-ids.xml)', leaderboards: 2, achievements: 5, config: { leaderboards: 2, achievements: 5 }, changes: [] }, play: { appId: '123456789012', resource: '123456789012 (android/app/src/main/res/values/games-ids.xml)', leaderboards: 2, achievements: 5, config: { leaderboards: 2, achievements: 5 }, changes: [] },
findings: [{ store: 'apple', level: 'ok', id: 'gc.entitlement', msg: 'com.apple.developer.game-center in ios/App/App/App.entitlements' }, { store: 'play', level: 'ok', id: 'pgs.app-id', msg: 'games_APP_ID 123456789012 matches the config' }], findings: [{ store: 'apple', level: 'ok', id: 'gc.entitlement', msg: 'com.apple.developer.game-center in ios/App/App/App.entitlements' }, { store: 'play', level: 'ok', id: 'pgs.app-id', msg: 'games_APP_ID 123456789012 matches the config' }],
links: [{ label: 'Play Console: Play Games Services configuration', url: 'https://play.google.com/console/u/0/developers/4444/app/9876/play-games-services/setup' }], links: [{ label: 'Play Console: Play Games Services configuration', url: 'https://play.google.com/console/u/0/developers/4444/app/9876/play-games-services/setup' }],
items: [
{ kind: 'leaderboard', id: 'com.example.prismpuddle.best', name: 'Best score', locales: ['en', 'tr', 'ja', 'ar'], ios: true, android: true,
apple: { action: 'keep', changed: [], locales: [{ locale: 'en-US', action: 'keep' }, { locale: 'tr', action: 'keep' }, { locale: 'ja', action: 'keep' }, { locale: 'ar-SA', action: 'keep' }] }, play: { action: 'keep', changed: [] } },
{ kind: 'leaderboard', id: 'com.example.prismpuddle.daily', name: 'Daily puddle', locales: ['en', 'tr'], ios: true, android: true,
apple: { action: 'create', changed: ['referenceName'], locales: [{ locale: 'en-US', action: 'create' }, { locale: 'tr', action: 'create' }] }, play: { action: 'keep', changed: [] } },
...['first-drop', 'ten-levels', 'no-hints', 'rainbow', 'speedrun'].map((k, i) => ({ kind: 'achievement', id: `com.example.prismpuddle.${k}`, name: ['First drop', 'Ten levels', 'No hints', 'Rainbow', 'Speedrun'][i]!, locales: ['en', 'tr', 'ja', 'ar'], points: [10, 20, 30, 20, 20][i], hidden: k === 'speedrun', ios: true, android: true,
apple: { action: 'keep', changed: [], locales: [{ locale: 'en-US', action: 'keep' }] }, play: { action: i === 2 ? 'update' : 'keep', changed: i === 2 ? ['draft.description'] : [] } })),
],
localeMap: { configured: { ar: 'ar-SA' }, suggested: [{ id: 'en', from: 'en-US', to: 'en-GB' }] },
playApiDisabled: null,
}; };
const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data }); const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data });
@ -454,7 +465,17 @@ export function fixtureRead(method: string, id: string, args: Record<string, unk
return method.startsWith('apple.') && r.ok ? { ...r, quota: { store: 'apple', limit: 3600, remaining: 3412 } } : r; return method.startsWith('apple.') && r.ok ? { ...r, quota: { store: 'apple', limit: 3600, remaining: 3412 } } : r;
} }
/** ?blocked: every Play health read fails with Google's SERVICE_DISABLED (the portfolio's "Check again" notice). */
const blockedSwitch = (): boolean => typeof location !== 'undefined' && new URLSearchParams(location.search).has('blocked');
function read(method: string, id: string, args: Record<string, unknown> = {}): ToolResult { function read(method: string, id: string, args: Record<string, unknown> = {}): ToolResult {
const r = read0(method, id, args);
const h = r.data as HealthSnapshot | undefined;
if (method !== 'health' || !blockedSwitch() || !h?.play) return r;
return { ...r, data: { ...h, play: { error: serviceDisabledMessage('com.example.app') } } };
}
function read0(method: string, id: string, args: Record<string, unknown> = {}): ToolResult {
if (method === 'health.issue') return ok(method, ISSUE_SAMPLE(args)); if (method === 'health.issue') return ok(method, ISSUE_SAMPLE(args));
if (id.startsWith('store:')) { if (id.startsWith('store:')) {
const play = /android:/.test(id); const play = /android:/.test(id);
@ -534,7 +555,12 @@ 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 }); } for (const line of lines) { await sleep(260); if (job) emit('sidecar-progress', { params: { requestId: 1, line, stream: 'stderr' }, job }); }
} }
/** Every fake-host call, for checks that count them (window.__fakeCalls: "cmd method target args"). */
const fakeCalls: string[] = [];
if (typeof window !== 'undefined') (window as unknown as { __fakeCalls: string[] }).__fakeCalls = fakeCalls;
export async function mockInvoke<T>(cmd: string, a: Record<string, unknown>): Promise<T> { export async function mockInvoke<T>(cmd: string, a: Record<string, unknown>): Promise<T> {
fakeCalls.push([cmd, a.method ?? '', a.projectId ?? a.id ?? '', JSON.stringify((a.params as { args?: unknown } | null)?.args ?? a.live ?? '')].join(' '));
const r = await answer(cmd, a); const r = await answer(cmd, a);
return r as T; return r as T;
} }

View file

@ -153,7 +153,10 @@ export const en = {
'phase.releasedUnknown': "Couldn't check the store page", 'phase.releasedUnknown': "Couldn't check the store page",
'phase.pageUnknown': "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.pageStale': "couldn't check the store page, as of {when}",
'phase.reviewLive': 'In review (live: {version})', 'phase.reviewLive': 'Not live yet (live: {version}): in review or blocked before review',
'phase.playPending': 'Not live yet: in review or blocked before review',
'roll.publishReady': 'If the release is approved, publish it in Publishing overview ("Publish N changes"). The agent prepares it with `{cmd}`; the final press is for the owner.',
'roll.publishOpen': 'Open Publishing overview',
'phase.reviewManaged': 'In review / ready to publish (managed publishing)', 'phase.reviewManaged': 'In review / ready to publish (managed publishing)',
'phase.rejected': 'Rejected', 'phase.rejected': 'Rejected',
'phase.testing': 'Testing', 'phase.testing': 'Testing',
@ -917,6 +920,9 @@ export const en = {
'read.couldNotRefresh': "couldn't refresh: {reason}", 'read.couldNotRefresh': "couldn't refresh: {reason}",
'read.refresh': "Refresh", 'read.refresh': "Refresh",
'read.waiting': "Reading…", 'read.waiting': "Reading…",
'read.justNow': "read just now",
'read.paused': "store limit: waits until {time}",
'read.busyShared': "Already reading: this joins the read in progress",
'reader.progress': "Reading {done} of {total}", 'reader.progress': "Reading {done} of {total}",
'reader.upToDate': "Everything read", 'reader.upToDate': "Everything read",
'reader.off': "Auto-read is off", 'reader.off': "Auto-read is off",
@ -971,7 +977,9 @@ export const en = {
'set.channel': 'Channel', 'set.channel': 'Channel',
'set.stable': 'Stable', 'set.stable': 'Stable',
'set.beta': 'Beta', 'set.beta': 'Beta',
'set.updatesText': 'Updates come from storebound.dev and are signed; the app checks the signature before it replaces anything, and installs only when you press Install. Nothing is checked in the background.', 'set.dev': 'Dev (every change)',
'set.devToStable': 'This is the dev build {version}: it stays until a stable release is newer (no downgrade).',
'set.updatesText': 'Updates come from storebound.dev and are signed; the app checks the signature before it replaces anything. It looks for a newer version of the chosen channel at start, every 15 minutes and after sleep, and installs it in the background (not while you work in this window). Stable follows the npm releases; Dev gets every change on main.',
'set.updateCheck': 'Check for updates', 'set.updateCheck': 'Check for updates',
'set.updateChecking': 'Checking…', 'set.updateChecking': 'Checking…',
'set.updateNone': 'storebound {version} is the newest version on the {channel} channel.', 'set.updateNone': 'storebound {version} is the newest version on the {channel} channel.',
@ -2052,6 +2060,12 @@ export const en = {
// context menus (ui/ContextMenu.tsx) // context menus (ui/ContextMenu.tsx)
'cm.cut': "Cut", 'cm.cut': "Cut",
'cm.pin': "Pin: keeps this menu open",
'cm.unpin': "Unpin",
'cm.closePanel': "Close",
'cm.gone': "Gone: what this menu was for is not on screen now.",
'cm.menu': "Menu",
'cm.tearOff': "Ctrl+click or middle-click: pin this submenu",
'cm.copy': "Copy", 'cm.copy': "Copy",
'cm.paste': "Paste", 'cm.paste': "Paste",
'cm.selectAll': "Select all", 'cm.selectAll': "Select all",
@ -2072,6 +2086,13 @@ export const en = {
'cm.ignoredNoReads': "Ignored apps are not read", 'cm.ignoredNoReads': "Ignored apps are not read",
'cm.ignore': "Ignore", 'cm.ignore': "Ignore",
'acct.devId': 'Play developer id {id}', 'acct.devId': 'Play developer id {id}',
'acct.viaBroker': 'tokens from the credential broker',
'acct.viaFile': 'local key file',
'acct.grantsTitle': 'Play permissions on the credential broker',
'acct.grantsOk': 'everything storebound needs',
'acct.grantsMissing': 'missing: {list}',
'acct.grantsNone': 'no permission data',
'acct.notRegistered': 'not registered on the broker',
'acct.noDevId': 'no Play developer id', 'acct.noDevId': 'no Play developer id',
'acct.devIdLabel': 'Play developer account id', 'acct.devIdLabel': 'Play developer account id',
'acct.devIdHint': "The digits after /developers/ in the Play Console address. With it, Play Console links open each app's own page; the CLI uses it too.", 'acct.devIdHint': "The digits after /developers/ in the Play Console address. With it, Play Console links open each app's own page; the CLI uses it too.",
@ -2109,4 +2130,106 @@ export const en = {
'cm.copyPrincipal': "Service account / key", 'cm.copyPrincipal': "Service account / key",
'cm.copyProfile': "Profile name", 'cm.copyProfile': "Profile name",
'cm.openAccounts': "Open Studios & accounts", 'cm.openAccounts': "Open Studios & accounts",
"sec.release": "Release",
"sec.store": "Store page",
"sec.revenue": "Revenue",
"sec.players": "Players",
"sec.health": "Health",
"sec.release.for": "Get a version to players on both stores: builds, TestFlight, review and rollout.",
"sec.store.for": "What people see on the store: texts per language, screenshots and app details.",
"sec.revenue.for": "What the app sells and for how much: in-app products, subscriptions and prices.",
"sec.players.for": "What players say, and for games what they can earn: reviews, Game Center, Play Games.",
"sec.health.for": "Is the app well and ready: crashes and ANRs, growth, checks to fix first, more tools.",
"sec.views": "{section} views",
"tab.games": "Game services",
"next.open": "Open {where}",
"next.rejected": "{version} was rejected on {store}",
"next.halted": "{version} is halted on {store}",
"next.blockers": "{count} blockers before submit",
"next.blockers_one": "1 blocker before submit",
"next.rollout": "{version} is rolling out at {share}",
"next.approved": "{version} is approved: release it",
"next.submit": "Submit {version} for review",
"next.review": "{version} is in review",
"next.managed": "{version} waits in Publishing overview (managed publishing)",
"next.upload": "Upload a first build",
"next.live": "Live: {version}",
"next.notRead": "Release state shows once the stores are read",
"next.storeLive": "The live store page, read from the stores",
"next.listingProblems": "{count} listing problems",
"next.listingProblems_one": "1 listing problem",
"next.unsaved": "{count} unsaved edits",
"next.unsaved_one": "1 unsaved edit",
"next.listingsUnread": "Listings not checked yet",
"next.storeOk": "Store page in step with the config",
"next.catalogDiff": "{count} products differ between the stores",
"next.catalogDiff_one": "1 product differs between the stores",
"next.noProducts": "No products yet: add one",
"next.products": "{products} products · {subs} subscriptions",
"next.reviews": "{count} reviews without a reply",
"next.reviews_one": "1 review without a reply",
"next.reviewsUnread": "See what players say",
"next.reviewsOk": "All reviews answered",
"next.gamesApiOff": "Play Games Services API is off",
"next.gamesBlockers": "{count} game services blockers",
"next.gamesBlockers_one": "1 game services blocker",
"next.gamesSync": "Game services: {count} changes to sync",
"next.gamesSync_one": "Game services: 1 change to sync",
"next.fixFirst": "{count} problems to fix first",
"next.fixFirst_one": "1 problem to fix first",
"next.warnings": "{count} warnings to look at",
"next.warnings_one": "1 warning to look at",
"next.healthOk": "No problems found",
"side.gAttention": "Needs attention",
"side.gProgress": "In progress",
"side.gLive": "Live",
"side.gDraft": "Not on a store yet",
"side.missing": "Folder missing",
"side.rejected": "Rejected · {what}",
"side.halted": "Halted · {what}",
"side.blockers": "{count} blockers",
"side.blockers_one": "1 blocker",
"side.rollout": "Rollout {share} · {what}",
"side.review": "In review · {what}",
"side.approved": "Approved · {what}",
"side.draft": "Draft · {what}",
"side.live": "Live · {version}",
"side.liveWarn": "Live · {version} · {count} warnings",
"side.liveWarn_one": "Live · {version} · 1 warning",
"side.storeOnly": "Store only · not read yet",
"side.notRead": "Not read yet",
"side.warnings": "{count} warnings",
"side.warnings_one": "1 warning",
"side.notOnStore": "No store version yet",
"side.ignored": "Ignored",
"side.studioFilter": "Show apps of a studio",
"side.allStudios": "All",
"games.keep": "In step",
"games.update": "Differs",
"games.create": "Missing",
"games.notOnStore": "Not on this store",
"games.notListed": "Not planned",
"games.notRead": "Not read",
"games.item": "Item",
"games.name": "Name",
"games.points": "Points",
"games.languages": "Languages",
"games.leaderboard": "Leaderboard",
"games.achievement": "Achievement",
"games.hidden": "hidden until earned",
"games.localeChanges": "Game Center languages: {list}",
"games.checkAgain": "Check again",
"games.apiOffTitle": "Play Games Services API is off.",
"games.apiOffText": "Turn on {api} in the service account's Google Cloud project, wait a minute, then check again.",
"games.itemsTitle": "Leaderboards and achievements",
"games.itemsSub": "One list in the config, mapped to both stores: each store's state against the config.",
"games.refresh": "Read again",
"games.noItems": "No leaderboards or achievements in the config yet (games.leaderboards, games.achievements).",
"games.notReadYet": "Reading game services…",
"games.images": "Images of leaderboards and achievements are added in the consoles; on Play the existing icon is kept on every sync.",
"games.localeMap": "Game Center locale map",
"games.localeMapSub": "Config language to the locale the live Game Center uses (games.localeMap).",
"games.mapSet": "Set",
"games.mapSuggested": "Suggested",
"games.mapHint": "Add to games.localeMap: {entries}",
} as const; } as const;

View file

@ -155,7 +155,10 @@ export const tr: Record<keyof typeof en, string> = {
'phase.releasedUnknown': 'Mağaza sayfası kontrol edilemedi', 'phase.releasedUnknown': 'Mağaza sayfası kontrol edilemedi',
'phase.pageUnknown': 'Mağaza sayfası kontrol edilemedi', 'phase.pageUnknown': 'Mağaza sayfası kontrol edilemedi',
'phase.pageStale': 'mağaza sayfası kontrol edilemedi, {when} itibarıyla', 'phase.pageStale': 'mağaza sayfası kontrol edilemedi, {when} itibarıyla',
'phase.reviewLive': 'İncelemede (yayında: {version})', 'phase.reviewLive': 'Henüz yayında değil (yayında: {version}): incelemede ya da incelemeden önce takıldı',
'phase.playPending': 'Henüz yayında değil: incelemede ya da incelemeden önce takıldı',
'roll.publishReady': 'Sürüm onaylandıysa Yayınlama özetinde yayınlayın ("Publish N changes"). Ajan `{cmd}` ile hazırlar; son basış sahibine aittir.',
'roll.publishOpen': 'Yayınlama özetini aç',
'phase.reviewManaged': 'İncelemede / yayına hazır (yönetilen yayınlama)', 'phase.reviewManaged': 'İncelemede / yayına hazır (yönetilen yayınlama)',
'phase.rejected': 'Reddedildi', 'phase.rejected': 'Reddedildi',
'phase.testing': 'Testte', 'phase.testing': 'Testte',
@ -919,6 +922,9 @@ export const tr: Record<keyof typeof en, string> = {
'read.couldNotRefresh': "yenilenemedi: {reason}", 'read.couldNotRefresh': "yenilenemedi: {reason}",
'read.refresh': "Yenile", 'read.refresh': "Yenile",
'read.waiting': "Okunuyor…", 'read.waiting': "Okunuyor…",
'read.justNow': "az önce okundu",
'read.paused': "mağaza sınırı: {time} saatine kadar bekliyor",
'read.busyShared': "Zaten okunuyor: bu, süren okumaya katılır",
'reader.progress': "{total} okumadan {done} tamam", 'reader.progress': "{total} okumadan {done} tamam",
'reader.upToDate': "Her şey okundu", 'reader.upToDate': "Her şey okundu",
'reader.off': "Otomatik okuma kapalı", 'reader.off': "Otomatik okuma kapalı",
@ -973,7 +979,9 @@ export const tr: Record<keyof typeof en, string> = {
'set.channel': 'Kanal', 'set.channel': 'Kanal',
'set.stable': 'Kararlı', 'set.stable': 'Kararlı',
'set.beta': 'Beta', 'set.beta': 'Beta',
'set.updatesText': 'Güncellemeler storebound.dev\'den imzalı gelir; uygulama bir şeyi değiştirmeden önce imzayı denetler ve yalnızca siz Yükle\'ye bastığınızda yükler. Arka planda denetim yapılmaz.', 'set.dev': 'Geliştirme (her değişiklik)',
'set.devToStable': 'Bu, geliştirme sürümü {version}: daha yeni bir kararlı sürüm çıkana kadar kalır (eski sürüme dönülmez).',
'set.updatesText': 'Güncellemeler storebound.dev\'den imzalı gelir; uygulama bir şeyi değiştirmeden önce imzayı denetler. Seçili kanalda daha yeni bir sürümü açılışta, 15 dakikada bir ve uykudan sonra arar, arka planda yükler (siz bu pencerede çalışırken değil). Kararlı, npm sürümlerini izler; Geliştirme, main\'deki her değişikliği alır.',
'set.updateCheck': 'Güncellemeleri denetle', 'set.updateCheck': 'Güncellemeleri denetle',
'set.updateChecking': 'Denetleniyor…', 'set.updateChecking': 'Denetleniyor…',
'set.updateNone': 'storebound {version}, {channel} kanalındaki en yeni sürüm.', 'set.updateNone': 'storebound {version}, {channel} kanalındaki en yeni sürüm.',
@ -2054,6 +2062,12 @@ export const tr: Record<keyof typeof en, string> = {
// context menus (ui/ContextMenu.tsx) // context menus (ui/ContextMenu.tsx)
'cm.cut': "Kes", 'cm.cut': "Kes",
'cm.pin': "Sabitle: menü açık kalır",
'cm.unpin': "Sabitlemeyi kaldır",
'cm.closePanel': "Kapat",
'cm.gone': "Yok: bu menünün ait olduğu şey şu an ekranda değil.",
'cm.menu': "Menü",
'cm.tearOff': "Ctrl+tık veya orta tık: bu alt menüyü sabitle",
'cm.copy': "Kopyala", 'cm.copy': "Kopyala",
'cm.paste': "Yapıştır", 'cm.paste': "Yapıştır",
'cm.selectAll': "Tümünü seç", 'cm.selectAll': "Tümünü seç",
@ -2074,6 +2088,13 @@ export const tr: Record<keyof typeof en, string> = {
'cm.ignoredNoReads': "Yok sayılan uygulamalar okunmaz", 'cm.ignoredNoReads': "Yok sayılan uygulamalar okunmaz",
'cm.ignore': "Yok say", 'cm.ignore': "Yok say",
'acct.devId': 'Play geliştirici kimliği {id}', 'acct.devId': 'Play geliştirici kimliği {id}',
'acct.viaBroker': 'jetonlar kimlik aracısından',
'acct.viaFile': 'yerel anahtar dosyası',
'acct.grantsTitle': 'Kimlik aracısındaki Play izinleri',
'acct.grantsOk': 'storebound için gereken her şey var',
'acct.grantsMissing': 'eksik: {list}',
'acct.grantsNone': 'izin bilgisi yok',
'acct.notRegistered': 'aracıda kayıtlı değil',
'acct.noDevId': 'Play geliştirici kimliği yok', 'acct.noDevId': 'Play geliştirici kimliği yok',
'acct.devIdLabel': 'Play geliştirici hesabı kimliği', 'acct.devIdLabel': 'Play geliştirici hesabı kimliği',
'acct.devIdHint': 'Play Console adresinde /developers/ sonrasındaki rakamlar. Girilince Play Console bağlantıları her uygulamanın kendi sayfasını açar; CLI de kullanır.', 'acct.devIdHint': 'Play Console adresinde /developers/ sonrasındaki rakamlar. Girilince Play Console bağlantıları her uygulamanın kendi sayfasını açar; CLI de kullanır.',
@ -2111,4 +2132,106 @@ export const tr: Record<keyof typeof en, string> = {
'cm.copyPrincipal': "Hizmet hesabı / anahtar", 'cm.copyPrincipal': "Hizmet hesabı / anahtar",
'cm.copyProfile': "Profil adı", 'cm.copyProfile': "Profil adı",
'cm.openAccounts': "Stüdyolar ve hesapları aç", 'cm.openAccounts': "Stüdyolar ve hesapları aç",
"sec.release": "Yayın",
"sec.store": "Mağaza sayfası",
"sec.revenue": "Gelir",
"sec.players": "Oyuncular",
"sec.health": "Sağlık",
"sec.release.for": "Bir sürümü iki mağazada oyunculara ulaştır: build, TestFlight, inceleme ve dağıtım.",
"sec.store.for": "Mağazada insanların gördüğü: dile göre metinler, ekran görüntüleri ve uygulama bilgileri.",
"sec.revenue.for": "Uygulamanın sattıkları ve fiyatları: uygulama içi ürünler, abonelikler ve fiyatlar.",
"sec.players.for": "Oyuncuların söyledikleri ve oyunlarda kazanabilecekleri: yorumlar, Game Center, Play Games.",
"sec.health.for": "Uygulama sağlıklı ve hazır mı: çökmeler ve ANR, büyüme, önce düzeltilecek kontroller, diğer araçlar.",
"sec.views": "{section} görünümleri",
"tab.games": "Oyun servisleri",
"next.open": "{where} aç",
"next.rejected": "{version}, {store} tarafından reddedildi",
"next.halted": "{version}, {store} üzerinde durduruldu",
"next.blockers": "Göndermeden önce {count} engel",
"next.blockers_one": "Göndermeden önce 1 engel",
"next.rollout": "{version} dağıtımı {share} seviyesinde",
"next.approved": "{version} onaylandı: yayınla",
"next.submit": "{version} sürümünü incelemeye gönder",
"next.review": "{version} incelemede",
"next.managed": "{version} Yayınlama özeti'nde bekliyor (yönetilen yayınlama)",
"next.upload": "İlk build'i yükle",
"next.live": "Yayında: {version}",
"next.notRead": "Yayın durumu mağazalar okununca görünür",
"next.storeLive": "Mağazalardan okunan canlı mağaza sayfası",
"next.listingProblems": "{count} mağaza metni sorunu",
"next.listingProblems_one": "1 mağaza metni sorunu",
"next.unsaved": "{count} kaydedilmemiş düzenleme",
"next.unsaved_one": "1 kaydedilmemiş düzenleme",
"next.listingsUnread": "Mağaza metinleri henüz kontrol edilmedi",
"next.storeOk": "Mağaza sayfası yapılandırmayla uyumlu",
"next.catalogDiff": "{count} ürün mağazalar arasında farklı",
"next.catalogDiff_one": "1 ürün mağazalar arasında farklı",
"next.noProducts": "Henüz ürün yok: bir tane ekle",
"next.products": "{products} ürün · {subs} abonelik",
"next.reviews": "{count} yorum yanıtsız",
"next.reviews_one": "1 yorum yanıtsız",
"next.reviewsUnread": "Oyuncuların söylediklerine bak",
"next.reviewsOk": "Tüm yorumlar yanıtlandı",
"next.gamesApiOff": "Play Games Services API kapalı",
"next.gamesBlockers": "{count} oyun servisi engeli",
"next.gamesBlockers_one": "1 oyun servisi engeli",
"next.gamesSync": "Oyun servisleri: eşitlenecek {count} değişiklik",
"next.gamesSync_one": "Oyun servisleri: eşitlenecek 1 değişiklik",
"next.fixFirst": "Önce düzeltilecek {count} sorun",
"next.fixFirst_one": "Önce düzeltilecek 1 sorun",
"next.warnings": "Bakılacak {count} uyarı",
"next.warnings_one": "Bakılacak 1 uyarı",
"next.healthOk": "Sorun bulunmadı",
"side.gAttention": "İlgi bekliyor",
"side.gProgress": "Sürüyor",
"side.gLive": "Yayında",
"side.gDraft": "Henüz mağazada değil",
"side.missing": "Klasör bulunamadı",
"side.rejected": "Reddedildi · {what}",
"side.halted": "Durduruldu · {what}",
"side.blockers": "{count} engel",
"side.blockers_one": "1 engel",
"side.rollout": "Dağıtım {share} · {what}",
"side.review": "İncelemede · {what}",
"side.approved": "Onaylandı · {what}",
"side.draft": "Taslak · {what}",
"side.live": "Yayında · {version}",
"side.liveWarn": "Yayında · {version} · {count} uyarı",
"side.liveWarn_one": "Yayında · {version} · 1 uyarı",
"side.storeOnly": "Yalnız mağaza · henüz okunmadı",
"side.notRead": "Henüz okunmadı",
"side.warnings": "{count} uyarı",
"side.warnings_one": "1 uyarı",
"side.notOnStore": "Henüz mağaza sürümü yok",
"side.ignored": "Yok sayıldı",
"side.studioFilter": "Bir stüdyonun uygulamalarını göster",
"side.allStudios": "Tümü",
"games.keep": "Uyumlu",
"games.update": "Farklı",
"games.create": "Eksik",
"games.notOnStore": "Bu mağazada değil",
"games.notListed": "Planlanmadı",
"games.notRead": "Okunmadı",
"games.item": "Öğe",
"games.name": "Ad",
"games.points": "Puan",
"games.languages": "Diller",
"games.leaderboard": "Skor tablosu",
"games.achievement": "Başarım",
"games.hidden": "kazanılana kadar gizli",
"games.localeChanges": "Game Center dilleri: {list}",
"games.checkAgain": "Yeniden kontrol et",
"games.apiOffTitle": "Play Games Services API kapalı.",
"games.apiOffText": "Hizmet hesabının Google Cloud projesinde {api} açın, bir dakika bekleyin, sonra yeniden kontrol edin.",
"games.itemsTitle": "Skor tabloları ve başarımlar",
"games.itemsSub": "Yapılandırmada tek liste, iki mağazaya eşlenir: her mağazanın yapılandırmaya göre durumu.",
"games.refresh": "Yeniden oku",
"games.noItems": "Yapılandırmada henüz skor tablosu veya başarım yok (games.leaderboards, games.achievements).",
"games.notReadYet": "Oyun servisleri okunuyor…",
"games.images": "Skor tablosu ve başarım görselleri konsollarda eklenir; Play'de mevcut simge her eşitlemede korunur.",
"games.localeMap": "Game Center dil eşlemesi",
"games.localeMapSub": "Yapılandırma dilinden canlı Game Center'ın kullandığı dile (games.localeMap).",
"games.mapSet": "Ayarlı",
"games.mapSuggested": "Önerilen",
"games.mapHint": "games.localeMap'e ekleyin: {entries}",
}; };

View file

@ -2,7 +2,7 @@
// inbox stats, catalog parity matrix, the portfolio's "needs attention" list, and the command palette matcher. // 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". // "Unknown, never false": every derivation keeps "not read" apart from "none" / "ok".
import { plainError } from '../../../../cli/lib/google-errors'; import { plainError } from '../../../../cli/lib/google-errors';
import type { AppStatus, ProjectSummary } from '../api'; import type { AppStatus, ProjectSummary, StoreRelease } from '../api';
import { t } from '../i18n'; import { t } from '../i18n';
import type { Tone } from '../../../../cli/lib/train'; import type { Tone } from '../../../../cli/lib/train';
@ -138,7 +138,7 @@ export function parityMatrix(s: ProjectSummary | null, diff: CatalogDiff | null)
// ---- Portfolio: needs attention ---- // ---- Portfolio: needs attention ----
export interface Attention { app: string; projectId: string; tone: Tone; text: string; hint?: string; tab?: 'releases' | 'catalog' | 'listings' | 'health' | 'reviews' | 'testflight' | 'checks' } export interface Attention { app: string; projectId: string; tone: Tone; text: string; hint?: string; tab?: 'releases' | 'catalog' | 'listings' | 'health' | 'reviews' | 'testflight' | 'checks' | 'games' }
export function attention(projectId: string, name: string, e: AppStatus | undefined, live: AppStatus | undefined, health?: HealthSnapshot | null): Attention[] { export function attention(projectId: string, name: string, e: AppStatus | undefined, live: AppStatus | undefined, health?: HealthSnapshot | null): Attention[] {
const out: Attention[] = []; const out: Attention[] = [];
@ -203,3 +203,46 @@ export function hueOf(name: string): number {
for (const c of name) h = (h * 31 + c.charCodeAt(0)) >>> 0; for (const c of name) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return h % 360; return h % 360;
} }
// ---- App kind and the sidebar ----
const PLAY_GAME_CATS = ['Action', 'Adventure', 'Arcade', 'Board', 'Card', 'Casino', 'Casual', 'Educational', 'Music', 'Puzzle', 'Racing', 'Role Playing', 'Simulation', 'Sports', 'Strategy', 'Trivia', 'Word'];
/** A game: profile game, a games section in the config, or a Play game category. */
export function isGameSummary(s: ProjectSummary | null | undefined): boolean {
if (!s) return false;
return s.profile === 'game' || !!s.games || PLAY_GAME_CATS.includes(s.playRelease?.category ?? '');
}
export type SideGroup = 'attention' | 'progress' | 'live' | 'draft';
export interface SideStatus { group: SideGroup; text: string; tone: Tone }
/** One sidebar row's group and status line: the one thing worth knowing about the app (docs IA). */
export function sideStatus(o: { att: Attention[]; all: StoreRelease[]; read: boolean; missing: boolean; storeOnly: boolean }): SideStatus {
const sn = (r: StoreRelease) => `${r.store === 'ios' ? 'iOS' : 'Play'} ${r.version ?? ''}`.trim();
if (o.missing) return { group: 'attention', text: t('side.missing'), tone: 'bad' };
const rej = o.all.find(r => r.phase === 'rejected');
if (rej) return { group: 'attention', text: t('side.rejected', { what: sn(rej) }), tone: 'bad' };
const halted = o.all.find(r => r.phase === 'halted');
if (halted) return { group: 'attention', text: t('side.halted', { what: sn(halted) }), tone: 'bad' };
const bad = o.att.filter(a => a.tone === 'bad').length;
if (bad) return { group: 'attention', text: t('side.blockers', { count: bad }), tone: 'bad' };
const crash = o.att.find(a => a.tab === 'health');
if (crash) return { group: 'attention', text: crash.text, tone: crash.tone };
const rolling = o.all.find(r => r.phase === 'rollout' && r.fraction !== null && r.fraction < 1);
if (rolling) return { group: 'progress', text: t('side.rollout', { share: `${Math.round((rolling.fraction ?? 0) * 100)} %`, what: sn(rolling) }), tone: 'info' };
const review = o.all.find(r => r.phase === 'review' || r.phase === 'sent');
if (review) return { group: 'progress', text: t('side.review', { what: sn(review) }), tone: 'info' };
const approved = o.all.find(r => r.phase === 'approved');
if (approved) return { group: 'progress', text: t('side.approved', { what: sn(approved) }), tone: 'info' };
const live = o.all.filter(r => r.phase === 'live' || r.phase === 'released' || r.phase === 'rollout');
const draft = o.all.find(r => r.phase === 'draft' || r.phase === 'testing');
if (draft && !live.length) return { group: 'progress', text: t('side.draft', { what: sn(draft) }), tone: 'neutral' };
const warn = o.att.filter(a => a.tone === 'warn').length;
if (live.length) {
const vs = [...new Set(live.map(r => r.version).filter(Boolean))];
return { group: 'live', text: warn ? t('side.liveWarn', { version: vs.join(' / '), count: warn }) : t('side.live', { version: vs.join(' / ') }), tone: warn ? 'warn' : 'ok' };
}
if (!o.read) return { group: o.storeOnly ? 'live' : 'draft', text: o.storeOnly ? t('side.storeOnly') : t('side.notRead'), tone: 'neutral' };
return { group: 'draft', text: warn ? t('side.warnings', { count: warn }) : t('side.notOnStore'), tone: warn ? 'warn' : 'neutral' };
}
export const SIDE_GROUPS: SideGroup[] = ['attention', 'progress', 'live', 'draft'];

View file

@ -65,7 +65,7 @@ export function normalizeSettings(v: unknown): Settings {
lowReviews: pick(n.lowReviews, d.notify.lowReviews, isBool), crash: pick(n.crash, d.notify.crash, isBool), lowReviews: pick(n.lowReviews, d.notify.lowReviews, isBool), crash: pick(n.crash, d.notify.crash, isBool),
quietHours: { enabled: pick(q.enabled, d.notify.quietHours.enabled, isBool), from: pick(q.from, d.notify.quietHours.from, isHm), to: pick(q.to, d.notify.quietHours.to, isHm) }, quietHours: { enabled: pick(q.enabled, d.notify.quietHours.enabled, isBool), from: pick(q.from, d.notify.quietHours.from, isHm), to: pick(q.to, d.notify.quietHours.to, isHm) },
}, },
channel: v.channel === 'beta' ? 'beta' : 'stable', channel: v.channel === 'dev' || v.channel === 'beta' ? v.channel : 'stable',
}; };
} }

View file

@ -0,0 +1,283 @@
// The one read registry of the window: every read button, notice, card, the background reader, the tray and Ctrl+K
// ask it, never the host directly. Pure logic over lib/scheduler.ts (tests/read-registry.test.ts).
//
// - Canonical key: target + method + args (lib/freshness.ts readKey), or a named key for reads without a target
// (the portfolio, an account's app list, an account check).
// - Single-flight: a read whose key is in flight (queued or running) is joined: the caller gets the same promise, its
// result or its error. No second host call, ever.
// - Scope: a read carries tags ('all', 'app:<target>', 'import', 'account:<id>' ...). A query asks by keys and / or
// tags; it is busy when any in-flight read has one of its keys, one of its tags, or COVERS one of its keys.
// - Covering: a broad read (Refresh all, Import all) is a group: it lists the narrow keys it stands for. While it runs
// those keys show busy everywhere and a click on one of them waits for the group, then reads only if the group did
// not (it usually did, so the click costs nothing). A narrow read in flight makes every broad button whose tag it
// carries busy too (decided with the owner: overlapping buttons are all busy and disabled; one click never starts a
// duplicate, it joins).
// - Just now: a read that finished less than `justNowMs` ago is not run again by a second click: the caller gets the
// last result ("read just now"). A write's invalidation drops that memo for the keys it touched.
// - Rate limits stay the scheduler's (lanes per store, spacing and the App Store Connect quota per account, shared
// 429 backoff); the registry reports a paused account on every query that uses it.
import { type Clock, type Lane, type Priority, type ReadScheduler, realClock } from './scheduler';
export interface ReadSpec<R> {
key: string;
/** Scopes the read belongs to: a query by any of these tags sees it. */
tags?: string[];
lanes: Lane[];
/** Credentials it uses ("apple:<account>", "play:<account>"): their quota pause shows on its buttons. */
accounts: string[];
priority: Priority;
run: () => Promise<R>;
/** Stops a running read (the host job). */
cancel?: () => void;
}
export interface GroupSpec<R> {
key: string;
tags?: string[];
/** Narrow keys this read stands for until it releases them (release()) or ends. */
covers: string[];
run: (g: GroupHandle) => Promise<R>;
}
export interface GroupHandle {
/** This key is no longer the group's (read by its own entry now, or skipped as fresh). */
release(key: string): void;
}
export type ReadQuery = string | { keys?: string[]; tags?: string[] };
export interface ReadStatus {
/** Something this query overlaps is queued or running. */
busy: boolean;
/** How many in-flight reads overlap it. */
inFlight: number;
/** Every key of the query finished successfully less than justNowMs ago. */
justNow: boolean;
/** Oldest last-finished time over the query's keys (epoch ms), null when one never finished here. */
lastAt: number | null;
/** The last error of a single-key query (cleared by its next success). */
error: string | null;
/** An account the query uses waits on a quota pause or a 429 backoff until this time (epoch ms). */
pausedUntil: number | null;
}
export type ReadEvent = { kind: 'start' } | { kind: 'done'; result: unknown } | { kind: 'error'; error: unknown };
interface Entry {
key: string;
tags: Set<string>;
covers: Set<string>;
accounts: string[];
promise: Promise<unknown>;
cancel?: () => void;
group: boolean;
}
interface Done { at: number; ok: boolean; result?: unknown; error?: string }
export interface RegistryOptions {
justNowMs?: number;
clock?: Clock;
/** Per-key start / done / error, for the cards' read bus (only real reads: never a join or a just-now answer). */
onEvent?: (key: string, e: ReadEvent) => void;
}
const errText = (e: unknown): string => (e instanceof Error ? e.message : typeof e === 'string' ? e : (e as { message?: string })?.message ?? String(e));
export class ReadRegistry {
private entries = new Map<string, Entry>();
private done = new Map<string, Done>();
private accountsOf = new Map<string, string[]>();
private listeners = new Set<() => void>();
private ver = 0;
private justNowMs: number;
private clock: Clock;
private onEvent?: RegistryOptions['onEvent'];
private expiry: unknown = null;
constructor(private sched: ReadScheduler, o: RegistryOptions = {}) {
this.justNowMs = o.justNowMs ?? 20_000;
this.clock = o.clock ?? realClock;
this.onEvent = o.onEvent;
// a quota pause or backoff of the scheduler changes what the buttons say
sched.subscribe(() => this.emit());
}
subscribe = (fn: () => void): (() => void) => { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; };
/** Changes on every start, finish, cover release, invalidation and scheduler change (useSyncExternalStore). */
version = (): number => this.ver;
/** True when this exact key is in flight (its own read, or a group that covers it). */
active(key: string): boolean {
if (this.entries.has(key)) return true;
for (const e of this.entries.values()) if (e.covers.has(key)) return true;
return false;
}
/** The last result of a key that finished less than justNowMs ago (undefined when there is none). */
recent(key: string): unknown {
const d = this.done.get(key);
return d?.ok && this.clock.now() - d.at < this.justNowMs ? d.result : undefined;
}
/**
* Reads one key: joins it when it is in flight, waits for a group that covers it, answers a just-finished read
* from its memo (unless `force`), else runs it through the scheduler.
*/
read<R>(spec: ReadSpec<R>, o: { force?: boolean } = {}): Promise<R> {
this.accountsOf.set(spec.key, spec.accounts);
const own = this.entries.get(spec.key);
if (own) {
// a higher priority asker raises the queued read
if (!own.group) this.sched.enqueue({ key: spec.key, lanes: spec.lanes, accounts: spec.accounts, priority: spec.priority, run: spec.run as () => Promise<unknown> }).catch(() => {});
return own.promise as Promise<R>;
}
for (const e of this.entries.values()) {
if (e.covers.has(spec.key)) {
// the broad read stands for this key: wait for it, then read only what it did not
return e.promise.then(() => undefined, () => undefined).then(() => this.read(spec, { force: false }));
}
}
const d = this.done.get(spec.key);
if (!o.force && d?.ok && this.clock.now() - d.at < this.justNowMs) return Promise.resolve(d.result as R);
const p = this.sched.enqueue<R>({ key: spec.key, lanes: spec.lanes, accounts: spec.accounts, priority: spec.priority, run: spec.run });
const entry: Entry = { key: spec.key, tags: new Set(spec.tags ?? []), covers: new Set(), accounts: spec.accounts, promise: p, cancel: spec.cancel, group: false };
this.entries.set(spec.key, entry);
this.onEvent?.(spec.key, { kind: 'start' });
this.emit();
p.then(r => this.settle(entry, true, r), e => this.settle(entry, false, undefined, e));
return p;
}
/** A broad read made of narrow ones (Refresh all, Import all): single-flight on its own key too. */
group<R>(spec: GroupSpec<R>): Promise<R> {
const own = this.entries.get(spec.key);
if (own) return own.promise as Promise<R>;
const covers = new Set(spec.covers);
let resolve!: (r: R) => void, reject!: (e: unknown) => void;
const promise = new Promise<R>((a, b) => { resolve = a; reject = b; });
const entry: Entry = { key: spec.key, tags: new Set(spec.tags ?? []), covers, accounts: [], promise, group: true };
this.entries.set(spec.key, entry);
this.emit();
const handle: GroupHandle = { release: k => { if (covers.delete(k)) this.emit(); } };
// run after the entry exists, so a read started inside joins nothing by mistake (release first, then read)
Promise.resolve().then(() => spec.run(handle)).then(r => { this.settle(entry, true, r); resolve(r); }, e => { this.settle(entry, false, undefined, e); reject(e); });
return promise;
}
/** Stops what overlaps the query: queued reads are dropped (their waiters get "cancelled"), running ones cancel their job. */
cancel(q: ReadQuery): void {
const { keys, tags } = norm(q);
for (const e of [...this.entries.values()]) {
if (!this.overlaps(e, keys, tags) || e.group) continue;
if (this.sched.isRunning(e.key)) e.cancel?.();
else this.sched.clear(k => k === e.key);
}
}
/** A write changed what these keys read: their "just now" memo goes, so the next read really reads. */
invalidate(match: (key: string) => boolean): string[] {
const hit: string[] = [];
for (const k of [...this.done.keys()]) if (match(k)) { this.done.delete(k); hit.push(k); }
if (hit.length) this.emit();
return hit;
}
state(q: ReadQuery): ReadStatus {
const { keys, tags } = norm(q);
const now = this.clock.now();
let inFlight = 0;
const accts = new Set<string>();
for (const e of this.entries.values()) {
if (!this.overlaps(e, keys, tags)) continue;
inFlight++;
for (const a of e.accounts) accts.add(a);
}
for (const k of keys) for (const a of this.accountsOf.get(k) ?? []) accts.add(a);
let lastAt: number | null = keys.length ? Infinity : null;
let justNow = keys.length > 0;
for (const k of keys) {
const d = this.done.get(k);
if (!d) { lastAt = null; justNow = false; break; }
lastAt = Math.min(lastAt as number, d.at);
if (!d.ok || now - d.at >= this.justNowMs) justNow = false;
}
const paused = this.sched.stats().paused;
let pausedUntil: number | null = null;
for (const a of accts) if (paused[a] && paused[a] > now) pausedUntil = Math.max(pausedUntil ?? 0, paused[a]);
const one = keys.length === 1 ? this.done.get(keys[0]!) : undefined;
return { busy: inFlight > 0, inFlight, justNow: justNow && inFlight === 0, lastAt: lastAt === Infinity ? null : lastAt, error: one && !one.ok ? one.error ?? null : null, pausedUntil };
}
private overlaps(e: Entry, keys: string[], tags: string[]): boolean {
for (const k of keys) if (e.key === k || e.covers.has(k)) return true;
for (const t of tags) if (e.tags.has(t) || e.key === t) return true;
return false;
}
private settle(e: Entry, ok: boolean, result: unknown, error?: unknown): void {
if (this.entries.get(e.key) === e) this.entries.delete(e.key);
const at = this.clock.now();
if (ok) this.done.set(e.key, { at, ok, result });
else if (!/cancel/i.test(errText(error))) this.done.set(e.key, { at, ok, error: errText(error) });
if (!e.group) this.onEvent?.(e.key, ok ? { kind: 'done', result } : { kind: 'error', error });
this.armExpiry();
this.emit();
}
/** "Read just now" ends by itself: one timer re-renders the buttons when the oldest memo runs out. */
private armExpiry(): void {
if (this.expiry !== null) return;
this.expiry = this.clock.setTimeout(() => { this.expiry = null; this.emit(); }, this.justNowMs + 50);
}
private emit(): void {
this.ver++;
for (const f of this.listeners) { try { f(); } catch { /* a listener never breaks the registry */ } }
}
}
function norm(q: ReadQuery): { keys: string[]; tags: string[] } {
return typeof q === 'string' ? { keys: [q], tags: [] } : { keys: q.keys ?? [], tags: q.tags ?? [] };
}
// ---- canonical keys of reads without an app target ----
export const PORTFOLIO_KEY = '*\u001fportfolio.status\u001f{"live":true}';
export const PORTFOLIO_CHECK_KEY = '*\u001fportfolio.status\u001f{}';
export const READ_ALL_KEY = '*\u001freadAll';
export const IMPORT_ALL_KEY = '*\u001fimport';
export const importKey = (account: string): string => `account:${account}\u001fstore_apps.list`;
export const accountCheckKey = (account: string): string => `account:${account}\u001faccount.check`;
/** The scope tags of a read of one app (Refresh all sees every app read; an app's own buttons see `app:<target>`). */
export const appTags = (target: string): string[] => ['all', `app:${target}`];
// ---- which reads a write changes ----
const ALL = null;
const LISTING = ['project.listings', 'project.editable', 'listing.live', 'validate', 'scan', 'aso.audit'];
const CATALOG = ['prices.current', 'prices.diff', 'catalog.diff', 'validate', 'scan'];
const ART = ['art.live', 'project.renders', 'project.icon', 'validate', 'scan'];
/**
* The read methods of the same app a write makes outdated (null: all of them). `portfolio` true when the write
* changes release state the portfolio read shows. Unknown writes invalidate everything of the app (safe default).
*/
export function affectedReads(writeMethod: string): { methods: string[] | null; portfolio: boolean } {
const m = writeMethod;
const r = (methods: string[] | null, portfolio = false) => ({ methods, portfolio });
if (m === 'owner.play_rollout' || m === 'owner.ios_phased') return r(['apple.status', 'play.status'], true);
if (m.startsWith('reviews.') || m === 'owner.reply_send') return r(['reviews.list', 'reviews.drafts']);
if (m.startsWith('prices.') || m === 'owner.prices_import' || m === 'apple.iap' || m === 'apple.subscriptions' || m === 'play.products' || m === 'play.subscriptions') return r(CATALOG);
if (m === 'apple.listing_pull' || m === 'play.listing_pull' || m === 'play.listing' || m === 'apple.appinfo' || m === 'apple.review_details') return r(LISTING);
if (m.startsWith('art.') || m.startsWith('shots.') || m === 'apple.screenshots' || m === 'apple.previews' || m === 'play.images' || m === 'icons') return r(ART);
if (m.startsWith('apple.testflight_') || m === 'owner.testflight_testers') return r(['apple.testflight_status']);
if (m.startsWith('owner.ppo_') || m.startsWith('apple.ppo_')) return r(['apple.ppo_status']);
if (m === 'apple.game_center' || m === 'play.games') return r(['games.status']);
if (m === 'apple.encryption' || m === 'play.data_safety') return r(['project.declarations', 'validate', 'scan']);
if (m.startsWith('analytics.')) return r(['analytics.compare']);
return r(ALL, true);
}
/** The method part of a canonical key (readKey: target \u001f method \u001f args). */
export const methodOfKey = (key: string): string => key.split('\u001f')[1] ?? '';
export const targetOfKey = (key: string): string => key.split('\u001f')[0] ?? '';

View file

@ -127,6 +127,9 @@ export class ReadScheduler {
subscribe(fn: () => void): () => void { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; } subscribe(fn: () => void): () => void { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; }
/** True while the read of this key is running (not just queued). */
isRunning(key: string): boolean { return this.running.has(key); }
has(key: string): boolean { return this.running.has(key) || this.queue.some(i => i.task.key === key); } has(key: string): boolean { return this.running.has(key) || this.queue.some(i => i.task.key === key); }
enqueue<R>(task: ReadTask<R>): Promise<R> { enqueue<R>(task: ReadTask<R>): Promise<R> {

View file

@ -0,0 +1,94 @@
// The "what's next" line of each app section (docs IA): one sentence and the sub view it opens, from state that is
// already read (status, live releases, attention, cached reads). Pure, so tests pin the rules; a section never starts
// a read to fill it.
import type { CatalogParity, ListingsResult, StoreRelease } from '../api';
import { t } from '../i18n';
import type { AppSection, AppTab } from '../nav';
import type { IconName } from '../ui/icons';
import { type Attention, isGameSummary } from './model';
import { share } from './format';
import type { ProjectSummary } from '../api';
export type NextTone = 'bad' | 'warn' | 'ok' | 'info' | 'neutral';
export interface SectionNext { text: string; tone: NextTone; tab: AppTab | null; icon: IconName }
export interface GamesNext { changes: number; blockers: number; apiOff: boolean }
export interface SectionInput {
project: boolean;
att: Attention[];
all: StoreRelease[];
next: string | null;
summary: ProjectSummary | null;
catalog: CatalogParity | null;
/** Unsaved edits of the section's editors. */
unsaved: number;
/** Cached reads (null: not read yet). */
listings: ListingsResult | null;
reviews: { reply?: unknown }[] | null;
games: GamesNext | null;
/** Blockers of the last store readiness read (validate), null when never read. */
readiness?: number | null;
}
const storeName = (s: 'ios' | 'android') => (s === 'ios' ? 'App Store' : 'Google Play');
/** Problems of a listings read: file problems plus required fields missing or over the limit. */
export function listingProblems(l: ListingsResult | null): number | null {
if (!l) return null;
let n = l.problems.length;
for (const loc of l.locales) for (const s of [loc.play, loc.apple]) for (const f of s?.fields ?? []) if (f.state === 'missing' || f.state === 'over') n++;
return n;
}
export function sectionNext(section: AppSection, i: SectionInput): SectionNext {
const bad = i.att.filter(a => a.tone === 'bad');
if (section === 'release') {
const rej = i.all.find(r => r.phase === 'rejected' || r.phase === 'halted');
if (rej) return { text: t(rej.phase === 'rejected' ? 'next.rejected' : 'next.halted', { version: rej.version ?? '', store: storeName(rej.store) }), tone: 'bad', tab: 'releases', icon: 'alertCircle' };
const checks = bad.filter(a => a.tab === 'checks').length + (i.readiness ?? 0);
if (checks) return { text: t('next.blockers', { count: checks }), tone: 'bad', tab: 'checks', icon: 'alertCircle' };
const rolling = i.all.find(r => r.phase === 'rollout' && r.fraction !== null && r.fraction < 1);
if (rolling) return { text: t('next.rollout', { share: share(rolling.fraction ?? 0), version: rolling.version ?? '' }), tone: 'info', tab: 'releases', icon: 'rocket' };
const approved = i.all.find(r => r.phase === 'approved');
if (approved) return { text: t('next.approved', { version: approved.version ?? '' }), tone: 'info', tab: 'releases', icon: 'rocket' };
const ready = i.all.find(r => r.phase === 'draft' || r.phase === 'testing');
if (ready) return { text: t('next.submit', { version: ready.version ?? '' }), tone: 'info', tab: 'releases', icon: 'send' };
const review = i.all.find(r => r.phase === 'review' || r.phase === 'sent');
if (review) return { text: review.managed ? t('next.managed', { version: review.version ?? '' }) : t('next.review', { version: review.version ?? '' }), tone: 'neutral', tab: 'releases', icon: 'clock' };
if (i.project && !i.next && !i.all.length) return { text: t('next.upload'), tone: 'neutral', tab: 'releases', icon: 'upload' };
const live = i.all.find(r => r.phase === 'live' || r.phase === 'released');
return live ? { text: t('next.live', { version: live.version ?? '' }), tone: 'ok', tab: null, icon: 'check' } : { text: t('next.notRead'), tone: 'neutral', tab: null, icon: 'clock' };
}
if (section === 'store') {
if (!i.project) return { text: t('next.storeLive'), tone: 'neutral', tab: null, icon: 'cloud' };
const n = listingProblems(i.listings);
if (n) return { text: t('next.listingProblems', { count: n }), tone: 'warn', tab: 'listings', icon: 'alert' };
if (i.unsaved) return { text: t('next.unsaved', { count: i.unsaved }), tone: 'warn', tab: null, icon: 'edit' };
return n === null ? { text: t('next.listingsUnread'), tone: 'neutral', tab: 'listings', icon: 'text' } : { text: t('next.storeOk'), tone: 'ok', tab: null, icon: 'check' };
}
if (section === 'revenue') {
const c = i.catalog;
if (c && c.checked === 'live' && !c.ok) return { text: t('next.catalogDiff', { count: c.missingIos.length + c.missingAndroid.length + c.onlyIos.length + c.onlyAndroid.length }), tone: 'warn', tab: 'catalog', icon: 'alert' };
const p = i.summary?.products ?? 0, s = i.summary?.subscriptions ?? 0;
if (!p && !s) return { text: t('next.noProducts'), tone: 'neutral', tab: 'catalog', icon: 'plus' };
return { text: t('next.products', { products: p, subs: s }), tone: 'ok', tab: null, icon: 'check' };
}
if (section === 'players') {
const open = i.reviews ? i.reviews.filter(r => !r.reply).length : null;
if (open) return { text: t('next.reviews', { count: open }), tone: 'warn', tab: 'reviews', icon: 'message' };
if (i.games?.apiOff) return { text: t('next.gamesApiOff'), tone: 'bad', tab: 'games', icon: 'alertCircle' };
if (i.games?.blockers) return { text: t('next.gamesBlockers', { count: i.games.blockers }), tone: 'bad', tab: 'games', icon: 'alertCircle' };
if (i.games?.changes) return { text: t('next.gamesSync', { count: i.games.changes }), tone: 'warn', tab: 'games', icon: 'upload' };
return open === null ? { text: t('next.reviewsUnread'), tone: 'neutral', tab: 'reviews', icon: 'message' } : { text: t('next.reviewsOk'), tone: 'ok', tab: null, icon: 'check' };
}
const crash = i.att.find(a => a.tab === 'health');
if (crash) return { text: crash.text, tone: crash.tone === 'bad' ? 'bad' : 'warn', tab: 'health', icon: 'activity' };
const problems = i.att.filter(a => a.tab === 'checks');
const fix = problems.filter(a => a.tone === 'bad').length + (i.readiness ?? 0);
if (fix) return { text: t('next.fixFirst', { count: fix }), tone: 'bad', tab: 'checks', icon: 'shield' };
if (problems.length) return { text: t('next.warnings', { count: problems.length }), tone: 'warn', tab: 'checks', icon: 'shield' };
return { text: t('next.healthOk'), tone: 'ok', tab: null, icon: 'check' };
}
/** A game: profile game, a games section in the config, or a Play game category. */
export const isGame = (s: ProjectSummary | null | undefined): boolean => isGameSummary(s);

View file

@ -7,6 +7,7 @@ import { applyPrefs, loadPrefs, type Prefs, resolveLang, savePrefs } from './pre
import { PrefsContext } from './prefs-ctx'; import { PrefsContext } from './prefs-ctx';
import { installGlobalHandlers, report } from './lib/crash'; import { installGlobalHandlers, report } from './lib/crash';
import { DataProvider } from './store'; import { DataProvider } from './store';
import { TrayCardBridge } from './card/bridge';
import { ErrorBoundary } from './ui/ErrorBoundary'; import { ErrorBoundary } from './ui/ErrorBoundary';
import { ContextMenuProvider } from './ui/ContextMenu'; import { ContextMenuProvider } from './ui/ContextMenu';
import { ExportProvider } from './ui/Exports'; import { ExportProvider } from './ui/Exports';
@ -37,7 +38,7 @@ function Root() {
update({ ...prefs, theme: dark ? 'light' : 'dark' }); update({ ...prefs, theme: dark ? 'light' : 'dark' });
}, [prefs, update]); }, [prefs, update]);
// a language change re-renders the whole tree in the new language // a language change re-renders the whole tree in the new language
return <PrefsContext.Provider value={{ prefs, update }}><DataProvider><ExportProvider><ContextMenuProvider><App key={lang} onTheme={onTheme} /></ContextMenuProvider></ExportProvider></DataProvider></PrefsContext.Provider>; return <PrefsContext.Provider value={{ prefs, update }}><DataProvider><TrayCardBridge /><ExportProvider><ContextMenuProvider><App key={lang} onTheme={onTheme} /></ContextMenuProvider></ExportProvider></DataProvider></PrefsContext.Provider>;
} }
installGlobalHandlers(); installGlobalHandlers();

View file

@ -4,31 +4,58 @@ import { createContext, useContext } from 'react';
import type { Key } from './i18n'; import type { Key } from './i18n';
import type { IconName } from './ui/icons'; import type { IconName } from './ui/icons';
export const APP_TABS = ['releases', 'catalog', 'prices', 'listings', 'art', 'health', 'reviews', 'testflight', 'growth', 'appinfo', 'checks', 'tools'] as const; export const APP_TABS = ['releases', 'testflight', 'listings', 'art', 'appinfo', 'catalog', 'prices', 'reviews', 'games', 'health', 'growth', 'checks', 'tools'] as const;
export type AppTab = (typeof APP_TABS)[number]; export type AppTab = (typeof APP_TABS)[number];
/** Tabs of a store-only app: store reads only (catalog, prices, app info and checks need the app folder; listings and
* store art are the live ones; Growth shows the Product Page Optimization tests only). */ /** The five sections of an app, by job (docs IA): each holds sub views (the old tabs). The route keeps the sub id. */
export const STORE_TABS: readonly AppTab[] = ['releases', 'listings', 'art', 'health', 'reviews', 'testflight', 'growth']; export const SECTIONS = ['release', 'store', 'revenue', 'players', 'health'] as const;
export const tabsFor = (hasFolder: boolean): readonly AppTab[] => (hasFolder ? APP_TABS : STORE_TABS); export type AppSection = (typeof SECTIONS)[number];
export const SECTION_TABS: Record<AppSection, readonly AppTab[]> = {
release: ['releases', 'testflight'], store: ['listings', 'art', 'appinfo'], revenue: ['catalog', 'prices'], players: ['reviews', 'games'], health: ['health', 'growth', 'checks', 'tools'],
};
export const sectionOf = (tab: AppTab): AppSection => SECTIONS.find(s => SECTION_TABS[s].includes(tab)) ?? 'release';
export const SECTION_KEY: Record<AppSection, Key> = { release: 'sec.release', store: 'sec.store', revenue: 'sec.revenue', players: 'sec.players', health: 'sec.health' };
export const SECTION_ICON: Record<AppSection, IconName> = { release: 'rocket', store: 'image', revenue: 'coins', players: 'users', health: 'activity' };
/** Sub views of a store-only app: store reads only (catalog, prices, app info, checks and tools need the app folder;
* listings and store art are the live ones; Growth shows the Product Page Optimization tests only). */
export const STORE_TABS: readonly AppTab[] = ['releases', 'testflight', 'listings', 'art', 'reviews', 'health', 'growth'];
/** The sub views an app has: the folder decides most; Game services only for games. */
export const tabsFor = (hasFolder: boolean, game = false): readonly AppTab[] => (hasFolder ? APP_TABS : STORE_TABS).filter(x => x !== 'games' || (game && hasFolder));
/** The sections an app has (a section with no sub view is left out: Revenue for a store-only app). */
export const sectionsFor = (hasFolder: boolean, game = false): AppSection[] => { const tabs = tabsFor(hasFolder, game); return SECTIONS.filter(s => SECTION_TABS[s].some(x => tabs.includes(x))); };
export const subsOf = (s: AppSection, hasFolder: boolean, game = false): AppTab[] => { const tabs = tabsFor(hasFolder, game); return SECTION_TABS[s].filter(x => tabs.includes(x)); };
export const TAB_KEY: Record<AppTab, Key> = { export const TAB_KEY: Record<AppTab, Key> = {
releases: 'tab.releases', catalog: 'tab.catalog', prices: 'tab.prices', listings: 'tab.listings', art: 'tab.art', health: 'tab.health', reviews: 'tab.reviews', releases: 'tab.releases', catalog: 'tab.catalog', prices: 'tab.prices', listings: 'tab.listings', art: 'tab.art', health: 'tab.health', reviews: 'tab.reviews',
testflight: 'tab.testflight', growth: 'tab.growth', appinfo: 'tab.appinfo', checks: 'tab.checks', tools: 'tab.tools', testflight: 'tab.testflight', growth: 'tab.growth', appinfo: 'tab.appinfo', checks: 'tab.checks', tools: 'tab.tools', games: 'tab.games',
}; };
export const TAB_ICON: Record<AppTab, IconName> = { export const TAB_ICON: Record<AppTab, IconName> = {
releases: 'rocket', catalog: 'tag', prices: 'coins', listings: 'text', art: 'grid', health: 'activity', reviews: 'message', testflight: 'plane', growth: 'chart', releases: 'rocket', catalog: 'tag', prices: 'coins', listings: 'text', art: 'grid', health: 'activity', reviews: 'message', testflight: 'plane', growth: 'chart',
appinfo: 'clipboard', checks: 'shield', tools: 'sliders', appinfo: 'clipboard', checks: 'shield', tools: 'sliders', games: 'sparkle',
}; };
/** A place in an app from a link: an old tab id ("prices"), a section ("revenue", its first sub view) or
* "section/sub" ("store/art"). Unknown: Release. */
export function placeOf(v: string | undefined | null): AppTab {
if (!v) return 'releases';
const [a, b] = v.split('/');
if (b && (SECTIONS as readonly string[]).includes(a!) && SECTION_TABS[a as AppSection].includes(b as AppTab)) return b as AppTab;
if (APP_TABS.includes(a as AppTab)) return a as AppTab;
if ((SECTIONS as readonly string[]).includes(a!)) return SECTION_TABS[a as AppSection][0]!;
return 'releases';
}
export const WORKSPACE = ['apps', 'accounts', 'ignored', 'dependencies', 'settings'] as const; export const WORKSPACE = ['apps', 'accounts', 'ignored', 'dependencies', 'settings'] as const;
export type WorkspaceScreen = (typeof WORKSPACE)[number]; export type WorkspaceScreen = (typeof WORKSPACE)[number];
export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen; section?: string }; export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen; section?: string };
/** storebound://<screen> deep links and the dev-only start switch ("app:health" = first app, Health tab; /** storebound://<screen> deep links and the dev-only start switch ("app:health" = first app, Health section;
* "app:health:2" = second app; "settings:refresh" = a Settings section). `apps` are the app keys in list order. */ * "app:store/art" = a sub view; "app:prices" = an old tab id; "app:health:2" = second app; "settings:refresh" = a Settings section). `apps` are the app keys in list order. */
export function parseStart(v: string, apps: string[]): Route | null { export function parseStart(v: string, apps: string[]): Route | null {
const [screen, tab, n] = v.split(':'); const [screen, tab, n] = v.split(':');
const app = apps[Math.max(0, (Number(n) || 1) - 1)]; const app = apps[Math.max(0, (Number(n) || 1) - 1)];
if (screen === 'app' && app) return { screen: 'app', appId: app, tab: APP_TABS.includes(tab as AppTab) ? tab as AppTab : 'releases' }; if (screen === 'app' && app) return { screen: 'app', appId: app, tab: placeOf(tab) };
if (screen === 'portfolio') return { screen: 'portfolio' }; if (screen === 'portfolio') return { screen: 'portfolio' };
if (!(WORKSPACE as readonly string[]).includes(screen ?? '')) return null; if (!(WORKSPACE as readonly string[]).includes(screen ?? '')) return null;
return tab ? { screen: screen as WorkspaceScreen, section: tab } : { screen: screen as WorkspaceScreen }; return tab ? { screen: screen as WorkspaceScreen, section: tab } : { screen: screen as WorkspaceScreen };
@ -41,7 +68,7 @@ export function parseRouteJson(v: string): Route | null {
if (!o || typeof o !== 'object') return null; if (!o || typeof o !== 'object') return null;
const r = o as Record<string, unknown>; const r = o as Record<string, unknown>;
if (r.screen === 'portfolio') return { screen: 'portfolio' }; if (r.screen === 'portfolio') return { screen: 'portfolio' };
if (r.screen === 'app') return typeof r.appId === 'string' && r.appId ? { screen: 'app', appId: r.appId, tab: APP_TABS.includes(r.tab as AppTab) ? r.tab as AppTab : 'releases' } : null; if (r.screen === 'app') return typeof r.appId === 'string' && r.appId ? { screen: 'app', appId: r.appId, tab: placeOf(typeof r.tab === 'string' ? r.tab : null) } : null;
if (typeof r.screen === 'string' && (WORKSPACE as readonly string[]).includes(r.screen)) return typeof r.section === 'string' ? { screen: r.screen as WorkspaceScreen, section: r.section } : { screen: r.screen as WorkspaceScreen }; if (typeof r.screen === 'string' && (WORKSPACE as readonly string[]).includes(r.screen)) return typeof r.section === 'string' ? { screen: r.screen as WorkspaceScreen, section: r.section } : { screen: r.screen as WorkspaceScreen };
return null; return null;
} }

View file

@ -10,7 +10,9 @@ import { type Account, type AccountCheck, api, errorText, STUDIO_COLORS, type St
import { type Key, t } from '../i18n'; import { type Key, t } from '../i18n';
import { ago } from '../lib/format'; import { ago } from '../lib/format';
import { withIgnored } from '../lib/identity'; import { withIgnored } from '../lib/identity';
import { type AccountHealth, useData } from '../store'; import { type AccountHealth, useData, useReadState } from '../store';
import { accountCheckKey, importKey } from '../lib/read-registry';
import { ImportAppsButton, TestAccountButton } from '../ui/ReadButtons';
import { Icon, StoreGlyph } from '../ui/icons'; import { Icon, StoreGlyph } from '../ui/icons';
import { Chip, Notice, StudioMark } from '../ui/kit'; import { Chip, Notice, StudioMark } from '../ui/kit';
import { EmptyState, PageHeader, Section, StatTile } from '../ui/ds'; import { EmptyState, PageHeader, Section, StatTile } from '../ui/ds';
@ -58,11 +60,14 @@ function AccountRow({ a, busy, setBusy, onError }: { a: Account; busy: string |
}; };
const save = (e: FormEvent) => { e.preventDefault(); run(`ed-${a.id}`, async () => { await api.updateAccount(a.id, label, studio || null); if (a.kind === 'play' && a.profile && dev.trim() !== (a.developerId ?? '')) await api.setPlayDeveloper(a.id, dev.trim() || null); await d.reload(); setEdit(false); }); }; const save = (e: FormEvent) => { e.preventDefault(); run(`ed-${a.id}`, async () => { await api.updateAccount(a.id, label, studio || null); if (a.kind === 'play' && a.profile && dev.trim() !== (a.developerId ?? '')) await api.setPlayDeveloper(a.id, dev.trim() || null); await d.reload(); setEdit(false); }); };
const check = h?.check; const check = h?.check;
// Test and Import of this account: busy from the read registry (Test all / Import apps make them busy too)
const ck = useReadState(accountCheckKey(a.id));
const im = useReadState(importKey(a.id));
const cm = useContextMenu(); const cm = useContextMenu();
const more = useMenuButton(); const more = useMenuButton();
const menu = (): MenuInput => [ const menu = (): MenuInput => [
{ label: t('acct.test'), icon: 'shield', disabled: busy ? t('cm.busy') : false, onSelect: () => run(`ck-${a.id}`, () => d.checkAccount(a.id)) }, { label: t('acct.test'), icon: 'shield', disabled: ck.busy ? t('cm.busy') : false, onSelect: () => { d.checkAccount(a.id).catch(() => {}); } },
{ label: t('acct.import'), icon: 'download', disabled: busy || d.importBusy ? t('cm.busy') : false, onSelect: () => run(`im-${a.id}`, () => d.importApps(a.id)) }, { label: t('acct.import'), icon: 'download', disabled: im.busy ? t('cm.busy') : false, onSelect: () => { d.importApps(a.id).catch(() => {}); } },
{ label: t('acct.edit'), icon: 'edit', onSelect: () => setEdit(true) }, { label: t('acct.edit'), icon: 'edit', onSelect: () => setEdit(true) },
'sep', 'sep',
{ label: t('cm.copy'), icon: 'copy', submenu: [ { label: t('cm.copy'), icon: 'copy', submenu: [
@ -87,11 +92,12 @@ function AccountRow({ a, busy, setBusy, onError }: { a: Account; busy: string |
{used ? ` · ${t('acct.folders', { count: used })}` : ''} {used ? ` · ${t('acct.folders', { count: used })}` : ''}
{a.kind === 'play' && (a.developerId ? <> · <span className="mono-id selectable" title={t('acct.devIdHint')}>{t('acct.devId', { id: a.developerId })}</span></> : <> · <span title={t('acct.devIdHint')}>{t('acct.noDevId')}</span></>)} {a.kind === 'play' && (a.developerId ? <> · <span className="mono-id selectable" title={t('acct.devIdHint')}>{t('acct.devId', { id: a.developerId })}</span></> : <> · <span title={t('acct.devIdHint')}>{t('acct.noDevId')}</span></>)}
{check?.principal ? <> · <span className="mono-id selectable">{check.principal}</span></> : null} {check?.principal ? <> · <span className="mono-id selectable">{check.principal}</span></> : null}
{a.kind === 'play' && check?.source ? ` · ${check.source === 'broker' ? t('acct.viaBroker') : t('acct.viaFile')}` : ''}
</div> </div>
</div> </div>
<div className="actions"> <div className="actions">
<button className="btn btn-sm" onClick={() => run(`ck-${a.id}`, () => d.checkAccount(a.id))} disabled={!!busy}><Icon name="shield" className={busy === `ck-${a.id}` ? 'spin' : undefined} />{t('acct.test')}</button> <TestAccountButton account={a.id} label={t('acct.test')} />
<button className="btn btn-sm" onClick={() => run(`im-${a.id}`, () => d.importApps(a.id))} disabled={!!busy || d.importBusy}><Icon name="download" />{t('acct.import')}</button> <ImportAppsButton account={a.id} label={t('acct.import')} />
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => setEdit(x => !x)} aria-expanded={edit} aria-label={t('acct.editAria', { label: a.label })} title={t('acct.edit')}><Icon name="edit" /></button> <button className="btn btn-sm btn-ghost btn-icon" onClick={() => setEdit(x => !x)} aria-expanded={edit} aria-label={t('acct.editAria', { label: a.label })} title={t('acct.edit')}><Icon name="edit" /></button>
<button className="btn btn-sm btn-ghost btn-icon" {...more(menu)} aria-label={t('cm.more')} title={t('cm.more')}><Icon name="more" /></button> <button className="btn btn-sm btn-ghost btn-icon" {...more(menu)} aria-label={t('cm.more')} title={t('cm.more')}><Icon name="more" /></button>
</div> </div>
@ -117,6 +123,22 @@ function AccountRow({ a, busy, setBusy, onError }: { a: Account; busy: string |
</Notice> </Notice>
</div> </div>
)} )}
{check?.grants && check.grants.length > 0 && (
<div className="acct-fix acct-grants">
<div className="small strong">{t('acct.grantsTitle')}</div>
<ul className="small">
{check.grants.map(g => (
<li key={g.packageName}>
<span className="mono-id selectable">{g.packageName}</span>{': '}
{!g.registered ? <span className="muted">{t('acct.notRegistered')}</span>
: g.missing.length ? <Chip tone="warn">{t('acct.grantsMissing', { list: g.missing.join(', ') })}</Chip>
: g.grants ? <Chip tone="ok">{t('acct.grantsOk')}</Chip> : <span className="muted">{t('acct.grantsNone')}</span>}
{g.grants && g.grants.length > 0 && <span className="muted mono-id" title={(g.enabledApis ?? []).join(', ')}>{` ${g.grants.join(', ')}`}</span>}
</li>
))}
</ul>
</div>
)}
{h?.error && <div className="acct-fix"><Notice tone="bad">{h.error}</Notice></div>} {h?.error && <div className="acct-fix"><Notice tone="bad">{h.error}</Notice></div>}
</div> </div>
); );
@ -196,7 +218,6 @@ export function Accounts({ focus }: { focus?: string }) {
const addStudio = () => act('studio', async () => { const s = await api.saveStudio(null, studioName, studioColor); setStudioName(''); return s; }, r => t('studio.added', { name: (r as Studio).name })); const addStudio = () => act('studio', async () => { const s = await api.saveStudio(null, studioName, studioColor); setStudioName(''); return s; }, r => t('studio.added', { name: (r as Studio).name }));
const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel, playStudio || null); if (a) setPlayLabel(''); return a; }, r => t('accounts.saved', { label: (r as Account).label })); const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel, playStudio || null); if (a) setPlayLabel(''); return a; }, r => t('accounts.saved', { label: (r as Account).label }));
const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId, appleStudio || null); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }, r => t('accounts.saved', { label: (r as Account).label })); const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId, appleStudio || null); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }, r => t('accounts.saved', { label: (r as Account).label }));
const testAll = async () => { setBusy('all'); await Promise.all(d.accounts.map(a => d.checkAccount(a.id))); setBusy(null); };
const unassigned = d.accounts.filter(a => !a.studio || !d.studios.some(s => s.id === a.studio)); const unassigned = d.accounts.filter(a => !a.studio || !d.studios.some(s => s.id === a.studio));
const studioSelect = (id: string, value: string, set: (v: string) => void) => ( const studioSelect = (id: string, value: string, set: (v: string) => void) => (
<div className="field"><label htmlFor={id}>{t('studio.studio')}</label> <div className="field"><label htmlFor={id}>{t('studio.studio')}</label>
@ -209,8 +230,8 @@ export function Accounts({ focus }: { focus?: string }) {
return ( return (
<div className="page scr-accounts"> <div className="page scr-accounts">
<PageHeader icon="key" eyebrow={t('v2cfg.workspace')} title={t('nav.accounts')} subtitle={t('accounts.leadStudios')} actions={<> <PageHeader icon="key" eyebrow={t('v2cfg.workspace')} title={t('nav.accounts')} subtitle={t('accounts.leadStudios')} actions={<>
<button className="btn" onClick={testAll} disabled={!!busy || !d.accounts.length}><Icon name="shield" className={busy === 'all' ? 'spin' : undefined} />{t('acct.testAll')}</button> <TestAccountButton className="btn" label={t('acct.testAll')} />
<button className="btn btn-primary" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length}><Icon name="download" className={d.importBusy ? 'spin' : undefined} />{t('action.importApps')}</button> <ImportAppsButton className="btn btn-primary" />
</>} /> </>} />
{d.accounts.length > 0 && <div className="ds-grid acct-kpis"> {d.accounts.length > 0 && <div className="ds-grid acct-kpis">
<StatTile icon="building" label={t('v2cfg.studios')} value={d.studios.length} /> <StatTile icon="building" label={t('v2cfg.studios')} value={d.studios.length} />

View file

@ -1,16 +1,20 @@
// One app across both stores: header (icon, studio, ids, store state, pairing), then the tabs. A store-only app (no // One app across both stores: header (icon, studio, ids, store state, pairing), then five sections by job (Release,
// Store page, Revenue, Players, Health; docs IA), each with a header (what it is for, the one next step) and its sub views. A store-only app (no
// app folder) shows its store reads (releases, health, reviews, TestFlight) read-only, with "Link a folder" and // app folder) shows its store reads (releases, health, reviews, TestFlight) read-only, with "Link a folder" and
// "Start an app folder here" to make it a full app. // "Start an app folder here" to make it a full app.
import { useContextMenu, useMenuButton } from '../ui/ContextMenu'; import { useContextMenu, useMenuButton } from '../ui/ContextMenu';
import { appMenu, playUrlFor } from '../ui/app-menu'; import { appMenu, playUrlFor } from '../ui/app-menu';
import { useShowIgnored } from '../lib/show-ignored'; import { useShowIgnored } from '../lib/show-ignored';
import { useState } from 'react'; import { useState } from 'react';
import { GamesTab } from './tabs/Games';
import { SectionHead } from './SectionHead';
import { api, errorText } from '../api'; import { api, errorText } from '../api';
import { type Key, t } from '../i18n'; import { type Key, t } from '../i18n';
import { pairCandidates, type UnifiedApp, withLink, withPair, withStudio } from '../lib/identity'; import { pairCandidates, type UnifiedApp, withLink, withPair, withStudio } from '../lib/identity';
import { attention, storeNow } from '../lib/model'; import { attention, storeNow } from '../lib/model';
import { Hero, nextStep, Tabs } from '../ui/ds'; import { Hero, nextStep, Tabs } from '../ui/ds';
import { type AppTab, TAB_ICON, TAB_KEY, tabsFor, useNav } from '../nav'; import { isGameSummary } from '../lib/model';
import { type AppSection, type AppTab, SECTION_ICON, SECTION_KEY, SECTION_TABS, sectionOf, sectionsFor, subsOf, useNav } from '../nav';
import { useData } from '../store'; import { useData } from '../store';
import { Icon } from '../ui/icons'; import { Icon } from '../ui/icons';
import { ErrorBoundary } from '../ui/ErrorBoundary'; import { ErrorBoundary } from '../ui/ErrorBoundary';
@ -65,7 +69,7 @@ function AppControls({ app }: { app: UnifiedApp }) {
</select></label> </select></label>
)} )}
<span className="grow" /> <span className="grow" />
<button className="btn btn-sm btn-ghost" {...more(() => appMenu(app, d, nav, { showIgnored }))} aria-label={t('cm.more')} title={t('cm.more')}><Icon name="more" />{app.ignored || app.ignoredStores.length ? t('nav.ignored') : null}</button> <button className="btn btn-sm btn-ghost" {...more(() => appMenu(app, d, nav, { showIgnored }), `app:${app.key}`)} aria-label={t('cm.more')} title={t('cm.more')}><Icon name="more" />{app.ignored || app.ignoredStores.length ? t('nav.ignored') : null}</button>
</div> </div>
); );
} }
@ -107,11 +111,15 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
const ios = e?.app?.platforms.ios ?? (app.ios ? { bundleId: app.ios.app.bundleId, ascAppId: app.ios.app.id } : null); const ios = e?.app?.platforms.ios ?? (app.ios ? { bundleId: app.ios.app.bundleId, ascAppId: app.ios.app.id } : null);
const android = e?.app?.platforms.android ?? (app.android ? { packageName: app.android.app.id } : null); const android = e?.app?.platforms.android ?? (app.android ? { packageName: app.android.app.id } : null);
const name = (app.project && e?.app?.name) || app.name; const name = (app.project && e?.app?.name) || app.name;
const tabs = tabsFor(!!app.project); const game = isGameSummary(e?.summary);
const sections = sectionsFor(!!app.project, game);
const section = sectionOf(tab);
const ed = useEdits(); const ed = useEdits();
useUnsavedGuard(); useUnsavedGuard();
const studio = d.studios.find(s => s.id === app.studio) ?? null; const studio = d.studios.find(s => s.id === app.studio) ?? null;
const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: app.key, tab: x }); const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: app.key, tab: x });
const setSection = (x: AppSection) => setTab(subsOf(x, !!app.project, game)[0] ?? SECTION_TABS[x][0]!);
const editCount = (x: AppTab) => (EDIT_TABS[x] ? ed.count(app.project?.id ?? app.target, EDIT_TABS[x]) : 0);
const all = l?.release.all ?? []; const all = l?.release.all ?? [];
const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null; const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null;
const att = attention(app.key, app.name, e, l); const att = attention(app.key, app.name, e, l);
@ -122,7 +130,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
return ( return (
<div className="page ds-app"> <div className="page ds-app">
<Hero name={name} icon={d.iconFor(app)} projectId={app.project && !app.project.missing ? app.project.id : null} <Hero name={name} icon={d.iconFor(app)} projectId={app.project && !app.project.missing ? app.project.id : null}
{...cm(() => appMenu(app, d, nav, { showIgnored }))} {...cm(() => appMenu(app, d, nav, { showIgnored }), `app:${app.key}`)}
badges={<> badges={<>
{e?.summary?.profile && app.project && <Chip tone="outline">{t(`profile.${e.summary.profile}` as 'profile.app')}</Chip>} {e?.summary?.profile && app.project && <Chip tone="outline">{t(`profile.${e.summary.profile}` as 'profile.app')}</Chip>}
{!app.project && <StoreOnlyTag />} {!app.project && <StoreOnlyTag />}
@ -137,19 +145,20 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
{android && <button className="btn btn-sm btn-ghost" onClick={() => open(playUrlFor(d, app))} title={t('app.consoleHint')}><Icon name="external" />Play Console</button>} {android && <button className="btn btn-sm btn-ghost" onClick={() => open(playUrlFor(d, app))} title={t('app.consoleHint')}><Icon name="external" />Play Console</button>}
</>} </>}
all={all} ios={!!ios} android={!!android} next={l?.release.next?.version ?? null} all={all} ios={!!ios} android={!!android} next={l?.release.next?.version ?? null}
compact={tab !== 'releases'} compact={section !== 'release' || tab !== 'releases'}
cta={nextStep({ project: !!app.project, att, all, next: l?.release.next?.version ?? null })} onCta={setTab} /> cta={nextStep({ project: !!app.project, att, all, next: l?.release.next?.version ?? null })} onCta={setTab} />
<AppControls app={app} /> <AppControls app={app} />
{!app.project && <StoreOnlyBanner app={app} />} {!app.project && <StoreOnlyBanner app={app} />}
{app.project?.storeboundPin && <Notice tone="info" icon="info">{t('app.pinNotice', { pin: app.project.storeboundPin, app: d.info?.version ?? '' })}</Notice>} {app.project?.storeboundPin && <Notice tone="info" icon="info">{t('app.pinNotice', { pin: app.project.storeboundPin, app: d.info?.version ?? '' })}</Notice>}
{app.project?.missing ? <FolderMissing project={app.project} /> : <> {app.project?.missing ? <FolderMissing project={app.project} /> : <>
<div className="ds-app-sticky"> <div className="ds-app-sticky">
<Tabs label={t('app.sections', { name })} value={tab} onChange={setTab} items={tabs.map(x => { <Tabs label={t('app.sections', { name })} value={section} onChange={setSection} items={sections.map((x, i) => {
const n = EDIT_TABS[x] ? ed.count(app.project?.id ?? app.target, EDIT_TABS[x]) : 0; const n = subsOf(x, !!app.project, game).reduce((a, s2) => a + editCount(s2), 0);
return { id: x, label: t(TAB_KEY[x]), icon: TAB_ICON[x], count: att.filter(a => a.tab === x && a.tone === 'bad').length, dot: n > 0, dotTitle: n ? t('ed.unsaved', { count: n }) : undefined }; return { id: x, label: t(SECTION_KEY[x]), icon: SECTION_ICON[x], hint: String(i + 1), count: att.filter(a => a.tab && sectionOf(a.tab) === x && a.tone === 'bad').length, dot: n > 0, dotTitle: n ? t('ed.unsaved', { count: n }) : undefined };
})} /> })} />
</div> </div>
<div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${tab}`} className="stack" style={{ gap: 16 }}> <SectionHead app={app} section={section} tab={tab} subs={subsOf(section, !!app.project, game)} att={att} all={all} next={l?.release.next?.version ?? null} unsaved={subsOf(section, !!app.project, game).reduce((a, s2) => a + editCount(s2), 0)} editCount={editCount} onTab={setTab} />
<div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${section}`} className="stack" style={{ gap: 16 }}>
<ErrorBoundary key={tab} where={`tab ${tab}`}> <ErrorBoundary key={tab} where={`tab ${tab}`}>
{tab === 'releases' && <ReleasesTab app={app} />} {tab === 'releases' && <ReleasesTab app={app} />}
{tab === 'catalog' && app.project && <CatalogTab project={app.project} />} {tab === 'catalog' && app.project && <CatalogTab project={app.project} />}
@ -160,6 +169,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
{tab === 'art' && !app.project && <LiveArt target={app.target} />} {tab === 'art' && !app.project && <LiveArt target={app.target} />}
{tab === 'health' && <HealthTab app={app} />} {tab === 'health' && <HealthTab app={app} />}
{tab === 'reviews' && <ReviewsTab app={app} />} {tab === 'reviews' && <ReviewsTab app={app} />}
{tab === 'games' && app.project && <GamesTab project={app.project} />}
{tab === 'testflight' && <TestFlightTab app={app} />} {tab === 'testflight' && <TestFlightTab app={app} />}
{tab === 'growth' && <GrowthTab app={app} />} {tab === 'growth' && <GrowthTab app={app} />}
{tab === 'appinfo' && app.project && <AppInfoTab project={app.project} />} {tab === 'appinfo' && app.project && <AppInfoTab project={app.project} />}

View file

@ -6,12 +6,15 @@ import { type AndroidSdkLookup, api, type DownloadInfo, errorText, type LocalToo
import { t } from '../i18n'; import { t } from '../i18n';
import { bytes } from '../lib/format'; import { bytes } from '../lib/format';
import { shortPath } from '../paths'; import { shortPath } from '../paths';
import { useData } from '../store'; import { useData, useReadState } from '../store';
import { Icon, type IconName } from '../ui/icons'; import { Icon, type IconName } from '../ui/icons';
import { Chip, Notice, Skeleton } from '../ui/kit'; import { Chip, Notice, Skeleton } from '../ui/kit';
import { PageHeader, Section, StatTile, StatusPill } from '../ui/ds'; import { PageHeader, Section, StatTile, StatusPill } from '../ui/ds';
import '../styles/deps.css'; import '../styles/deps.css';
/** The local tools check (system.tools): one registry key. */
const TOOLS_KEY = '*\u001fsystem.tools';
const TOOL_ICON: Record<string, IconName> = { ffmpeg: 'image', ffprobe: 'search', chrome: 'globe', xcode: 'terminal', simctl: 'phone', adb: 'phone', git: 'layers' }; const TOOL_ICON: Record<string, IconName> = { ffmpeg: 'image', ffprobe: 'search', chrome: 'globe', xcode: 'terminal', simctl: 'phone', adb: 'phone', git: 'layers' };
/** Status chip of one tool. */ /** Status chip of one tool. */
@ -29,16 +32,18 @@ export function Dependencies() {
const [sdk, setSdk] = useState<AndroidSdkLookup | null>(d.sidecar?.tools?.androidSdk ?? null); const [sdk, setSdk] = useState<AndroidSdkLookup | null>(d.sidecar?.tools?.androidSdk ?? null);
const [info, setInfo] = useState<DownloadInfo[]>([]); const [info, setInfo] = useState<DownloadInfo[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false); // local tools check: one registry key, so a second click (or a remount) joins the check in flight
const busy = useReadState(TOOLS_KEY).busy;
const [dl, setDl] = useState<Record<string, Dl>>({}); const [dl, setDl] = useState<Record<string, Dl>>({});
const reg = d.registry;
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
setBusy(true); setError(null); setError(null);
try { try {
const [s, i] = await Promise.all([api.call<LocalTools>('system.tools'), api.toolsInfo()]); const [s, i] = await reg.read({ key: TOOLS_KEY, lanes: ['local'], accounts: [], priority: 0, run: () => Promise.all([api.call<LocalTools>('system.tools'), api.toolsInfo()]) }, { force: true });
setTools(s.tools); setInfo(i); setSdk(s.androidSdk ?? null); setTools(s.tools); setInfo(i); setSdk(s.androidSdk ?? null);
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } } catch (e) { setError(errorText(e)); }
}, []); }, [reg]);
useEffect(() => { refresh(); }, [refresh]); useEffect(() => { refresh(); }, [refresh]);
useEffect(() => { useEffect(() => {
const un = onDownload(e => setDl(m => { const un = onDownload(e => setDl(m => {

View file

@ -30,7 +30,7 @@ export function Ignored() {
{apps.map(a => { {apps.map(a => {
const s = d.studios.find(x => x.id === a.studio) ?? null; const s = d.studios.find(x => x.id === a.studio) ?? null;
return ( return (
<div className="li" key={a.key} {...cm(() => appMenu(a, d, nav, { showIgnored: true }))}> <div className="li" key={a.key} {...cm(() => appMenu(a, d, nav, { showIgnored: true }), `app:${a.key}`)}>
<AppIcon name={a.name} src={d.iconFor(a)} /> <AppIcon name={a.name} src={d.iconFor(a)} />
<div className="li-main"> <div className="li-main">
<span className="li-title row" style={{ gap: 8 }}>{a.name}{!a.project && <StoreOnlyTag />}</span> <span className="li-title row" style={{ gap: 8 }}>{a.name}{!a.project && <StoreOnlyTag />}</span>

View file

@ -4,8 +4,8 @@
// version, crash rate, catalog parity, config check), grouped by studio; then what changed and what to fix first. // version, crash rate, catalog parity, config check), grouped by studio; then what changed and what to fix first.
import { plainError } from '../../../../cli/lib/google-errors'; import { plainError } from '../../../../cli/lib/google-errors';
import { BlockedProjectsNotice, blockedProjects } from '../ui/StoreError'; import { BlockedProjectsNotice, blockedProjects } from '../ui/StoreError';
import { type ReactNode, useEffect, useMemo, useState } from 'react'; import { type ReactNode, useEffect, useMemo, useRef, useState } from 'react';
import { api, type AppStatus, newJob, type StoreRelease, type ToolResult } from '../api'; import { api, type AppStatus, type StoreRelease, type ToolResult } from '../api';
import { type Key, t } from '../i18n'; import { type Key, t } from '../i18n';
import { ago, pct, share } from '../lib/format'; import { ago, pct, share } from '../lib/format';
import { useShowIgnored } from '../lib/show-ignored'; import { useShowIgnored } from '../lib/show-ignored';
@ -15,13 +15,16 @@ import { type AppTab, useNav } from '../nav';
import { useContextMenu } from '../ui/ContextMenu'; import { useContextMenu } from '../ui/ContextMenu';
import { appMenu } from '../ui/app-menu'; import { appMenu } from '../ui/app-menu';
import type { IconName } from '../ui/icons'; import type { IconName } from '../ui/icons';
import { useData } from '../store'; import { useData, useReadState } from '../store';
import { ImportAppsButton } from '../ui/ReadButtons';
import { readKey } from '../lib/freshness';
import { PORTFOLIO_KEY } from '../lib/read-registry';
import { exportName, portfolioCsv } from '../lib/exports'; import { exportName, portfolioCsv } from '../lib/exports';
import { useExports } from '../ui/Exports'; import { useExports } from '../ui/Exports';
import { Icon, StoreGlyph } from '../ui/icons'; import { Icon, StoreGlyph } from '../ui/icons';
import { nextStep, Pipeline, tintStyle, useShots, useTint } from '../ui/ds'; import { nextStep, Pipeline, tintStyle, useShots, useTint } from '../ui/ds';
export { nextStep } from '../ui/ds'; export { nextStep } from '../ui/ds';
import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Seg, Skeleton, Sparkline, StudioMark } from '../ui/kit'; import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, phaseLabel, Seg, Skeleton, Sparkline, StudioMark } from '../ui/kit';
/** Tag of one app's offline config check. */ /** Tag of one app's offline config check. */
export function checkState(e: Pick<AppStatus, 'errors' | 'check'> | undefined): { text: string; tone: Tone } { export function checkState(e: Pick<AppStatus, 'errors' | 'check'> | undefined): { text: string; tone: Tone } {
@ -69,7 +72,7 @@ function NextCell({ e }: { e: AppStatus | undefined }) {
<span className="strong num">{n.version}</span> <span className="strong num">{n.version}</span>
<div className="row small muted" style={{ gap: 10 }}> <div className="row small muted" style={{ gap: 10 }}>
{n.ios && <span className="row" style={{ gap: 4 }}><StoreGlyph store="ios" className="ic13" />{t(`phase.${n.ios.phase}`)}</span>} {n.ios && <span className="row" style={{ gap: 4 }}><StoreGlyph store="ios" className="ic13" />{t(`phase.${n.ios.phase}`)}</span>}
{n.android && <span className="row" style={{ gap: 4 }}><StoreGlyph store="android" className="ic13" />{t(`phase.${n.android.phase}`)}</span>} {n.android && <span className="row" style={{ gap: 4 }}><StoreGlyph store="android" className="ic13" />{phaseLabel(n.android).text}</span>}
</div> </div>
</div> </div>
); );
@ -150,7 +153,7 @@ function AppCard({ r, icon, health, studio }: { r: CardRow; icon: string | null;
const menu = useContextMenu(); const menu = useContextMenu();
const [showIgnored] = useShowIgnored(); const [showIgnored] = useShowIgnored();
return ( return (
<article className="pf-card" style={style} aria-label={name} {...menu(() => appMenu(app, d, nav, { showIgnored }))}> <article className="pf-card" style={style} aria-label={name} {...menu(() => appMenu(app, d, nav, { showIgnored }), `app:${app.key}`)}>
<div className={`pf-shots${shots.length ? '' : ' empty'}`} aria-hidden="true"> <div className={`pf-shots${shots.length ? '' : ' empty'}`} aria-hidden="true">
{shots.length ? shots.map((s, i) => <img key={i} src={s} alt="" draggable={false} loading="lazy" />) : <> {shots.length ? shots.map((s, i) => <img key={i} src={s} alt="" draggable={false} loading="lazy" />) : <>
<AppIcon name={app.name} src={icon} className="pf-hero-icon" /> <AppIcon name={app.name} src={icon} className="pf-hero-icon" />
@ -302,20 +305,25 @@ export function Portfolio() {
const [showIgnored, setShowIgnored] = useShowIgnored(); const [showIgnored, setShowIgnored] = useShowIgnored();
const menu = useContextMenu(); const menu = useContextMenu();
const [round, setRound] = useState(0); const [round, setRound] = useState(0);
const [rechecking, setRechecking] = useState(false);
const health = useCachedHealth(visible.map(a => a.target), round); const health = useCachedHealth(visible.map(a => a.target), round);
const blocked = useMemo(() => blockedProjects(visible.map(a => { const blocked = useMemo(() => blockedProjects(visible.map(a => {
const h = health[a.target]?.h, l = d.liveFor(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] }; return { app: a.name, errors: [h?.play && isError(h.play) ? h.play : null, l?.storeErrors.android] };
})), [visible, health, d]); })), [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 // "Check again": the health reads of the blocked apps (the same keys as their Health tab's refresh and Refresh all),
const recheck = async () => { // plus the portfolio read when a blocked store came from it. Busy (and disabled) whenever any of these keys is in
setRechecking(true); // flight, whoever started it; a click joins what runs and the scheduler spaces the rest (one Cloud project's quota).
const names = new Set(blocked.flatMap(b => b.apps)); const blockedApps = useMemo(() => { const names = new Set(blocked.flatMap(b => b.apps)); return visible.filter(x => names.has(x.name)); }, [blocked, visible]);
for (const a of visible.filter(x => names.has(x.name))) await api.call<ToolResult>('health', a.target, { args: {} }, newJob('health')).catch(() => null); const fromLive = blockedApps.some(a => !!d.liveFor(a)?.storeErrors.android);
setRechecking(false); const checkKeys = useMemo(() => [...blockedApps.map(a => readKey(a.target, 'health', {})), ...(fromLive ? [PORTFOLIO_KEY] : [])], [blockedApps, fromLive]);
setRound(n => n + 1); const checkReads = useReadState({ keys: checkKeys });
const recheck = () => {
Promise.allSettled([...blockedApps.map(a => d.schedule(a.target, 'health', {}, 0)), ...(fromLive ? [d.refreshPortfolio(true)] : [])]).catch(() => {});
}; };
// whoever read them (this button, Refresh all, a Health tab), the notice looks at the saved health again after
const wasBusy = useRef(false);
useEffect(() => { if (wasBusy.current && !checkReads.busy) setRound(n => n + 1); wasBusy.current = checkReads.busy; }, [checkReads.busy]);
const allReads = useReadState({ tags: ['all'] });
const open = (a: UnifiedApp) => nav.go({ screen: 'app', appId: a.key, tab: 'releases' }); const open = (a: UnifiedApp) => nav.go({ screen: 'app', appId: a.key, tab: 'releases' });
const all = useMemo(() => visible.map(app => { const all = useMemo(() => visible.map(app => {
@ -365,7 +373,7 @@ export function Portfolio() {
const ios = !!(app.ios || e?.app?.platforms.ios), android = !!(app.android || e?.app?.platforms.android); 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 ?? ''; const sub = app.ios?.app.bundleId ?? e?.app?.platforms.ios?.bundleId ?? app.android?.app.id ?? e?.app?.platforms.android?.packageName ?? '';
return ( return (
<tr key={app.key} className="clickable" onClick={() => open(app)} {...menu(() => appMenu(app, d, nav, { showIgnored }))}> <tr key={app.key} className="clickable" onClick={() => open(app)} {...menu(() => appMenu(app, d, nav, { showIgnored }), `app:${app.key}`)}>
<td> <td>
<div className="cell-app"> <div className="cell-app">
<AppIcon name={app.name} src={d.iconFor(app)} /> <AppIcon name={app.name} src={d.iconFor(app)} />
@ -411,14 +419,14 @@ export function Portfolio() {
<p>{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}{d.live ? ` · ${t('pf.readAgo', { when: ago(d.live.at) })}` : ''}</p> <p>{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}{d.live ? ` · ${t('pf.readAgo', { when: ago(d.live.at) })}` : ''}</p>
</div> </div>
<div className="actions"> <div className="actions">
{neverImported === 0 && <button className="btn" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length} title={t('action.importAppsHint')}><Icon name="download" className={d.importBusy ? 'spin' : undefined} />{t('action.importApps')}</button>} {neverImported === 0 && <ImportAppsButton className="btn" />}
</div> </div>
</div> </div>
{d.portfolioError && <Notice tone="bad">{d.portfolioError}</Notice>} {d.portfolioError && <Notice tone="bad">{d.portfolioError}</Notice>}
<BlockedProjectsNotice blocked={blocked} onRetry={recheck} busy={rechecking} /> <BlockedProjectsNotice blocked={blocked} onRetry={recheck} busy={checkReads.busy} />
{neverImported > 0 && <Notice tone="info" icon="download" action={<button className="btn btn-sm" onClick={() => d.importApps()} disabled={d.importBusy}>{t('action.importApps')}</button>}>{t('portfolio.notImported', { count: neverImported })}</Notice>} {neverImported > 0 && <Notice tone="info" icon="download" action={<ImportAppsButton />}>{t('portfolio.notImported', { count: neverImported })}</Notice>}
{!known && d.ready && d.portfolioBusy !== 'live' && <Notice tone="info" action={<button className="btn btn-sm btn-primary" onClick={() => { d.readAll(true).catch(() => {}); }}>{t('action.readStores')}</button>}>{t('portfolio.notReadNotice')}</Notice>} {!known && d.ready && d.portfolioBusy !== 'live' && <Notice tone="info" action={<button className="btn btn-sm btn-primary" onClick={() => { d.readAll(true).catch(() => {}); }} disabled={allReads.busy} aria-busy={allReads.busy}><Icon name="refresh" className={allReads.busy ? 'spin' : undefined} />{t('action.readStores')}</button>}>{t('portfolio.notReadNotice')}</Notice>}
<div className="kpis"> <div className="kpis">
<Kpi icon="layers" label={t('kpi.apps')} value={rows.length} sub={t('kpi.appsSubStore', { ios: iosApps, android: androidApps, store: storeOnly })} /> <Kpi icon="layers" label={t('kpi.apps')} value={rows.length} sub={t('kpi.appsSubStore', { ios: iosApps, android: androidApps, store: storeOnly })} />
@ -448,7 +456,7 @@ export function Portfolio() {
<button className="link" aria-pressed={showIgnored} onClick={() => setShowIgnored(!showIgnored)}>{showIgnored ? t('ignored.hide', { count: ignoredApps.length }) : t('ignored.show', { count: ignoredApps.length })}</button> <button className="link" aria-pressed={showIgnored} onClick={() => setShowIgnored(!showIgnored)}>{showIgnored ? t('ignored.hide', { count: ignoredApps.length }) : t('ignored.show', { count: ignoredApps.length })}</button>
{showIgnored && ignoredApps.map(a => ( {showIgnored && ignoredApps.map(a => (
<span key={a.key} className="row muted" style={{ gap: 4 }}> <span key={a.key} className="row muted" style={{ gap: 4 }}>
<button className="link" onClick={() => open(a)} {...menu(() => appMenu(a, d, nav, { showIgnored }))}>{a.name}</button> <button className="link" onClick={() => open(a)} {...menu(() => appMenu(a, d, nav, { showIgnored }), `app:${a.key}`)}>{a.name}</button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => d.updateOverrides(o => withIgnored(o, a.ignoreKeys, false))} aria-label={t('ignored.restore')} title={t('ignored.restore')}><Icon name="eye" /></button> <button className="btn btn-sm btn-ghost btn-icon" onClick={() => d.updateOverrides(o => withIgnored(o, a.ignoreKeys, false))} aria-label={t('ignored.restore')} title={t('ignored.restore')}><Icon name="eye" /></button>
</span> </span>
))} ))}

View file

@ -0,0 +1,60 @@
// The header of one app section (docs IA): the section's name, one line on what it is for, the single next step
// derived from state that is already read (lib/sections.ts), and the sub views as a segmented control (only when the
// section has more than one).
import type { ListingsResult, StoreRelease } from '../api';
import { t } from '../i18n';
import type { UnifiedApp } from '../lib/identity';
import type { Attention } from '../lib/model';
import { sectionNext } from '../lib/sections';
import { type AppSection, type AppTab, SECTION_ICON, SECTION_KEY, TAB_ICON, TAB_KEY } from '../nav';
import { useCachedRead, useData } from '../store';
import type { GameServicesStatus } from '../ui/GameServicesCard';
import { Icon } from '../ui/icons';
const PURPOSE: Record<AppSection, 'sec.release.for' | 'sec.store.for' | 'sec.revenue.for' | 'sec.players.for' | 'sec.health.for'> = {
release: 'sec.release.for', store: 'sec.store.for', revenue: 'sec.revenue.for', players: 'sec.players.for', health: 'sec.health.for',
};
export function SectionHead({ app, section, tab, subs, att, all, next, unsaved, editCount, onTab }: {
app: UnifiedApp; section: AppSection; tab: AppTab; subs: AppTab[]; att: Attention[]; all: StoreRelease[]; next: string | null; unsaved: number;
editCount: (t: AppTab) => number; onTab: (t: AppTab) => void;
}) {
const d = useData();
const e = d.statusFor(app);
const pid = app.project && !app.project.missing ? app.project.id : null;
// cached reads only: the header never starts a store call
const listings = useCachedRead<ListingsResult>(section === 'store' ? pid : null, 'project.listings');
const reviews = useCachedRead<{ reply?: unknown }[]>(section === 'players' ? app.target : null, 'reviews.list', { days: 30 });
const games = useCachedRead<GameServicesStatus>(section === 'players' && subs.includes('games') ? pid : null, 'games.status');
const validate = useCachedRead<{ findings?: { level: string }[] }>(section === 'health' || section === 'release' ? pid : null, 'validate');
const n = sectionNext(section, {
project: !!app.project, att, all, next, summary: e?.summary ?? null, catalog: (d.liveFor(app) ?? e)?.catalog ?? null, unsaved, listings,
reviews: Array.isArray(reviews) ? reviews : null, readiness: validate?.findings ? validate.findings.filter(f => f.level === 'blocker').length : null,
games: games ? { changes: (games.apple?.changes.length ?? 0) + (games.play?.changes.length ?? 0), blockers: games.findings.filter(f => f.level === 'error').length, apiOff: !!games.playApiDisabled } : null,
});
return (
<div className="sec-head" data-testid="section-head">
<div className="sec-head-t">
<h2 className="sec-head-name"><Icon name={SECTION_ICON[section]} />{t(SECTION_KEY[section])}</h2>
<p className="sec-head-for">{t(PURPOSE[section])}</p>
</div>
<div className={`sec-next tone-${n.tone}`} role="status" data-testid="section-next">
<Icon name={n.icon} />
<span className="sec-next-t">{n.text}</span>
{n.tab && n.tab !== tab && <button className="btn btn-sm" onClick={() => onTab(n.tab!)}>{t('next.open', { where: t(TAB_KEY[n.tab]) })}<Icon name="arrowRight" /></button>}
</div>
{subs.length > 1 && (
<div className="seg sec-subs" role="group" aria-label={t('sec.views', { section: t(SECTION_KEY[section]) })}>
{subs.map(x => {
const c = editCount(x);
return (
<button key={x} id={`sub-${x}`} type="button" aria-pressed={tab === x} aria-controls="tabpanel" onClick={() => onTab(x)}>
<Icon name={TAB_ICON[x]} />{t(TAB_KEY[x])}{c > 0 && <span className="ed-dot" title={t('ed.unsaved', { count: c })} />}
</button>
);
})}
</div>
)}
</div>
);
}

View file

@ -12,6 +12,7 @@ import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/id
import { useNav } from '../nav'; import { useNav } from '../nav';
import { usePrefs } from '../prefs-ctx'; import { usePrefs } from '../prefs-ctx';
import { useData } from '../store'; import { useData } from '../store';
import { ImportAppsButton, RefreshAllButton } from '../ui/ReadButtons';
import { Icon, type IconName, StoreGlyph } from '../ui/icons'; import { Icon, type IconName, StoreGlyph } from '../ui/icons';
import { AppIcon, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit'; import { AppIcon, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit';
@ -153,8 +154,8 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
{[1, 2, 3, 4, 6, 8].map(n => <option key={n} value={n}>{n}</option>)} {[1, 2, 3, 4, 6, 8].map(n => <option key={n} value={n}>{n}</option>)}
</select><span className="hint">{t('set.parallelHint')}</span></div> </select><span className="hint">{t('set.parallelHint')}</span></div>
<div className="actions"> <div className="actions">
<button className="btn btn-sm" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length}><Icon name="download" />{t('action.importApps')}</button> <ImportAppsButton />
<button className="btn btn-sm" onClick={() => { d.readAll(true).catch(() => {}); }}><Icon name="refresh" />{t('action.refreshAll')}</button> <RefreshAllButton />
<span className="small muted">{d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')}</span> <span className="small muted">{d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')}</span>
</div> </div>
</div> </div>
@ -256,7 +257,8 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
<Section id="set-updates" title={t('set.updates')} icon="download" className="set-card"> <Section id="set-updates" title={t('set.updates')} icon="download" className="set-card">
<div className="form"> <div className="form">
<div className="field"><span className="legend">{t('set.channel')}</span> <div className="field"><span className="legend">{t('set.channel')}</span>
<Seg value={s.channel} label={t('set.channel')} onChange={channel => set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} /></div> <Seg value={s.channel} label={t('set.channel')} onChange={channel => set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['dev', t('set.dev')]]} /></div>
{s.channel === 'stable' && /-dev\./.test(d.info?.version ?? '') && <p className="small muted">{t('set.devToStable', { version: d.info!.version })}</p>}
<Updates /> <Updates />
<p className="small muted">{t('set.updatesText')}</p> <p className="small muted">{t('set.updatesText')}</p>
</div> </div>
@ -278,7 +280,7 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
); );
} }
/** Settings > Updates: checks on click only; installs after the host's native dialog (the signature is checked there). */ /** Settings > Updates: Check asks the channel now; Install runs after the host's native dialog (the signature is checked there). The host also checks and installs in the background (lib.rs auto_update). */
function Updates() { function Updates() {
const [info, setInfo] = useState<UpdateInfo | null>(null); const [info, setInfo] = useState<UpdateInfo | null>(null);
const [busy, setBusy] = useState<'check' | 'install' | null>(null); const [busy, setBusy] = useState<'check' | 'install' | null>(null);
@ -293,7 +295,7 @@ function Updates() {
setBusy('install'); setError(null); setBusy('install'); setError(null);
try { await api.updateInstall(version); } catch (e) { setError(errorText(e)); } finally { setBusy(null); setGot(null); } try { await api.updateInstall(version); } catch (e) { setError(errorText(e)); } finally { setBusy(null); setGot(null); }
}; };
const channel = info ? t(info.channel === 'beta' ? 'set.beta' : 'set.stable') : ''; const channel = info ? t(info.channel === 'beta' ? 'set.beta' : info.channel === 'dev' ? 'set.dev' : 'set.stable') : '';
return ( return (
<div className="stack" style={{ gap: 8 }}> <div className="stack" style={{ gap: 8 }}>
{error && <Notice tone="bad">{error}</Notice>} {error && <Notice tone="bad">{error}</Notice>}

View file

@ -23,7 +23,7 @@ export function TabEditor({ tab, project }: { tab: AppTab; project: Project }) {
const r = useEditable(project); const r = useEditable(project);
if (!EDIT_TABS[tab]) return null; if (!EDIT_TABS[tab]) return null;
if (!r.data) return r.error ? <ErrorNotice error={t('ed.loadFailed', { error: r.error })} tone="bad" /> : <Section><Skeleton lines={4} block /></Section>; if (!r.data) return r.error ? <ErrorNotice error={t('ed.loadFailed', { error: r.error })} tone="bad" /> : <Section><Skeleton lines={4} block /></Section>;
const p = { project, data: r.data, onSaved: () => { r.refresh(); } }; const p = { project, data: r.data, onSaved: () => { r.refresh(true); } };
switch (tab) { switch (tab) {
case 'listings': return <ListingEditor {...p} />; case 'listings': return <ListingEditor {...p} />;
case 'appinfo': return <AppInfoEditor {...p} />; case 'appinfo': return <AppInfoEditor {...p} />;

View file

@ -19,7 +19,6 @@ import { Bar, Chip, ErrorNotice, Notice, Skeleton } from '../../ui/kit';
import { EmptyState, Section } from '../../ui/ds'; import { EmptyState, Section } from '../../ui/ds';
import '../../styles/appinfo.css'; import '../../styles/appinfo.css';
import { WriteButton } from '../../ui/WriteButton'; import { WriteButton } from '../../ui/WriteButton';
import { GameServicesCard } from '../../ui/GameServicesCard';
import { ascUrl } from '../AppView'; import { ascUrl } from '../AppView';
const AREA: Record<DeclAsk['area'], Key> = { dataSafety: 'ai.aDataSafety', appPrivacy: 'ai.aAppPrivacy', appInfo: 'ai.aAppInfo', encryption: 'ai.aEncryption', review: 'ai.aReview' }; const AREA: Record<DeclAsk['area'], Key> = { dataSafety: 'ai.aDataSafety', appPrivacy: 'ai.aAppPrivacy', appInfo: 'ai.aAppInfo', encryption: 'ai.aEncryption', review: 'ai.aReview' };
@ -258,7 +257,6 @@ export function AppInfoTab({ project }: { project: Project }) {
</Section> </Section>
</div> </div>
)} )}
<GameServicesCard project={project} />
<ConsoleSteps project={project} stores={d.stores} /> <ConsoleSteps project={project} stores={d.stores} />
<p className="ai-foot">{t('ai.foot', { when: ago(r.at) })}</p> <p className="ai-foot">{t('ai.foot', { when: ago(r.at) })}</p>

View file

@ -0,0 +1,90 @@
// Players > Game services: Game Center (App Store) and Play Games Services (Google Play) for a game, from
// `games status --json` (cli/games-status.ts). The two store panels (switches, ids, counts, sync writes with dry run +
// confirm) are the GameServicesCard; below it one row per leaderboard / achievement with its languages and each
// store's state against the config, the Game Center locale map with suggestions, and the Play API-disabled state with
// the enable link and the console plan.
import { Fragment } from 'react';
import type { Project } from '../../api';
import { t } from '../../i18n';
import { useRead } from '../../store';
import { ConsolePlanButton } from '../../ui/ConsolePlan';
import { EmptyState, Section } from '../../ui/ds';
import { type GameAction, type GameItemRow, GameServicesCard, type GameServicesStatus } from '../../ui/GameServicesCard';
import { Icon, StoreGlyph } from '../../ui/icons';
import { Chip, Notice } from '../../ui/kit';
import { OpenLink } from '../../ui/OpenLink';
const ACTION_TONE: Record<GameAction, 'ok' | 'warn' | 'info'> = { keep: 'ok', update: 'warn', create: 'info' };
const ACTION_KEY = { keep: 'games.keep', update: 'games.update', create: 'games.create' } as const;
function StoreState({ on, plan, read }: { on: boolean; plan: { action: GameAction; changed: string[] } | null; read: boolean }) {
if (!on) return <span className="muted small">{t('games.notOnStore')}</span>;
if (!plan) return <span className="muted small">{read ? t('games.notListed') : t('games.notRead')}</span>;
return <Chip tone={ACTION_TONE[plan.action]} title={plan.changed.length && plan.action !== 'keep' ? plan.changed.join(', ') : undefined}>{t(ACTION_KEY[plan.action])}</Chip>;
}
function ItemsTable({ rows, appleRead, playRead }: { rows: GameItemRow[]; appleRead: boolean; playRead: boolean }) {
return (
<div className="table-wrap">
<table className="table">
<thead><tr>
<th>{t('games.item')}</th><th>{t('games.name')}</th><th className="num">{t('games.points')}</th><th>{t('games.languages')}</th>
<th><span className="row" style={{ gap: 4 }}><StoreGlyph store="ios" className="ic13" />{t('gs.gameCenter')}</span></th>
<th><span className="row" style={{ gap: 4 }}><StoreGlyph store="android" className="ic13" />{t('gs.playGames')}</span></th>
</tr></thead>
<tbody>
{rows.map(r => {
const locs = r.apple?.locales.filter(l => l.action !== 'keep') ?? [];
return (
<tr key={`${r.kind}:${r.id}`}>
<td><span className="row" style={{ gap: 6 }}><Icon name={r.kind === 'leaderboard' ? 'chart' : 'sparkle'} className="ic13" /><span className="mono-id small">{r.id}</span></span>
<div className="small muted">{t(r.kind === 'leaderboard' ? 'games.leaderboard' : 'games.achievement')}{r.hidden ? ` · ${t('games.hidden')}` : ''}</div></td>
<td>{r.name}</td>
<td className="num">{r.points ?? '–'}</td>
<td className="small">{r.locales.join(', ')}{locs.length > 0 && <div className="small muted">{t('games.localeChanges', { list: locs.map(l => `${l.locale} ${t(ACTION_KEY[l.action])}`).join(', ') })}</div>}</td>
<td><StoreState on={r.ios} plan={r.apple} read={appleRead} /></td>
<td><StoreState on={r.android} plan={r.play} read={playRead} /></td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
export function GamesTab({ project }: { project: Project }) {
const r = useRead<GameServicesStatus>(project.id, 'games.status', { network: true, title: t('gs.title') });
const s = r.data;
const rows = s?.items ?? [];
const appleRead = !!s?.apple && !s.apple.error, playRead = !!s?.play && !s.play.error;
const map = s?.localeMap;
return (
<>
{s?.playApiDisabled && (
<Notice tone="bad" icon="alertCircle" action={<div className="actions">
<button className="btn btn-sm btn-primary" onClick={() => r.refresh()} disabled={r.loading}><Icon name="refresh" className={r.loading ? 'spin' : undefined} />{t('games.checkAgain')}</button>
<ConsolePlanButton project={project} form="play-games-services" label={t('gs.setup')} />
</div>}>
<b>{t('games.apiOffTitle')}</b> {t('games.apiOffText', { api: s.playApiDisabled.title })} <OpenLink url={s.playApiDisabled.url} />
</Notice>
)}
<GameServicesCard project={project} read={r} />
<Section title={t('games.itemsTitle')} icon="chart" sub={t('games.itemsSub')}
actions={<button className="btn btn-sm" onClick={() => r.refresh()} disabled={r.loading} aria-busy={r.loading}><Icon name="refresh" className={r.loading ? 'spin' : undefined} />{t('games.refresh')}</button>}>
{rows.length ? <ItemsTable rows={rows} appleRead={appleRead} playRead={playRead} />
: <EmptyState icon="sparkle">{s ? t('games.noItems') : t('games.notReadYet')}</EmptyState>}
<p className="small muted" style={{ marginTop: 10 }}>{t('games.images')}</p>
</Section>
{map && (Object.keys(map.configured).length > 0 || map.suggested.length > 0) && (
<Section title={t('games.localeMap')} icon="globe" sub={t('games.localeMapSub')}>
<dl className="kv">
{Object.entries(map.configured).map(([k, v]) => <Fragment key={`k${k}`}><dt>{k}</dt><dd><span className="mono-id small">{v}</span> <Chip tone="ok">{t('games.mapSet')}</Chip></dd></Fragment>)}
{map.suggested.map(x => <Fragment key={`s${x.id}`}><dt>{x.id}</dt><dd><span className="mono-id small">{x.from} → {x.to}</span> <Chip tone="warn">{t('games.mapSuggested')}</Chip></dd></Fragment>)}
</dl>
{map.suggested.length > 0 && <p className="small muted" style={{ marginTop: 8 }}>{t('games.mapHint', { entries: map.suggested.map(x => `${x.id}: '${x.to}'`).join(', ') })}</p>}
</Section>
)}
</>
);
}

View file

@ -11,6 +11,7 @@ import { WriteButton } from '../../ui/WriteButton';
import { type Key, t } from '../../i18n'; import { type Key, t } from '../../i18n';
import { ago, date, share } from '../../lib/format'; import { ago, date, share } from '../../lib/format';
import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model'; import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model';
import { api } from '../../api';
import { useData, useRead, useWrite } from '../../store'; import { useData, useRead, useWrite } from '../../store';
import { Icon, StoreGlyph } from '../../ui/icons'; import { Icon, StoreGlyph } from '../../ui/icons';
import { RolloutBar } from '../../ui/charts'; import { RolloutBar } from '../../ui/charts';
@ -19,6 +20,8 @@ import { EmptyState, Section, StatusPill, tintStyle, useTint } from '../../ui/ds
import { AppleSubmitCard, PlayProductionCard } from './Submit'; import { AppleSubmitCard, PlayProductionCard } from './Submit';
import { useContextMenu } from '../../ui/ContextMenu'; import { useContextMenu } from '../../ui/ContextMenu';
import { releaseMenu } from '../../ui/app-menu'; import { releaseMenu } from '../../ui/app-menu';
import { consoleUrl } from '../../../../../cli/lib/console-links';
import { PUBLISH_PLAN_HINT } from '../../../../../cli/lib/play-publish';
import '../../styles/releases.css'; import '../../styles/releases.css';
const STAGE_KEY: Record<(typeof STAGES)[number], Key> = { build: 'stage.build', testing: 'stage.testing', review: 'stage.review', live: 'stage.live', rollout: 'stage.rollout' }; const STAGE_KEY: Record<(typeof STAGES)[number], Key> = { build: 'stage.build', testing: 'stage.testing', review: 'stage.review', live: 'stage.live', rollout: 'stage.rollout' };
@ -92,11 +95,24 @@ function LaneRow({ lane, version, st, app }: { lane: Lane; version: string; st:
)} )}
</div> </div>
)} )}
{r && r.store === 'android' && r.managed && r.phase === 'review' && !!r.liveVersion && !r.pageStaleAt && <PublishHint st={st} />}
{r && app.project && <RolloutControls app={app} r={r} />} {r && app.project && <RolloutControls app={app} r={r} />}
</article> </article>
); );
} }
/** Managed publishing: the approved production release waits in Publishing overview ("Publish N changes"). */
function PublishHint({ st }: { st: AppStatus }) {
const a = st.app?.platforms.android;
const url = consoleUrl('play.publishing', { playDeveloperId: a?.developerId, playAppId: a?.appId });
return (
<div className="roll-ctl" data-hint="publish-changes">
<span className="small muted">{t('roll.publishReady', { cmd: PUBLISH_PLAN_HINT })}</span>
<button className="btn btn-sm" onClick={() => { api.openExternal(url).catch(() => {}); }}><Icon name="external" />{t('roll.publishOpen')}</button>
</div>
);
}
const SHARES = [1, 2, 5, 10, 20, 50]; const SHARES = [1, 2, 5, 10, 20, 50];
/** Rollout controls of one store release: Play staged rollout share / halt / resume / complete, iOS phased release /** Rollout controls of one store release: Play staged rollout share / halt / resume / complete, iOS phased release

View file

@ -2,7 +2,7 @@
// overrides, settings, the sidecar, the portfolio (offline check + the last live read from the cache), app icons, and // overrides, settings, the sidecar, the portfolio (offline check + the last live read from the cache), app icons, and
// background jobs shown as toasts with progress and cancel. // background jobs shown as toasts with progress and cancel.
import { askPreview } from './ui/DryRunPreview'; import { askPreview } from './ui/DryRunPreview';
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { import {
type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload, type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload,
onProgress, onTrayAction, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult, onProgress, onTrayAction, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult,
@ -17,6 +17,7 @@ import { normalizeAccounts, normalizeProjects, normalizeWorkspace } from './lib/
import { keepLines, progressOf } from './lib/progress'; import { keepLines, progressOf } from './lib/progress';
import { isStale, lanesOf, looksThrottled, oneLine, readKey, readsFor } from './lib/freshness'; import { isStale, lanesOf, looksThrottled, oneLine, readKey, readsFor } from './lib/freshness';
import { type Outcome, type Priority, ReadScheduler, type ReadTask, type SchedulerStats } from './lib/scheduler'; import { type Outcome, type Priority, ReadScheduler, type ReadTask, type SchedulerStats } from './lib/scheduler';
import { accountCheckKey, affectedReads, appTags, IMPORT_ALL_KEY, importKey, methodOfKey, PORTFOLIO_CHECK_KEY, PORTFOLIO_KEY, READ_ALL_KEY, type ReadQuery, ReadRegistry, type ReadStatus } from './lib/read-registry';
import { fixHint } from './lib/views'; import { fixHint } from './lib/views';
import type { Route } from './nav'; import type { Route } from './nav';
import { withLastGood } from '../../../cli/lib/train'; import { withLastGood } from '../../../cli/lib/train';
@ -90,8 +91,11 @@ export interface Data {
icons: Record<string, string | null>; icons: Record<string, string | null>;
/** Background reader: progress and the App Store Connect quota seen this hour. */ /** Background reader: progress and the App Store Connect quota seen this hour. */
reader: ReaderState; reader: ReaderState;
/** Runs one read through the scheduler (deduped, rate limited); the result also goes to the read bus. */ /** Runs one read through the read registry and the scheduler (single-flight, rate limited, "read just now" memo
schedule: (target: string, method: string, args: Record<string, unknown>, priority: Priority) => Promise<ToolResult>; * unless `force`); the result also goes to the read bus. */
schedule: (target: string, method: string, args: Record<string, unknown>, priority: Priority, force?: boolean) => Promise<ToolResult>;
/** The one read registry (lib/read-registry.ts): every read button asks it through useReadState. */
registry: ReadRegistry;
/** Listens to one read's bus key. */ /** Listens to one read's bus key. */
onRead: (key: string, fn: (e: ReadEvent) => void) => () => void; onRead: (key: string, fn: (e: ReadEvent) => void) => () => void;
isReading: (key: string) => boolean; isReading: (key: string) => boolean;
@ -101,8 +105,8 @@ export interface Data {
muteUntil: number; muteUntil: number;
/** Mutes notifications for `minutes` (0 = unmute). */ /** Mutes notifications for `minutes` (0 = unmute). */
setMute: (minutes: number) => void; setMute: (minutes: number) => void;
/** After a write: the app's reads are read again. */ /** After a write: the reads of the app that `writeMethod` changed are read again (all of them without one). */
invalidate: (target: string) => void; invalidate: (target: string, writeMethod?: string) => void;
/** The app on screen (its reads go first). */ /** The app on screen (its reads go first). */
setFocus: (key: string | null) => void; setFocus: (key: string | null) => void;
/** True when the read succeeded. */ /** True when the read succeeded. */
@ -127,6 +131,8 @@ export interface Data {
} }
const Ctx = createContext<Data | null>(null); const Ctx = createContext<Data | null>(null);
/** The read registry on its own context (DataProvider fills it), so read buttons and tests need only this. */
export const RegistryCtx = createContext<ReadRegistry | null>(null);
export const useData = (): Data => { export const useData = (): Data => {
const d = useContext(Ctx); const d = useContext(Ctx);
if (!d) throw new Error('useData outside DataProvider'); if (!d) throw new Error('useData outside DataProvider');
@ -137,6 +143,9 @@ const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(
/** A failure line with how to fix it, when the error is a known one. */ /** A failure line with how to fix it, when the error is a known one. */
const withHint = (msg: string | undefined): string | undefined => { const h = fixHint(msg); return h && msg ? `${msg} · ${t(h)}` : msg; }; const withHint = (msg: string | undefined): string | undefined => { const h = fixHint(msg); return h && msg ? `${msg} · ${t(h)}` : msg; };
/** The scheduler credential of a store account. */
const credOf = (a: Account): string => `${a.kind === 'play' ? 'play' : 'apple'}:${a.id}`;
const storeName = (s: 'ios' | 'android'): string => (s === 'ios' ? 'App Store' : 'Google Play'); const storeName = (s: 'ios' | 'android'): string => (s === 'ios' ? 'App Store' : 'Google Play');
/** Title and body of the notification of one release change (by kind; a rejection adds the store's reason when it has one). */ /** Title and body of the notification of one release change (by kind; a rejection adds the store's reason when it has one). */
export function releaseText(c: ReleaseChange): [string, string] { export function releaseText(c: ReleaseChange): [string, string] {
@ -164,9 +173,7 @@ export function DataProvider({ children }: { children: ReactNode }) {
const [sidecarError, setSidecarError] = useState<string | null>(null); const [sidecarError, setSidecarError] = useState<string | null>(null);
const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null); const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null);
const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null); const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null);
const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null);
const [portfolioError, setPortfolioError] = useState<string | null>(null); const [portfolioError, setPortfolioError] = useState<string | null>(null);
const [importBusy, setImportBusy] = useState(false);
const [icons, setIcons] = useState<Record<string, string | null>>({}); const [icons, setIcons] = useState<Record<string, string | null>>({});
const [toasts, setToasts] = useState<Toast[]>([]); const [toasts, setToasts] = useState<Toast[]>([]);
const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>()); const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
@ -240,9 +247,30 @@ export function DataProvider({ children }: { children: ReactNode }) {
const appsRef = useRef(apps); const appsRef = useRef(apps);
appsRef.current = apps; appsRef.current = apps;
const refreshPortfolio = useCallback(async (liveRead = false, quiet = false): Promise<boolean> => { // ---- reads: one scheduler (lib/scheduler.ts) under one read registry (lib/read-registry.ts) for every read of the
// window: buttons, notices, cards, the background reader, the tray and Ctrl+K. Same key = one host call (joined);
// a broad read covers its narrow keys; every button renders busy from the registry (useReadState), never its own flag.
const schedRef = useRef<ReadScheduler | null>(null);
if (!schedRef.current) schedRef.current = new ReadScheduler({ classify: classifyRead, limits: { apple: settings.refresh.parallel, play: settings.refresh.parallel } });
const sched = schedRef.current;
const bus = useRef(new Map<string, Set<(e: ReadEvent) => 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 regRef = useRef<ReadRegistry | null>(null);
if (!regRef.current) regRef.current = new ReadRegistry(sched, {
onEvent: (key, e) => emitRead(key, e.kind === 'start' ? e : e.kind === 'done' ? { kind: 'done', result: e.result as ToolResult } : { kind: 'error', error: errorText(e.error) }),
});
const reg = regRef.current;
// the provider's derived busy flags (portfolioBusy, importBusy) follow the registry
const regVer = useSyncExternalStore(reg.subscribe, reg.version, reg.version);
const portfolioBusy: Data['portfolioBusy'] = useMemo(() => (reg.state(PORTFOLIO_KEY).busy ? 'live' : reg.state(PORTFOLIO_CHECK_KEY).busy ? 'offline' : null), [reg, regVer]); // eslint-disable-line react-hooks/exhaustive-deps
const importBusy = useMemo(() => reg.state({ tags: ['import'] }).busy, [reg, regVer]); // eslint-disable-line react-hooks/exhaustive-deps
const accountsRef = useRef(accounts);
accountsRef.current = accounts;
const refreshPortfolio = useCallback((liveRead = false, quiet = false): Promise<boolean> => {
const job = newJob(liveRead ? 'portfolio-live' : 'portfolio'); const job = newJob(liveRead ? 'portfolio-live' : 'portfolio');
setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null); const run = async (): Promise<boolean> => {
setPortfolioError(null);
const tid = liveRead && !quiet ? 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 { try {
const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : []; const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : [];
@ -268,14 +296,15 @@ export function DataProvider({ children }: { children: ReactNode }) {
setPortfolioError(msg); setPortfolioError(msg);
if (tid) updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailed'), detail: msg, progress: undefined, job: undefined }); if (tid) updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailed'), detail: msg, progress: undefined, job: undefined });
return false; return false;
} finally { setBusy(null); } }
return true; return true;
}, [toast, updateToast, notice]); };
// the live read uses every store account (their quota pauses show on its buttons); the offline check is local
return reg.read<boolean>(liveRead
? { key: PORTFOLIO_KEY, tags: ['all', 'portfolio'], lanes: ['apple', 'play'], accounts: accountsRef.current.map(credOf), priority: quiet ? 1 : 0, run, cancel: () => { api.cancel(job).catch(() => {}); } }
: { key: PORTFOLIO_CHECK_KEY, tags: ['portfolio-check'], lanes: ['local'], accounts: [], priority: 0, run }).catch(() => false);
}, [reg, toast, updateToast, notice]);
// ---- background reader: one scheduler for every store read of the window (lib/scheduler.ts) ----
const schedRef = useRef<ReadScheduler | null>(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<SchedulerStats>(() => sched.stats()); const [reader, setReader] = useState<SchedulerStats>(() => sched.stats());
useEffect(() => { useEffect(() => {
let tm: ReturnType<typeof setTimeout> | null = null; let tm: ReturnType<typeof setTimeout> | null = null;
@ -283,14 +312,12 @@ export function DataProvider({ children }: { children: ReactNode }) {
return () => { un(); if (tm) clearTimeout(tm); }; return () => { un(); if (tm) clearTimeout(tm); };
}, [sched]); }, [sched]);
useEffect(() => { sched.setLimits({ apple: settings.refresh.parallel, play: settings.refresh.parallel }); }, [sched, settings.refresh.parallel]); useEffect(() => { sched.setLimits({ apple: settings.refresh.parallel, play: settings.refresh.parallel }); }, [sched, settings.refresh.parallel]);
const bus = useRef(new Map<string, Set<(e: ReadEvent) => 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 onRead = useCallback((key: string, fn: (e: ReadEvent) => void) => {
const set = bus.current.get(key) ?? new Set(); const set = bus.current.get(key) ?? new Set();
set.add(fn); bus.current.set(key, set); set.add(fn); bus.current.set(key, set);
return () => { set.delete(fn); if (!set.size) bus.current.delete(key); }; return () => { set.delete(fn); if (!set.size) bus.current.delete(key); };
}, []); }, []);
const isReading = useCallback((key: string) => sched.has(key), [sched]); const isReading = useCallback((key: string) => reg.active(key), [reg]);
const focusRef = useRef<string | null>(null); const focusRef = useRef<string | null>(null);
const setFocus = useCallback((key: string | null) => { focusRef.current = key; }, []); const setFocus = useCallback((key: string | null) => { focusRef.current = key; }, []);
@ -303,101 +330,124 @@ export function DataProvider({ children }: { children: ReactNode }) {
const statusRef = useRef<(a: UnifiedApp) => AppStatus | undefined>(() => undefined); const statusRef = useRef<(a: UnifiedApp) => AppStatus | undefined>(() => undefined);
const lastData = useRef(new Map<string, unknown>()); const lastData = useRef(new Map<string, unknown>());
const schedule = useCallback((target: string, method: string, args: Record<string, unknown>, priority: Priority): Promise<ToolResult> => { const schedule = useCallback((target: string, method: string, args: Record<string, unknown>, priority: Priority, force = false): Promise<ToolResult> => {
const key = readKey(target, method, args); const key = readKey(target, method, args);
const app = appsRef.current.find(a => a.target === target); const app = appsRef.current.find(a => a.target === target);
const pf = platformsOf(app, app ? statusRef.current(app) : undefined); const pf = platformsOf(app, app ? statusRef.current(app) : undefined);
const lanes = lanesOf(method, pf); const lanes = lanesOf(method, pf);
// reviews and health: compared with the previous read here (not in a card), so the tray app notices them with no window open // reviews and health: compared with the previous read here (not in a card), so the tray app notices them with no window open
const watch = method === 'reviews.list' || method === 'health'; const watch = method === 'reviews.list' || method === 'health';
const job = newJob(method);
const run = async (): Promise<ToolResult> => { const run = async (): Promise<ToolResult> => {
const before = watch ? (lastData.current.has(key) ? lastData.current.get(key) : (await api.cached<ToolResult>(method, target, args).catch(() => null))?.value.data ?? null) : null; const before = watch ? (lastData.current.has(key) ? lastData.current.get(key) : (await api.cached<ToolResult>(method, target, args).catch(() => null))?.value.data ?? null) : null;
const result = await api.call<ToolResult>(method, target, { args }, newJob(method)); const result = await api.call<ToolResult>(method, target, { args }, job);
if (watch && usable(method, result)) { if (watch && usable(method, result)) {
notifyAfterRead(method, before, result.data, notice, app?.name, app?.key); notifyAfterRead(method, before, result.data, notice, app?.name, app?.key);
lastData.current.set(key, result.data); lastData.current.set(key, result.data);
} }
return result; return result;
}; };
const p = sched.enqueue<ToolResult>({ key, lanes, accounts: accountsOf(app, lanes), priority, run }); return reg.read<ToolResult>({ key, tags: appTags(target), lanes, accounts: accountsOf(app, lanes), priority, run, cancel: () => { api.cancel(job).catch(() => {}); } }, { force });
emitRead(key, { kind: 'start' }); }, [reg, notice]);
p.then(result => emitRead(key, { kind: 'done', result }), e => emitRead(key, { kind: 'error', error: errorText(e) }));
return p;
}, [sched, emitRead, notice]);
/** /**
* Reads everything past its TTL. The portfolio read is a LIVE one (refreshPortfolio(true)): it is what releaseChanges * Refresh all (and the background pass): one group read that covers the portfolio and every app read it plans, so
* compares, so a rejection is seen even when no screen asked. Resolves when that read is done: false when it failed. * every button and card of those keys shows busy at once and a click on any of them joins. Single-flight: a second
* Refresh all, the tray's "Read now" or a pass while one runs joins it. Without `force` only reads past their TTL run.
* Resolves when everything it started is done: false when the portfolio read failed.
*/ */
const readAll = useCallback(async (force = false): Promise<boolean> => { const readAll = useCallback(async (force = false): Promise<boolean> => {
if (!force && !settingsRef.current.refresh.autoRead) return true; if (!force && !settingsRef.current.refresh.autoRead) return true;
let ok = true;
let portfolioRead: Promise<void> | null = null;
const pkey = '*\u001fportfolio.status';
if (!sched.has(pkey) && (force || isStale('portfolio.status', liveRef.current?.at))) {
portfolioRead = sched.enqueue<boolean>({ key: pkey, lanes: ['apple', 'play'], accounts: [], priority: 1, run: () => refreshPortfolio(true, true) })
.then(r => { ok = r !== false; }, () => { ok = false; });
}
const list = [...appsRef.current].filter(a => !a.ignored && !a.project?.missing) const list = [...appsRef.current].filter(a => !a.ignored && !a.project?.missing)
.sort((a, b) => Number(b.key === focusRef.current) - Number(a.key === focusRef.current)); .sort((a, b) => Number(b.key === focusRef.current) - Number(a.key === focusRef.current));
for (const a of list) { const planned = list.flatMap(a => readsFor({ folder: !!a.project, ...platformsOf(a, statusRef.current(a)) }).map(r => ({ a, r, key: readKey(a.target, r.method, r.args) })));
const pf = platformsOf(a, statusRef.current(a)); return reg.group<boolean>({
for (const r of readsFor({ folder: !!a.project, ...pf })) { key: READ_ALL_KEY, tags: ['all'], covers: [PORTFOLIO_KEY, ...planned.map(p => p.key)],
const key = readKey(a.target, r.method, r.args); run: async g => {
if (sched.has(key)) continue; const waits: Promise<unknown>[] = [];
if (!force) { let portfolioRead: Promise<boolean> | null = null;
const c = await api.cached<ToolResult>(r.method, a.target, r.args).catch(() => null); g.release(PORTFOLIO_KEY);
if (c && !isStale(r.method, c.at)) continue; if (force || isStale('portfolio.status', liveRef.current?.at)) portfolioRead = refreshPortfolio(true, true);
} // the TTL checks of every key at once (cache reads, local), then the reads that are due, in priority order
schedule(a.target, r.method, r.args, a.key === focusRef.current ? 0 : 2).catch(() => {}); const due = await Promise.all(planned.map(async p => {
} if (force || reg.active(p.key)) return true;
} const c = await api.cached<ToolResult>(p.r.method, p.a.target, p.r.args).catch(() => null);
await portfolioRead; return !(c && !isStale(p.r.method, c.at));
}));
planned.forEach((p, i) => {
g.release(p.key);
if (due[i]) waits.push(schedule(p.a.target, p.r.method, p.r.args, p.a.key === focusRef.current ? 0 : 2).catch(() => {}));
});
const ok = portfolioRead ? await portfolioRead : true;
await Promise.allSettled(waits);
return ok; return ok;
}, [sched, schedule, refreshPortfolio]); },
}).catch(() => false);
}, [reg, schedule, refreshPortfolio]);
const invalidate = useCallback((target: string) => { /** After a write: only the reads it changed (lib/read-registry.ts affectedReads) lose their memo and read again. */
const invalidate = useCallback((target: string, writeMethod?: string) => {
const aff = writeMethod ? affectedReads(writeMethod) : { methods: null, portfolio: true };
const pre = `${target}\u001f`; const pre = `${target}\u001f`;
for (const k of [...bus.current.keys()]) if (k.startsWith(pre)) emitRead(k, { kind: 'invalidate' }); const hits = (k: string) => k.startsWith(pre) && (!aff.methods || aff.methods.includes(methodOfKey(k)));
reg.invalidate(k => hits(k) || (aff.portfolio && (k === PORTFOLIO_KEY || k === PORTFOLIO_CHECK_KEY)));
for (const k of [...bus.current.keys()]) if (hits(k)) emitRead(k, { kind: 'invalidate' });
const a = appsRef.current.find(x => x.target === target); const a = appsRef.current.find(x => x.target === target);
if (a) for (const r of readsFor({ folder: !!a.project, ...platformsOf(a, statusRef.current(a)) })) { if (a) for (const r of readsFor({ folder: !!a.project, ...platformsOf(a, statusRef.current(a)) })) {
const key = readKey(target, r.method, r.args); const key = readKey(target, r.method, r.args);
if (!bus.current.has(key)) schedule(target, r.method, r.args, 1).catch(() => {}); if (hits(key) && !bus.current.has(key)) schedule(target, r.method, r.args, 1, true).catch(() => {});
} }
}, [emitRead, schedule]); }, [reg, emitRead, schedule]);
const importApps = useCallback(async (account?: string) => { /** Import apps: one read per account (key importKey); "all" is a group that covers them, so an account's own
* Import button and the page's Import apps are busy together and never read an account twice. */
const importApps = useCallback(async (account?: string): Promise<void> => {
const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`)); const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`));
if (!ids.length) return; if (!ids.length) return;
const job = newJob('import'); const job = newJob('import');
setImportBusy(true); const readOne = (id: string) => {
const acc = accountsRef.current.find(a => a.id === id);
const cred = acc ? credOf(acc) : `apple:${id}`;
return reg.read<CacheEntry<AppsListResult>>({ key: importKey(id), tags: ['import', `account:${id}`], lanes: [cred.startsWith('play:') ? 'play' : 'apple'], accounts: [cred], priority: 0,
run: () => api.refreshStoreApps(id, job).then(e => { setStoreApps(m => ({ ...m, [id]: e })); return e; }), cancel: () => { api.cancel(job).catch(() => {}); } });
};
// one account whose import is already running (alone or inside Import all): join it, no second toast
if (account && reg.active(importKey(account))) { await readOne(account).catch(() => {}); return; }
const body = async (g?: { release: (k: string) => void }) => {
const tid = toast({ id: job, kind: 'job', title: t('toast.importing'), detail: t('toast.importingDetail'), progress: { done: 0, total: ids.length }, job }); const tid = toast({ id: job, kind: 'job', title: t('toast.importing'), detail: t('toast.importingDetail'), progress: { done: 0, total: ids.length }, job });
let ok = 0, apps = 0; let ok = 0, apps = 0, n = 0, cancelled = false;
const errors: string[] = []; const errors: string[] = [];
for (const [n, id] of ids.entries()) { await Promise.all(ids.map(async id => {
try { g?.release(importKey(id));
const e = await api.refreshStoreApps(id, job); try { const e = await readOne(id); ok++; apps += e.value.apps.length; } catch (e) {
setStoreApps(m => ({ ...m, [id]: e }));
ok++; apps += e.value.apps.length;
} catch (e) {
const msg = errorText(e); const msg = errorText(e);
if (/cancel/i.test(msg)) { updateToast(tid, { kind: 'info', title: t('toast.cancelled'), detail: undefined, progress: undefined, job: undefined }); setImportBusy(false); return; } if (/cancel/i.test(msg)) cancelled = true;
errors.push(`${accounts.find(a => a.id === id)?.label ?? id}: ${msg}`); else errors.push(`${accountsRef.current.find(a => a.id === id)?.label ?? id}: ${msg}`);
} }
updateToast(tid, { progress: { done: n + 1, total: ids.length } }); updateToast(tid, { progress: { done: ++n, total: ids.length } });
} }));
setImportBusy(false); if (cancelled) { updateToast(tid, { kind: 'info', title: t('toast.cancelled'), detail: undefined, progress: undefined, job: undefined }); return; }
updateToast(tid, errors.length ? { kind: ok ? 'info' : 'bad', title: t('toast.importPartial', { count: errors.length }), detail: errors[0], progress: undefined, job: undefined } updateToast(tid, errors.length ? { kind: ok ? 'info' : 'bad', title: t('toast.importPartial', { count: errors.length }), detail: errors[0], progress: undefined, job: undefined }
: { kind: 'ok', title: t('toast.importDone', { count: apps }), detail: t('toast.importDoneDetail', { count: ok }), progress: undefined, job: undefined }); : { kind: 'ok', title: t('toast.importDone', { count: apps }), detail: t('toast.importDoneDetail', { count: ok }), progress: undefined, job: undefined });
}, [accounts, overrides.ignored, toast, updateToast]); };
if (account) { await body(); return; }
await reg.group({ key: IMPORT_ALL_KEY, tags: ['import'], covers: ids.map(importKey), run: g => body(g) }).catch(() => {});
}, [reg, accounts, overrides.ignored, toast, updateToast]);
/** "Test" of one account: single-flight per account (Test all and the row's Test join). */
const checkAccount = useCallback(async (id: string) => { const checkAccount = useCallback(async (id: string) => {
const acc = accountsRef.current.find(a => a.id === id);
const cred = acc ? credOf(acc) : `apple:${id}`;
const job = newJob('check');
await reg.read({ key: accountCheckKey(id), tags: ['check', `account:${id}`], lanes: [cred.startsWith('play:') ? 'play' : 'apple'], accounts: [cred], priority: 0,
run: async () => {
try { try {
const check = await api.checkAccount(id, newJob('check')); const check = await api.checkAccount(id, job);
setAccountHealth(m => ({ ...m, [id]: { check, at: new Date().toISOString() } })); setAccountHealth(m => ({ ...m, [id]: { check, at: new Date().toISOString() } }));
} catch (e) { setAccountHealth(m => ({ ...m, [id]: { error: errorText(e), at: new Date().toISOString() } })); } } catch (e) { setAccountHealth(m => ({ ...m, [id]: { error: errorText(e), at: new Date().toISOString() } })); }
}, []); return null;
} }, { force: true }).catch(() => {});
}, [reg]);
const updateOverrides = useCallback(async (fn: (o: Overrides) => Overrides) => { const updateOverrides = useCallback(async (fn: (o: Overrides) => Overrides) => {
const next = fn(overrides); const next = fn(overrides);
setOverrides(next); setOverrides(next);
@ -534,13 +584,13 @@ export function DataProvider({ children }: { children: ReactNode }) {
const value = useMemo<Data>(() => ({ const value = useMemo<Data>(() => ({
ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError,
importBusy, icons, reader: readerState, muteUntil, setMute, schedule, onRead, isReading, readAll, invalidate, setFocus, importBusy, icons, reader: readerState, muteUntil, setMute, schedule, registry: reg, onRead, isReading, readAll, invalidate, setFocus,
refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
toasts, toast, updateToast, dismiss, cancelJob, toasts, toast, updateToast, dismiss, cancelJob,
}), [readerState, muteUntil, setMute, schedule, onRead, isReading, readAll, invalidate, setFocus, ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, }), [readerState, muteUntil, setMute, 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, importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
toasts, toast, updateToast, dismiss, cancelJob]); toasts, toast, updateToast, dismiss, cancelJob, reg]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>; return <Ctx.Provider value={value}><RegistryCtx.Provider value={reg}>{children}</RegistryCtx.Provider></Ctx.Provider>;
} }
export interface ReadState<T> { export interface ReadState<T> {
@ -554,10 +604,16 @@ export interface ReadState<T> {
error: string | null; error: string | null;
/** The command line it ran (shown with errors). */ /** The command line it ran (shown with errors). */
command: string | null; command: string | null;
refresh: () => Promise<void>; /** Finished less than a few seconds ago: a click answers from it ("read just now"), no second store call. */
justNow?: boolean;
/** Its store account waits on a quota pause or 429 backoff until then (epoch ms). */
pausedUntil?: number | null;
/** Reads again (joins / memo); `true` skips the "read just now" memo. */
refresh: (force?: unknown) => Promise<void>;
} }
export interface WriteRun { method: string; args: Record<string, unknown>; title: string; done: string; after?: () => void } /** preview: false when the screen already showed this dry run (the editors' Review step); the native dialog still follows. */
export interface WriteRun { method: string; args: Record<string, unknown>; title: string; done: string; after?: () => void; preview?: false }
/** /**
* Writes of one app folder: dry run, the native dialog that shows it (Apply / Cancel, or the owner action's own * Writes of one app folder: dry run, the native dialog that shows it (Apply / Cancel, or the owner action's own
@ -575,13 +631,15 @@ export function useWrite(projectId: string | null) {
const tid = d.toast({ id: job, kind: 'job', title: w.title, detail: t('write.dryRunning'), progress: null, job }); const tid = d.toast({ id: job, kind: 'job', title: w.title, detail: t('write.dryRunning'), progress: null, job });
try { try {
// the in-app preview of the dry run first (readable, styled); the host's native dialog stays the real gate // the in-app preview of the dry run first (readable, styled); the host's native dialog stays the real gate
if (w.preview !== false) {
const dry = await api.call<ToolResult>(w.method, projectId, { args: w.args }, job); const dry = await api.call<ToolResult>(w.method, projectId, { args: w.args }, job);
if (!dry.ok) { d.updateToast(tid, { kind: 'bad', title: t('write.dryFailed'), detail: withHint(failureText(dry)), progress: undefined, job: undefined }); return null; } if (!dry.ok) { d.updateToast(tid, { kind: 'bad', title: t('write.dryFailed'), detail: withHint(failureText(dry)), progress: undefined, job: undefined }); return null; }
if (!(await askPreview(w.title, dry))) { d.updateToast(tid, { kind: 'info', title: t('write.notApplied'), detail: t('write.notAppliedDetail'), progress: undefined, job: undefined }); return null; } if (!(await askPreview(w.title, dry))) { d.updateToast(tid, { kind: 'info', title: t('write.notApplied'), detail: t('write.notAppliedDetail'), progress: undefined, job: undefined }); return null; }
}
const o = await api.writeWithConfirm(w.method, projectId, w.args, job); 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 }); 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.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?.(); d.invalidate(projectId); } else if (o.result?.ok) { d.updateToast(tid, { kind: 'ok', title: w.done, detail: lastLine(o.result.output) || undefined, progress: undefined, job: undefined }); d.invalidate(projectId, w.method); w.after?.(); }
// exit 3: the command stopped for an owner decision it did not get (a price change of a live product: the // 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 // 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 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?.(); }
@ -612,42 +670,60 @@ function notifyAfterRead(method: string, prev: unknown, next: unknown, notice: N
} }
} }
/**
* The live state of one read query (a key, several keys, tags such as 'all' or 'import') from the read registry:
* busy while anything overlapping is queued or running (its own read, a broad read covering it, a narrow read of its
* scope), "read just now", the quota pause of its accounts. Every read button, notice and card renders loading and
* disabled from this, never from a local flag. Re-renders on every registry change (useSyncExternalStore).
*/
export function useReadState(q: ReadQuery): ReadStatus {
const reg = useContext(RegistryCtx);
if (!reg) throw new Error('useReadState outside DataProvider');
const ver = useSyncExternalStore(reg.subscribe, reg.version, reg.version);
const qk = typeof q === 'string' ? q : JSON.stringify(q);
return useMemo(() => reg.state(q), [reg, ver, qk]); // eslint-disable-line react-hooks/exhaustive-deps
}
/** /**
* One read method of one app (a project id, or a store-only app's store target). The cached value shows at once with * 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; then, past its TTL (lib/freshness.ts), it is read again through the background scheduler (offline reads * its time; then, past its TTL (lib/freshness.ts), it is read again through the read registry (offline reads always;
* always; store reads while Settings > Reading > auto-read is on). A read the background reader runs for this key * store reads while Settings > Reading > auto-read is on). A read anyone else runs for this key (the background reader,
* lands here too (the read bus). A failed read keeps the last good value and says so: never an empty "all fine". * Refresh all, a write's invalidation) lands here too (the read bus), and `loading` follows the registry: busy whenever
* the key, or a broad read covering it, is in flight. A failed read keeps the last good value and says so.
*/ */
export function useRead<T>(target: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string; appName?: string; skip?: boolean }): ReadState<T> { export function useRead<T>(target: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string; appName?: string; skip?: boolean }): ReadState<T> {
const d = useData(); const d = useData();
const argsKey = JSON.stringify(o.args ?? {}); const argsKey = JSON.stringify(o.args ?? {});
const key = readKey(target, method, JSON.parse(argsKey) as Record<string, unknown>); const key = readKey(target, method, JSON.parse(argsKey) as Record<string, unknown>);
// `loading` here is only the first look into the cache; the read itself is the registry's
const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
const dataRef = useRef<T | null>(null); const st = useReadState(key);
dataRef.current = s.data;
const dRef = useRef(d); const dRef = useRef(d);
dRef.current = d; dRef.current = d;
const skipRef = useRef(o.skip); const skipRef = useRef(o.skip);
skipRef.current = o.skip; skipRef.current = o.skip;
const refresh = useCallback(async () => { const refresh = useCallback(async (force?: unknown) => {
if (skipRef.current) return; if (skipRef.current) return;
set(x => ({ ...x, loading: true })); set(x => ({ ...x, loading: false }));
await dRef.current.schedule(target, method, JSON.parse(argsKey) as Record<string, unknown>, 0).catch(() => {}); // a click: highest priority, joins a read in flight, answered from the memo when it finished just now. The answer
// is applied here too: a join or a memo answer sends no bus event, and a card that mounted after the read (a tab
// opened again) would otherwise wait forever. `force === true` (after a save of this app's files) skips the memo.
const r = await dRef.current.schedule(target, method, JSON.parse(argsKey) as Record<string, unknown>, 0, force === true).catch(() => null);
if (r && usable(method, r)) set(x => (x.data === r.data ? x : { data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, stale: false, error: null, command: r.command }));
}, [target, method, argsKey]); }, [target, method, argsKey]);
// results of this key, whoever asked for them (this card, the background reader, a write's invalidation) // results of this key, whoever asked for them (this card, the background reader, a write's invalidation)
useEffect(() => { useEffect(() => {
if (o.skip) return; if (o.skip) return;
return d.onRead(key, e => { return d.onRead(key, e => {
if (e.kind === 'start') set(x => ({ ...x, loading: true })); if (e.kind === 'start') return;
else if (e.kind === 'invalidate') { set(x => ({ ...x, stale: true })); refresh(); } 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 if (e.kind === 'error') { if (!/cancel/i.test(e.error)) set(x => ({ ...x, error: oneLine(e.error) })); }
else { else {
const r = e.result; const r = e.result;
if (usable(method, r)) { if (usable(method, r)) set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, stale: false, error: null, command: r.command });
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, error: oneLine(failureText(r)), command: r.command }));
} else set(x => ({ ...x, loading: false, error: oneLine(failureText(r)), command: r.command }));
} }
}); });
}, [key, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps }, [key, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps
@ -656,13 +732,12 @@ export function useRead<T>(target: string, method: string, o: { network: boolean
let alive = true; let alive = true;
if (o.skip) { set({ data: null, at: null, fromCache: false, loading: false, error: null, command: null }); return; } 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 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 }); set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
const go = (at: string | null) => { const go = (at: string | null) => {
if (!alive) return; if (!alive) return;
const due = !o.network || isStale(method, at); const due = !o.network || isStale(method, at);
if (running) set(x => ({ ...x, loading: true })); // in flight already (Refresh all, the background reader): the registry shows it busy; nothing to start
else if (auto && due) refresh(); if (!dRef.current.isReading(key) && auto && due) refresh();
else set(x => ({ ...x, loading: false })); else set(x => ({ ...x, loading: false }));
}; };
api.cached<ToolResult>(method, target, JSON.parse(argsKey) as Record<string, unknown>).then(c => { api.cached<ToolResult>(method, target, JSON.parse(argsKey) as Record<string, unknown>).then(c => {
@ -673,5 +748,23 @@ export function useRead<T>(target: string, method: string, o: { network: boolean
return () => { alive = false; }; return () => { alive = false; };
}, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps }, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps
return { ...s, refresh }; return { ...s, loading: !o.skip && (s.loading || st.busy), justNow: st.justNow, pausedUntil: st.pausedUntil, refresh };
}
/** The cached value of one read (and every later result of it), without ever starting a read: for summaries such as a
* section's "what's next" line that must not cost a store call. Null until the read ran once. */
export function useCachedRead<T>(target: string | null, method: string, args: Record<string, unknown> = {}): T | null {
const d = useData();
const argsKey = JSON.stringify(args);
const [v, set] = useState<T | null>(null);
useEffect(() => {
set(null);
if (!target) return;
let alive = true;
const a = JSON.parse(argsKey) as Record<string, unknown>;
api.cached<ToolResult>(method, target, a).then(c => { if (alive && c && c.value.data !== undefined && usable(method, c.value)) set(c.value.data as T); }, () => {});
const un = d.onRead(readKey(target, method, a), e => { if (e.kind === 'done' && usable(method, e.result)) set(e.result.data as T); });
return () => { alive = false; un(); };
}, [target, method, argsKey]); // eslint-disable-line react-hooks/exhaustive-deps
return v;
} }

View file

@ -24,3 +24,5 @@
.scr-accounts .acct-fix { padding: 0 16px 16px; } .scr-accounts .acct-fix { padding: 0 16px 16px; }
.scr-accounts .acct-add { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 18px; align-items: start; } .scr-accounts .acct-add { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 18px; align-items: start; }
.scr-accounts .acct-add .form { gap: 14px; } .scr-accounts .acct-add .form { gap: 14px; }
.scr-accounts .acct-grants ul { margin: 4px 0 0; padding-left: 18px; display: grid; gap: 2px; }
.scr-accounts .acct-grants li { overflow-wrap: anywhere; }

Some files were not shown because too many files have changed in this diff Show more