Compare commits
No commits in common. "main" and "v0.6.0" have entirely different histories.
|
|
@ -9,7 +9,7 @@
|
|||
"name": "storebound",
|
||||
"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.",
|
||||
"version": "0.8.78",
|
||||
"version": "0.6.0",
|
||||
"category": "development",
|
||||
"tags": [
|
||||
"mobile",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "storebound",
|
||||
"version": "0.8.78",
|
||||
"version": "0.6.0",
|
||||
"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": {
|
||||
"name": "CRTkafa"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "storebound",
|
||||
"version": "0.8.78",
|
||||
"version": "0.6.0",
|
||||
"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": {
|
||||
"name": "CRTkafa"
|
||||
|
|
|
|||
|
|
@ -7,53 +7,13 @@ alwaysApply: false
|
|||
|
||||
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
|
||||
|
||||
## First rule: do it, don't ask
|
||||
|
||||
storebound plus you, the AI agent, do the work. The owner is not your pair of hands.
|
||||
|
||||
1. **You do everything yourself:** API calls, uploads, builds, template and CSV downloads and exports, every console
|
||||
navigation (open, Get Started, Edit, Next, Continue, Save draft), console forms, and the verification afterwards.
|
||||
Never tell the owner "run this yourself" or "click X yourself" for any of these.
|
||||
2. **The owner keeps only the final public or irreversible buttons:** Submit for review (App Review or Beta App
|
||||
Review), releasing a version or completing / resuming a production rollout, App Privacy Publish, accepting legal
|
||||
agreements; plus deleting store data, changing live prices, sending review replies and inviting or removing
|
||||
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
|
||||
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:
|
||||
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
|
||||
`.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so.
|
||||
3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety,
|
||||
App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start
|
||||
(`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that
|
||||
are already in the config.
|
||||
4. **Default loop:** plan, then you drive (the API first, your browser tool for consoles without an API), then verify
|
||||
(read it back), then continue. No round trip to the owner in between.
|
||||
5. **Catch rejections offline.** Before a write, `storebound check` and `--dry` must catch what the store would refuse
|
||||
(live-shape fixtures, id and pair checks). A failure belongs in the dry run, not in a 400 at write time; when a
|
||||
store refuses something the dry run passed, fix the check (pitfalls), not just the data.
|
||||
|
||||
Every hour of "please click this" is an hour the owner did not want to spend. If you catch yourself writing "you
|
||||
need to ...", do it instead, unless it is one of the owner steps in point 2.
|
||||
|
||||
## The other rules
|
||||
|
||||
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
|
||||
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
|
||||
|
||||
1. **The owner presses only the owner steps** (point 2 of the first rule). Prepare them completely, say what will
|
||||
happen, and let the owner press the button, or run the command only after a clear yes in chat. storebound's MCP
|
||||
server does not offer these at all. Everything else you run yourself.
|
||||
2. **Dry run first, then run it yourself.** Every write command has `--dry` (MCP: `dry_run`, default true). Run the
|
||||
dry run, check and show it (the rows that change, not just a count), then run the real command yourself (`--yes`
|
||||
where it asks for a confirmation) and read the result back. Wait for the owner's yes only before an owner step.
|
||||
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review),
|
||||
releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings,
|
||||
accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping
|
||||
a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in
|
||||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
|
|
@ -61,8 +21,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
target audience: ask the owner when the code does not prove the answer, all such questions in one batch at the
|
||||
start (first rule, point 3), and write the answers into the config. A wrong "no" is worse than a slow "ask".
|
||||
target audience: ask the owner when the code does not prove the answer. A wrong "no" is worse than a slow "ask".
|
||||
6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest".
|
||||
7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and
|
||||
you report the progress lines, not guesses.
|
||||
|
|
@ -71,20 +30,10 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in
|
||||
`.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits,
|
||||
and never ask for tester emails in chat (storebound masks them in its output).
|
||||
10. **Console forms without an API: drive them yourself, agent-first.** `storebound console plan <form> --json` (MCP
|
||||
`console_plan`) gives the start URL, steps, the answer sheet, the buttons you must never press and the verified UI
|
||||
facts. Drive the page with your own browser tool, adapt to what it shows, run long flows as an in-page async loop
|
||||
that writes `window.__log` (one evaluate call times out around 45 s), stop only before the final button (Publish,
|
||||
Submit, Create, a final Save) and tell the owner exactly what to press, then `storebound console verify <form>`.
|
||||
Never sign in, accept an agreement or grant a permission (a service account's app access) for the owner.
|
||||
`storebound console fill` is the optional scripted fast path; it never blocks you.
|
||||
11. **Console pages: always the absolute deep link.** When you send the owner to a console page, give the absolute
|
||||
deep link (storebound prints it; `storebound console plan` has start URLs), never just "go to App Store Connect"
|
||||
or "App Store Connect > App Information" alone.
|
||||
|
||||
## Tools
|
||||
|
||||
- CLI: `storebound <command>` (`storebound help`; outside the plugin: `npx storebound` on Node 20+ or `bunx storebound` on Bun); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
|
@ -102,17 +51,14 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
- `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game
|
||||
- `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text
|
||||
- `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
|
||||
- `skills/console-autofill/SKILL.md`: Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default
|
||||
- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes
|
||||
- `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly
|
||||
- `skills/game-services/SKILL.md`: Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section
|
||||
- `skills/listing-localization/SKILL.md`: Translate the store listing of a mobile app or game into more languages
|
||||
- `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane`
|
||||
- `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game
|
||||
- `skills/portfolio-originality/SKILL.md`: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins)
|
||||
- `skills/ppp-pricing/SKILL.md`: Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp`
|
||||
- `skills/privacy-manifest/SKILL.md`: Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game
|
||||
- `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games
|
||||
- `skills/release-flows/SKILL.md`: Repo-local workflows for a mobile app or game
|
||||
- `skills/release-management/SKILL.md`: Ship updates safely after the first release
|
||||
- `skills/revenuecat-sync/SKILL.md`: Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config
|
||||
- `skills/review-access/SKILL.md`: Give App Store and Google Play reviewers working access to an app behind a sign-in
|
||||
|
|
@ -123,7 +69,6 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game
|
||||
- `skills/store-health/SKILL.md`: Watch a released mobile app's or game's crash and ANR health on both stores
|
||||
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
||||
- `skills/store-pitfalls/SKILL.md`: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each
|
||||
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile app or game
|
||||
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages
|
||||
- `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
# `bun run ci` after .forgejo/actions/linux-setup: the target / timings caches, bun install, Node 20 (the npm bundle's oldest supported Node) and the full CI. Shared by ci.yml and release.yml.
|
||||
name: ci-run
|
||||
description: storebound's full CI (bun run ci) on the Linux runner
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: apps/desktop/src-tauri/target
|
||||
key: ci-target-${{ runner.os }}-${{ hashFiles('apps/desktop/src-tauri/Cargo.lock') }}
|
||||
restore-keys: ci-target-${{ runner.os }}-
|
||||
# recorded test durations (shard balance) and tsc's incremental build info
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules/.cache/storebound-ci
|
||||
key: ci-timings-${{ runner.os }}-${{ github.sha }}
|
||||
restore-keys: ci-timings-${{ runner.os }}-
|
||||
- name: Install
|
||||
shell: bash
|
||||
run: |
|
||||
bun --version && cargo --version
|
||||
bun install --frozen-lockfile
|
||||
# the npm bundle runs on Node 20+: tools/ci.ts smoke-tests dist/storebound.mjs with the oldest supported Node
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
# no browser tests in CI (tests/browser/ runs only with `bun run test:browser`); the changes of this push (against
|
||||
# its parent; the checkout has fetch-depth 2) decide the Rust steps, as on a laptop against origin/main
|
||||
- name: bun run ci
|
||||
shell: bash
|
||||
run: STOREBOUND_CI_BASE=HEAD~1 bun run ci
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
# Shared setup of the Linux jobs (ci.yml; release.yml's ci and linux jobs) on the VDS runner (label ubuntu-22.04, the
|
||||
# catthehacker act image): Tauri's system packages plus `packages`, the Bun / Cargo caches, Bun and Rust on PATH.
|
||||
name: linux-setup
|
||||
description: System packages, caches, Bun and Rust for storebound's Linux jobs
|
||||
inputs:
|
||||
packages:
|
||||
description: Extra apt packages
|
||||
default: ''
|
||||
cache-key:
|
||||
description: Cache key prefix (separate caches for CI and the installer build)
|
||||
default: ci
|
||||
rust-components:
|
||||
description: Extra rustup components (for example clippy)
|
||||
default: ''
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: System packages
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev \
|
||||
libayatana-appindicator3-dev librsvg2-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libssl-dev libxdo-dev \
|
||||
build-essential curl unzip pkg-config ${{ inputs.packages }} >/dev/null
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
~/.cache/tauri
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
key: ${{ inputs.cache-key }}-${{ runner.os }}-${{ hashFiles('bun.lock', 'apps/desktop/src-tauri/Cargo.lock') }}
|
||||
restore-keys: ${{ inputs.cache-key }}-${{ runner.os }}-
|
||||
- name: Bun and Rust
|
||||
shell: bash
|
||||
run: |
|
||||
P="${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
bash tools/ci-install-bun.sh
|
||||
echo "$HOME/.bun/bin" >> "$P"
|
||||
command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
echo "$HOME/.cargo/bin" >> "$P"
|
||||
for c in ${{ inputs.rust-components }}; do "$HOME/.cargo/bin/rustup" component add "$c"; done
|
||||
|
|
@ -1,110 +0,0 @@
|
|||
# The release acceptance matrix on demand (the same jobs as release.yml's acceptance + acceptance-report, which gate
|
||||
# every release): every user-facing command from the packed npm tarball on Linux and Windows x Node 20 / Node 22 / Bun,
|
||||
# then the markdown matrix (artifact storebound-acceptance). Run it from Actions > acceptance > Run workflow, or with
|
||||
# the API (POST /repos/{owner}/{repo}/actions/workflows/acceptance.yml/dispatches). macOS: tools/acceptance.ts on the Mac.
|
||||
name: acceptance
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
BUN_VERSION: '1.4.0'
|
||||
|
||||
jobs:
|
||||
acceptance:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { os: ubuntu-22.04, platform: Linux, runtime: node, node: '20', name: node20 }
|
||||
- { os: ubuntu-22.04, platform: Linux, runtime: node, node: '22', name: node22 }
|
||||
- { os: ubuntu-22.04, platform: Linux, runtime: bun, node: '22', name: bun }
|
||||
- { os: windows, platform: Windows, runtime: node, node: '20', name: node20 }
|
||||
- { os: windows, platform: Windows, runtime: node, node: '22', name: node22 }
|
||||
- { os: windows, platform: Windows, runtime: bun, node: '22', name: bun }
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
- name: Bun (Linux)
|
||||
if: ${{ matrix.platform == 'Linux' }}
|
||||
shell: bash
|
||||
run: |
|
||||
bash tools/ci-install-bun.sh
|
||||
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
- name: Acceptance matrix (Linux)
|
||||
if: ${{ matrix.platform == 'Linux' }}
|
||||
shell: bash
|
||||
run: |
|
||||
node --version && bun --version
|
||||
bun install --frozen-lockfile
|
||||
bun tools/acceptance.ts run --runtime ${{ matrix.runtime }} --platform Linux --jobs 4 --out acceptance/Linux-${{ matrix.name }}.json
|
||||
- name: Acceptance matrix (Windows)
|
||||
if: ${{ matrix.platform == 'Windows' }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
node --version; bun --version
|
||||
bun install --frozen-lockfile
|
||||
if ($LASTEXITCODE -ne 0) { throw "bun install failed" }
|
||||
bun tools/acceptance.ts run --runtime ${{ matrix.runtime }} --platform Windows --jobs 3 --out acceptance/Windows-${{ matrix.name }}.json
|
||||
if ($LASTEXITCODE -ne 0) { throw "acceptance matrix: red cells" }
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: acceptance-${{ matrix.platform }}-${{ matrix.name }}
|
||||
path: acceptance/
|
||||
retention-days: 30
|
||||
|
||||
acceptance-report:
|
||||
needs: [acceptance]
|
||||
if: ${{ always() }}
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: acceptance-Linux-node20
|
||||
path: acceptance-runs/Linux-node20
|
||||
- uses: actions/download-artifact@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: acceptance-Linux-node22
|
||||
path: acceptance-runs/Linux-node22
|
||||
- uses: actions/download-artifact@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: acceptance-Linux-bun
|
||||
path: acceptance-runs/Linux-bun
|
||||
- uses: actions/download-artifact@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: acceptance-Windows-node20
|
||||
path: acceptance-runs/Windows-node20
|
||||
- uses: actions/download-artifact@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: acceptance-Windows-node22
|
||||
path: acceptance-runs/Windows-node22
|
||||
- uses: actions/download-artifact@v3
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: acceptance-Windows-bun
|
||||
path: acceptance-runs/Windows-bun
|
||||
- name: Matrix (markdown), red cells fail the job
|
||||
run: |
|
||||
bash tools/ci-install-bun.sh
|
||||
export PATH="$HOME/.bun/bin:$PATH"
|
||||
V=$(bun tools/desktop-version.ts --print)
|
||||
mkdir -p out
|
||||
bun tools/acceptance.ts report acceptance-runs docs/acceptance --md "out/storebound_${V}_acceptance.md" --expect 9 --strict
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: storebound-acceptance
|
||||
path: out/
|
||||
retention-days: 30
|
||||
|
|
@ -1,24 +1,11 @@
|
|||
# Every push to main is a release candidate (docs/desktop-release.md, "Release candidates"). In parallel:
|
||||
# ci bun run ci (adapters, desktop version, tests, typecheck, desktop i18n / typecheck / build, the boot check
|
||||
# in headless Chromium, desktop Rust tests and clippy, scrub); tools/ci.ts runs it as a task graph with
|
||||
# parallel test shards on the one Linux runner; no browser test runs here (tests/browser/, `bun run
|
||||
# test:browser` by hand). The Rust steps run when the push changed a Rust input (STOREBOUND_CI_BASE).
|
||||
# acceptance the release acceptance matrix (tools/acceptance.ts): every user-facing command from the packed npm
|
||||
# tarball with real piped stdin, Linux and Windows x Node 20 / Node 22 / Bun.
|
||||
# linux AppImage + deb (path-free build), self-tests, both started under Xvfb, privacy scan.
|
||||
# windows NSIS installer, silent per-user install, self-test, uninstall, the Node prompt smoke, privacy scan.
|
||||
# record when all are green (the installers already scanned with the private terms): the draft release rc-<sha> with the installers, the acceptance runs and matrix and
|
||||
# green.json (tools/release-candidate.ts record). A v* tag on this commit only promotes it (release.yml).
|
||||
# gate decides first: a commit that differs from its green parent only in version copies + CHANGELOG (a release's
|
||||
# version bump, proven file by file: tools/release-candidate.ts gate) reuses the parent's ci and acceptance results
|
||||
# and builds only the installers, whose embedded version changed.
|
||||
# Pull requests run ci + acceptance (no installers, no record). rehearsal/* branches are release rehearsals
|
||||
# (tools/release.ts --rehearsal). site/ is still published by Jenkins.
|
||||
# bun run ci on every push to main and every pull request into main: adapters, desktop version, tests, typecheck,
|
||||
# desktop i18n / typecheck / build, desktop boot check (headless Chromium), desktop Rust tests and clippy, scrub. Runs on the VDS runner (docs/desktop-release.md).
|
||||
# Publishes nothing: site/ is still published by Jenkins.
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, 'rehearsal/**']
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
|
@ -29,400 +16,43 @@ env:
|
|||
CARGO_INCREMENTAL: '0'
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
runs-on: ubuntu-22.04
|
||||
# the self-hosted runners only run code from this repo: pull requests from forks are skipped
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
timeout-minutes: 45
|
||||
outputs:
|
||||
reuse: ${{ steps.gate.outputs.reuse }}
|
||||
from: ${{ steps.gate.outputs.from }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- name: Version-only commit of a green parent?
|
||||
id: gate
|
||||
env:
|
||||
FORGEJO_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
FORGEJO_URL: ${{ github.server_url }}
|
||||
FORGEJO_ORIGIN: ${{ secrets.FORGEJO_ORIGIN }}
|
||||
EVENT: ${{ github.event_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
run: |
|
||||
# tests never gate a release (the owner's decision 2026-10-16): no waiting on the parent's run, which the
|
||||
# release's own bump push cancels; every commit builds its installers and runs the tests in the background
|
||||
echo "reuse=false" >> "$GITHUB_OUTPUT"; echo "from=" >> "$GITHUB_OUTPUT"; echo "tests run in the background; installers build for this commit"
|
||||
|
||||
# background tests (the owner's decision 2026-10-16): they run on every push and report, but the record job (the
|
||||
# release candidate) never waits for them; `bun tools/release.ts` and `bun tools/ci-status.ts` print a red result
|
||||
ci:
|
||||
needs: gate
|
||||
if: github.event_name != 'pull_request' || true
|
||||
# runner label: ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04
|
||||
runs-on: ubuntu-22.04
|
||||
# the self-hosted runner only runs code from this repo: pull requests from forks are skipped
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- uses: ./.forgejo/actions/linux-setup
|
||||
with:
|
||||
cache-key: ci
|
||||
rust-components: clippy
|
||||
- uses: ./.forgejo/actions/ci-run
|
||||
|
||||
# The release acceptance matrix (tools/acceptance.ts, docs/acceptance.md): every user-facing command from the packed
|
||||
# npm tarball, in fresh temp folders with piped stdin and the fake stores, on Linux and Windows x Node 20 / Node 22
|
||||
# (npx --package=<tgz>) / Bun (bun x). One red cell and the commit is no candidate. macOS runs on the owner's Mac
|
||||
# (tools/release.ts, cached per CLI key).
|
||||
# after the installers: the one Windows runner builds the release installer first, the background tests wait
|
||||
# (0.8.13's Windows installer queued behind six acceptance jobs)
|
||||
acceptance:
|
||||
needs: [gate, linux, windows]
|
||||
if: github.event_name != 'pull_request' || true
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { os: ubuntu-22.04, platform: Linux, runtime: node, node: '20', name: node20 }
|
||||
- { os: ubuntu-22.04, platform: Linux, runtime: node, node: '22', name: node22 }
|
||||
- { os: ubuntu-22.04, platform: Linux, runtime: bun, node: '22', name: bun }
|
||||
- { os: windows, platform: Windows, runtime: node, node: '20', name: node20 }
|
||||
- { os: windows, platform: Windows, runtime: node, node: '22', name: node22 }
|
||||
- { os: windows, platform: Windows, runtime: bun, node: '22', name: bun }
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
- name: Bun (Linux)
|
||||
if: ${{ matrix.platform == 'Linux' }}
|
||||
shell: bash
|
||||
- name: System packages (Tauri on Linux)
|
||||
run: |
|
||||
bash tools/ci-install-bun.sh
|
||||
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
- name: Acceptance matrix (Linux)
|
||||
if: ${{ matrix.platform == 'Linux' }}
|
||||
shell: bash
|
||||
run: |
|
||||
node --version && bun --version
|
||||
# npm pack runs prepack, which builds the package's declarations with the pinned TypeScript
|
||||
bun install --frozen-lockfile
|
||||
bun tools/acceptance.ts run --runtime ${{ matrix.runtime }} --platform Linux --jobs 4 --out acceptance/Linux-${{ matrix.name }}.json
|
||||
- name: Acceptance matrix (Windows)
|
||||
if: ${{ matrix.platform == 'Windows' }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
node --version; bun --version
|
||||
# npm pack runs prepack, which builds the package's declarations with the pinned TypeScript
|
||||
bun install --frozen-lockfile
|
||||
if ($LASTEXITCODE -ne 0) { throw "bun install failed" }
|
||||
bun tools/acceptance.ts run --runtime ${{ matrix.runtime }} --platform Windows --jobs 3 --out acceptance/Windows-${{ matrix.name }}.json
|
||||
if ($LASTEXITCODE -ne 0) { throw "acceptance matrix: red cells" }
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: acceptance-${{ matrix.platform }}-${{ matrix.name }}
|
||||
path: acceptance/
|
||||
retention-days: 14
|
||||
|
||||
linux:
|
||||
needs: gate
|
||||
if: github.event_name != 'pull_request'
|
||||
# runner label: ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04 (glibc 2.35: the AppImage and the
|
||||
# deb then run on Ubuntu 22.04 and newer, Debian 12)
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
# the path-free build keeps the target folder outside every home folder
|
||||
CARGO_TARGET_DIR: /tmp/storebound-target
|
||||
# linuxdeploy (AppImage) runs without FUSE inside the container
|
||||
APPIMAGE_EXTRACT_AND_RUN: '1'
|
||||
# linuxdeploy must not strip: the storebound sidecar is a `bun build --compile` executable whose JS payload strip
|
||||
# removes (it then starts as plain bun). The Rust binary is already stripped by Cargo (profile.release strip).
|
||||
NO_STRIP: '1'
|
||||
# WebKitGTK's DMABUF renderer leaves the window blank on some GPU / VM setups; the app sets this itself at
|
||||
# start (src-tauri/src/lib.rs linux_webkit_env) unless the user did; set here too for anything run in CI
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER: '1'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: ./.forgejo/actions/linux-setup
|
||||
with:
|
||||
cache-key: desktop
|
||||
packages: patchelf file squashfs-tools p7zip-full xz-utils
|
||||
# the release target folder (dependencies compiled once; a version bump recompiles only the app crate)
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev \
|
||||
libayatana-appindicator3-dev librsvg2-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libssl-dev libxdo-dev \
|
||||
build-essential curl unzip pkg-config >/dev/null
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: /tmp/storebound-target
|
||||
key: desktop-target-${{ runner.os }}-${{ hashFiles('apps/desktop/src-tauri/Cargo.lock') }}
|
||||
restore-keys: desktop-target-${{ runner.os }}-
|
||||
- name: Install and check
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
apps/desktop/src-tauri/target
|
||||
key: ci-${{ runner.os }}-${{ hashFiles('bun.lock', 'apps/desktop/src-tauri/Cargo.lock') }}
|
||||
restore-keys: ci-${{ runner.os }}-
|
||||
- name: Bun and Rust
|
||||
run: |
|
||||
P="${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null
|
||||
echo "$HOME/.bun/bin" >> "$P"
|
||||
command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --component clippy
|
||||
echo "$HOME/.cargo/bin" >> "$P"
|
||||
- name: Install
|
||||
run: |
|
||||
rustup component add clippy
|
||||
bun --version && cargo --version
|
||||
bun install --frozen-lockfile
|
||||
bun tools/desktop-version.ts
|
||||
bun tools/build-sidecars.ts --target bun-linux-x64
|
||||
# linuxdeploy (AppImage) sets the rpath of every executable with its own patchelf, which corrupts the bun
|
||||
# sidecar (segfault, then ldd fails in the gtk plugin). With the rpath already set (Ubuntu's patchelf, which
|
||||
# keeps it working), linuxdeploy leaves the file as it is. The sidecar needs only libc, so the rpath is inert.
|
||||
patchelf --set-rpath '$ORIGIN/../lib' apps/desktop/src-tauri/binaries/storebound-x86_64-unknown-linux-gnu
|
||||
apps/desktop/src-tauri/binaries/storebound-x86_64-unknown-linux-gnu version
|
||||
- name: Build AppImage and deb (path-free)
|
||||
working-directory: apps/desktop
|
||||
run: |
|
||||
rm -rf "$CARGO_TARGET_DIR/release/bundle"
|
||||
# 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
|
||||
run: |
|
||||
V=$(bun tools/desktop-version.ts --print)
|
||||
B="$CARGO_TARGET_DIR/release/bundle"
|
||||
mkdir -p out && cp "$B/appimage/storebound_${V}_amd64.AppImage" "$B/deb/storebound_${V}_amd64.deb" out/
|
||||
chmod +x out/*.AppImage
|
||||
(cd /tmp && rm -rf squashfs-root && "$GITHUB_WORKSPACE/out/storebound_${V}_amd64.AppImage" --appimage-extract >/dev/null && squashfs-root/usr/bin/storebound-desktop --self-test)
|
||||
rm -rf /tmp/deb && dpkg-deb -x "out/storebound_${V}_amd64.deb" /tmp/deb && /tmp/deb/usr/bin/storebound-desktop --self-test
|
||||
dpkg-deb -I "out/storebound_${V}_amd64.deb" | sed -n '1,20p'
|
||||
- name: Start the app under Xvfb (AppImage and deb)
|
||||
# --self-test checks only the sidecar; this opens the real window (GTK, WebKitGTK, the bundled libraries of the
|
||||
# AppImage) on a virtual display. "sidecar started" in host.log means the webview ran the UI and called the host.
|
||||
run: |
|
||||
sudo apt-get install -y -qq --no-install-recommends xvfb xauth dbus-x11 >/dev/null
|
||||
V=$(bun tools/desktop-version.ts --print)
|
||||
smoke() { # <label> <executable>
|
||||
local d; d=$(mktemp -d); local log="$d/data/dev.storebound.desktop/logs/host.log"
|
||||
XDG_DATA_HOME="$d/data" XDG_CONFIG_HOME="$d/config" XDG_CACHE_HOME="$d/cache" \
|
||||
xvfb-run -a dbus-run-session -- "$2" >"$d/out.txt" 2>&1 &
|
||||
local pid=$! ok=0
|
||||
for i in $(seq 1 90); do
|
||||
if grep -q 'sidecar started' "$log" 2>/dev/null; then ok=1; break; fi
|
||||
kill -0 "$pid" 2>/dev/null || break
|
||||
sleep 1
|
||||
done
|
||||
sleep 3; kill -0 "$pid" 2>/dev/null || ok=0
|
||||
pkill -TERM -f storebound-desktop || true; wait "$pid" 2>/dev/null || true
|
||||
echo "--- $1 host.log"; cat "$log" 2>/dev/null || true
|
||||
local wv="$d/data/dev.storebound.desktop/logs/webview.log"
|
||||
if [ -f "$wv" ]; then echo "--- $1 webview.log"; cat "$wv"; grep -qE '^\S+ error ' "$wv" && ok=0; fi
|
||||
grep -qE '^\S+ error |panicked' "$log" 2>/dev/null && ok=0
|
||||
if [ "$ok" != 1 ]; then echo "--- $1 output"; tail -n 60 "$d/out.txt"; echo "$1: the window did not start the UI" >&2; return 1; fi
|
||||
echo "$1: window started, UI reached the sidecar"
|
||||
}
|
||||
smoke AppImage "$GITHUB_WORKSPACE/out/storebound_${V}_amd64.AppImage"
|
||||
smoke deb /tmp/deb/usr/bin/storebound-desktop
|
||||
- name: Privacy scan (with the private terms; never printed)
|
||||
env:
|
||||
FORBIDDEN_TERMS: ${{ secrets.FORBIDDEN_TERMS }}
|
||||
run: |
|
||||
[ -n "$FORBIDDEN_TERMS" ] || { echo "secret FORBIDDEN_TERMS is missing" >&2; exit 1; }
|
||||
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 out/ || rc=$?
|
||||
rm -f "$RUNNER_TEMP/terms.txt"; exit $rc
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: storebound-desktop-linux
|
||||
path: out/
|
||||
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:
|
||||
needs: gate
|
||||
if: github.event_name != 'pull_request'
|
||||
# the Windows runner on the VDS ("windows" label, host mode): Rust (MSVC), Bun, 7-Zip, pwsh
|
||||
runs-on: windows
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TARGET_DIR: C:\storebound-target
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: Install and check
|
||||
shell: pwsh
|
||||
run: |
|
||||
bun install --frozen-lockfile
|
||||
bun tools/desktop-version.ts
|
||||
bun tools/build-sidecars.ts --target bun-windows-x64
|
||||
- name: Node bundle on Windows (npx storebound) - stdin prompts read with node, clean exit
|
||||
shell: pwsh
|
||||
run: |
|
||||
bun tools/build-node.ts
|
||||
node --version
|
||||
bun tools/node-smoke.ts --only prompt
|
||||
if ($LASTEXITCODE -ne 0) { throw "node prompt smoke failed" }
|
||||
"n" | node dist/storebound.mjs --version
|
||||
if ($LASTEXITCODE -ne 0) { throw "node dist/storebound.mjs --version failed" }
|
||||
- name: Build NSIS installer (per user, WebView2 bootstrapper, path-free)
|
||||
shell: pwsh
|
||||
working-directory: apps/desktop
|
||||
run: |
|
||||
Remove-Item -Recurse -Force "$env:CARGO_TARGET_DIR\release\bundle\nsis" -ErrorAction SilentlyContinue
|
||||
bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles nsis --ci
|
||||
- name: Install per user, self-test, uninstall
|
||||
shell: pwsh
|
||||
run: |
|
||||
$V = bun tools/desktop-version.ts --print
|
||||
New-Item -ItemType Directory -Force out | Out-Null
|
||||
Copy-Item "$env:CARGO_TARGET_DIR\release\bundle\nsis\storebound_${V}_x64-setup.exe" out\
|
||||
Start-Process -Wait -FilePath "out\storebound_${V}_x64-setup.exe" -ArgumentList '/S'
|
||||
$exe = "$env:LOCALAPPDATA\storebound\storebound-desktop.exe"
|
||||
if (-not (Test-Path $exe)) { throw "not installed per user at $exe" }
|
||||
& $exe --self-test | Tee-Object -Variable st
|
||||
if ($LASTEXITCODE -ne 0) { throw "self-test failed" }
|
||||
Start-Process -Wait -FilePath "$env:LOCALAPPDATA\storebound\uninstall.exe" -ArgumentList '/S'
|
||||
- name: Privacy scan (no .pdb, no paths; with the private terms, never printed)
|
||||
shell: pwsh
|
||||
env:
|
||||
FORBIDDEN_TERMS: ${{ secrets.FORBIDDEN_TERMS }}
|
||||
run: |
|
||||
if (-not $env:FORBIDDEN_TERMS) { throw "secret FORBIDDEN_TERMS is missing" }
|
||||
$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 out
|
||||
$rc = $LASTEXITCODE
|
||||
Remove-Item -Force $t
|
||||
if ($rc -ne 0) { throw "privacy scan failed" }
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: storebound-desktop-windows
|
||||
path: out/
|
||||
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:
|
||||
needs: [gate, linux, windows]
|
||||
if: ${{ always() && github.event_name != 'pull_request' && needs.gate.result == 'success' && needs.linux.result == 'success' && needs.windows.result == 'success' }}
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
FORGEJO_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
FORGEJO_URL: ${{ github.server_url }}
|
||||
# uploads over 100 MB go to the origin directly (Cloudflare refuses them): tools/forgejo-release.ts
|
||||
FORGEJO_ORIGIN: ${{ secrets.FORGEJO_ORIGIN }}
|
||||
SHA: ${{ github.sha }}
|
||||
REUSE: ${{ needs.gate.outputs.reuse }}
|
||||
FROM: ${{ needs.gate.outputs.from }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# no apt: the installers were scanned with the private terms in their own jobs; this job only records
|
||||
- name: Tools
|
||||
run: |
|
||||
bash tools/ci-install-bun.sh
|
||||
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
[ -n "$FORGEJO_TOKEN" ] || { echo "secret RELEASE_TOKEN is missing (repo Settings > Actions > Secrets)" >&2; exit 1; }
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: storebound-desktop-linux
|
||||
path: cand
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: storebound-desktop-windows
|
||||
path: cand
|
||||
- name: Checksums file of the build jobs is not shipped as is
|
||||
run: rm -f cand/SHA256SUMS
|
||||
- name: Record the candidate (draft rc-<sha>, green.json last)
|
||||
run: |
|
||||
bun tools/release-candidate.ts record --sha "$SHA" --run "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_NUMBER" --dir cand ${FROM:+--reused-from "$FROM"} --yes
|
||||
bun tools/release-candidate.ts prune --keep 12 --yes
|
||||
- name: Headless Chromium (desktop boot check)
|
||||
run: bunx playwright install --with-deps chromium
|
||||
- name: bun run ci
|
||||
run: bun run ci
|
||||
|
|
|
|||
135
.forgejo/workflows/desktop.yml
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
# storebound desktop: Linux (AppImage + deb) and Windows (NSIS, per user, unsigned) installers.
|
||||
# macOS is built, signed and notarized on the owner's Mac (tools/desktop-release.ts mac); the updater signing key
|
||||
# never reaches a runner: the Mac signs these installers after downloading them (tools/desktop-release.ts add).
|
||||
# Runner setup (Forgejo runners on the VDS: Linux in Docker, Windows in a KVM VM): docs/desktop-release.md.
|
||||
# Publishes nothing: the installers are workflow artifacts only (14 days); `tools/desktop-release.ts add` on the Mac
|
||||
# signs and stages them, and only `publish` puts anything on storebound.dev.
|
||||
name: desktop
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
windows:
|
||||
description: Build Windows too (needs a runner with the "windows" label)
|
||||
type: boolean
|
||||
default: false
|
||||
push:
|
||||
tags: ['desktop-v*']
|
||||
|
||||
env:
|
||||
BUN_VERSION: '1.4.0'
|
||||
# the path-free build keeps the target folder outside every home folder
|
||||
CARGO_TARGET_DIR: /tmp/storebound-target
|
||||
CARGO_TERM_COLOR: never
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
# runner label: ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04 (glibc 2.35: the AppImage and the
|
||||
# deb then run on Ubuntu 22.04 and newer, Debian 12)
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
# linuxdeploy (AppImage) runs without FUSE inside the container
|
||||
APPIMAGE_EXTRACT_AND_RUN: '1'
|
||||
# linuxdeploy must not strip: the storebound sidecar is a `bun build --compile` executable whose JS payload strip
|
||||
# removes (it then starts as plain bun). The Rust binary is already stripped by Cargo (profile.release strip).
|
||||
NO_STRIP: '1'
|
||||
# WebKitGTK's DMABUF renderer leaves the window blank on some GPU / VM setups; the app sets this itself at
|
||||
# start (src-tauri/src/lib.rs linux_webkit_env) unless the user did; set here too for anything run in CI
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER: '1'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: System packages
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
|
||||
librsvg2-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libssl-dev libxdo-dev patchelf file build-essential \
|
||||
curl unzip squashfs-tools p7zip-full xz-utils >/dev/null
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
key: desktop-${{ runner.os }}-${{ hashFiles('bun.lock', 'apps/desktop/src-tauri/Cargo.lock') }}
|
||||
restore-keys: desktop-${{ runner.os }}-
|
||||
- name: Bun and Rust
|
||||
run: |
|
||||
P="${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null
|
||||
echo "$HOME/.bun/bin" >> "$P"
|
||||
command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
echo "$HOME/.cargo/bin" >> "$P"
|
||||
- name: Install and check
|
||||
run: |
|
||||
bun install --frozen-lockfile
|
||||
bun tools/desktop-version.ts
|
||||
bun tools/build-sidecars.ts --target bun-linux-x64
|
||||
# linuxdeploy (AppImage) sets the rpath of every executable with its own patchelf, which corrupts the bun
|
||||
# sidecar (segfault, then ldd fails in the gtk plugin). With the rpath already set (Ubuntu's patchelf, which
|
||||
# keeps it working), linuxdeploy leaves the file as it is. The sidecar needs only libc, so the rpath is inert.
|
||||
patchelf --set-rpath '$ORIGIN/../lib' apps/desktop/src-tauri/binaries/storebound-x86_64-unknown-linux-gnu
|
||||
apps/desktop/src-tauri/binaries/storebound-x86_64-unknown-linux-gnu version
|
||||
- name: Build AppImage and deb (path-free)
|
||||
working-directory: apps/desktop
|
||||
run: bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles appimage,deb --ci
|
||||
- name: Self-test the exact artifacts
|
||||
run: |
|
||||
V=$(bun tools/desktop-version.ts --print)
|
||||
B="$CARGO_TARGET_DIR/release/bundle"
|
||||
mkdir -p out && cp "$B/appimage/storebound_${V}_amd64.AppImage" "$B/deb/storebound_${V}_amd64.deb" out/
|
||||
chmod +x out/*.AppImage
|
||||
(cd /tmp && rm -rf squashfs-root && "$GITHUB_WORKSPACE/out/storebound_${V}_amd64.AppImage" --appimage-extract >/dev/null && squashfs-root/usr/bin/storebound-desktop --self-test)
|
||||
rm -rf /tmp/deb && dpkg-deb -x "out/storebound_${V}_amd64.deb" /tmp/deb && /tmp/deb/usr/bin/storebound-desktop --self-test
|
||||
dpkg-deb -I "out/storebound_${V}_amd64.deb" | sed -n '1,20p'
|
||||
- name: Privacy scan
|
||||
run: bun tools/privacy-scan.ts out/
|
||||
- name: Checksums
|
||||
run: (cd out && sha256sum * | tee SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: storebound-desktop-linux
|
||||
path: out/
|
||||
retention-days: 14
|
||||
|
||||
windows:
|
||||
# only on a manual run with "windows" ticked (a tag push never sets it), so without a Windows runner it is skipped
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.windows }}
|
||||
# the Windows runner on the VDS ("windows" label, host mode): Rust (MSVC), Bun, 7-Zip, pwsh
|
||||
runs-on: windows
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TARGET_DIR: C:\storebound-target
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install and check
|
||||
shell: pwsh
|
||||
run: |
|
||||
bun install --frozen-lockfile
|
||||
bun tools/desktop-version.ts
|
||||
bun tools/build-sidecars.ts --target bun-windows-x64
|
||||
- name: Build NSIS installer (per user, WebView2 bootstrapper, path-free)
|
||||
shell: pwsh
|
||||
working-directory: apps/desktop
|
||||
run: bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles nsis --ci
|
||||
- name: Install per user, self-test, uninstall
|
||||
shell: pwsh
|
||||
run: |
|
||||
$V = bun tools/desktop-version.ts --print
|
||||
New-Item -ItemType Directory -Force out | Out-Null
|
||||
Copy-Item "$env:CARGO_TARGET_DIR\release\bundle\nsis\storebound_${V}_x64-setup.exe" out\
|
||||
Start-Process -Wait -FilePath "out\storebound_${V}_x64-setup.exe" -ArgumentList '/S'
|
||||
$exe = "$env:LOCALAPPDATA\storebound\storebound-desktop.exe"
|
||||
if (-not (Test-Path $exe)) { throw "not installed per user at $exe" }
|
||||
& $exe --self-test | Tee-Object -Variable st
|
||||
if ($LASTEXITCODE -ne 0) { throw "self-test failed" }
|
||||
Start-Process -Wait -FilePath "$env:LOCALAPPDATA\storebound\uninstall.exe" -ArgumentList '/S'
|
||||
- name: Privacy scan (no .pdb, no paths)
|
||||
shell: pwsh
|
||||
run: bun tools/privacy-scan.ts out
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: storebound-desktop-windows
|
||||
path: out/
|
||||
retention-days: 14
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
# The release of storebound: a version tag (v0.8.5) promotes the release candidate of its commit. Nothing is rebuilt
|
||||
# or retested here: ci.yml ran the full CI, the acceptance matrix (Linux + Windows x Node 20 / 22 / Bun) and built,
|
||||
# self-tested and privacy-scanned the Linux and Windows installers for that very commit (for a version-only bump
|
||||
# commit: the installers, with the parent's CI and matrix, proven version-only file by file), and stored them as the
|
||||
# draft rc-<sha> with green.json (tools/release-candidate.ts).
|
||||
#
|
||||
# push of a tag v* checks (tag = package.json version, every version copy equal, the CHANGELOG section), waits
|
||||
# for the commit's candidate (heartbeat; fails at once when the commit is red or has no ci run,
|
||||
# with the run's link; times out after 40 min), then ONE release "storebound <version>" with the
|
||||
# candidate's installers, the acceptance matrix, SHA256SUMS and short notes. Stable versions
|
||||
# then delete the older release entries (tags stay). A version with a "-" (0.0.0-rehearsal.1)
|
||||
# is a prerelease: never pruning, never the stable release.
|
||||
# workflow_dispatch tag: the same for an existing tag; dry (default): only the plan.
|
||||
#
|
||||
# Not here: macOS. tools/release.ts on the owner's Mac builds, signs and notarizes the DMG in parallel and adds it to
|
||||
# this release, then publishes storebound.dev (docs/desktop-release.md). The updater signing key never reaches a runner.
|
||||
# Secrets: RELEASE_TOKEN (scope write:repository), FORGEJO_ORIGIN (the server's IP: uploads over 100 MB bypass
|
||||
# Cloudflare). The private terms scan of the installers ran in ci.yml's build jobs (FORBIDDEN_TERMS).
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Version tag to release (v0.8.5)
|
||||
type: string
|
||||
default: ''
|
||||
dry:
|
||||
description: Dry run (only the plan)
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
env:
|
||||
BUN_VERSION: '1.4.0'
|
||||
|
||||
jobs:
|
||||
promote:
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 50
|
||||
env:
|
||||
FORGEJO_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
FORGEJO_URL: ${{ github.server_url }}
|
||||
FORGEJO_ORIGIN: ${{ secrets.FORGEJO_ORIGIN }}
|
||||
TAG: ${{ github.event_name == 'push' && github.ref_name || inputs.tag }}
|
||||
steps:
|
||||
- name: Mode
|
||||
id: mode
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
IN_DRY: ${{ inputs.dry }}
|
||||
run: |
|
||||
[ -n "$TAG" ] || { echo "input tag is required" >&2; exit 1; }
|
||||
case "$(echo "${IN_DRY:-true}" | tr A-Z a-z)" in false|0|off|no) dry=false;; *) dry=true;; esac
|
||||
[ "$EVENT" = push ] && dry=false
|
||||
echo "dry=$dry" >> "$GITHUB_OUTPUT"; echo "tag=$TAG dry=$dry"
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: refs/tags/${{ env.TAG }}
|
||||
- name: Tag, package.json version, every version copy and the CHANGELOG agree
|
||||
id: check
|
||||
run: |
|
||||
bash tools/ci-install-bun.sh
|
||||
echo "$HOME/.bun/bin" >> "${FORGEJO_PATH:-$GITHUB_PATH}"
|
||||
export PATH="$HOME/.bun/bin:$PATH"
|
||||
bun tools/desktop-version.ts
|
||||
V=$(bun tools/desktop-version.ts --print)
|
||||
[ "$TAG" = "v$V" ] || { echo "tag $TAG is not v$V (package.json): bun tools/release.ts <version> makes the bump commit and the tag" >&2; exit 1; }
|
||||
case "$V" in *-*) echo "prerelease $V: the CHANGELOG section is optional";; *) grep -q "^## $V" CHANGELOG.md || { echo "CHANGELOG.md has no '## $V' section" >&2; exit 1; };; esac
|
||||
[ -n "$FORGEJO_TOKEN" ] || { echo "secret RELEASE_TOKEN is missing (repo Settings > Actions > Secrets)" >&2; exit 1; }
|
||||
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
- name: Promote the commit's green candidate
|
||||
run: bun tools/release-candidate.ts promote --tag "$TAG" --sha "${{ steps.check.outputs.sha }}" --wait 40 ${{ steps.mode.outputs.dry == 'false' && '--yes' || '' }}
|
||||
- name: Keep only the newest release (stable versions; tags stay)
|
||||
if: ${{ steps.mode.outputs.dry == 'false' && !contains(steps.check.outputs.version, '-') }}
|
||||
run: bun tools/forgejo-release.ts prune --keep "$TAG" --yes
|
||||
13
.gitattributes
vendored
|
|
@ -1,13 +0,0 @@
|
|||
* text=auto eol=lf
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
*.ttf binary
|
||||
*.woff2 binary
|
||||
*.mp4 binary
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
# kept byte-for-byte as published upstream (CRLF)
|
||||
cli/data/play-data-safety-form.csv -text
|
||||
**/icons/LICENSE.txt -text
|
||||
75
.github/copilot-instructions.md
vendored
|
|
@ -7,53 +7,13 @@ format; `storebound install --agent copilot` copies them to `.github/skills/` of
|
|||
|
||||
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
|
||||
|
||||
## First rule: do it, don't ask
|
||||
|
||||
storebound plus you, the AI agent, do the work. The owner is not your pair of hands.
|
||||
|
||||
1. **You do everything yourself:** API calls, uploads, builds, template and CSV downloads and exports, every console
|
||||
navigation (open, Get Started, Edit, Next, Continue, Save draft), console forms, and the verification afterwards.
|
||||
Never tell the owner "run this yourself" or "click X yourself" for any of these.
|
||||
2. **The owner keeps only the final public or irreversible buttons:** Submit for review (App Review or Beta App
|
||||
Review), releasing a version or completing / resuming a production rollout, App Privacy Publish, accepting legal
|
||||
agreements; plus deleting store data, changing live prices, sending review replies and inviting or removing
|
||||
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
|
||||
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:
|
||||
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
|
||||
`.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so.
|
||||
3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety,
|
||||
App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start
|
||||
(`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that
|
||||
are already in the config.
|
||||
4. **Default loop:** plan, then you drive (the API first, your browser tool for consoles without an API), then verify
|
||||
(read it back), then continue. No round trip to the owner in between.
|
||||
5. **Catch rejections offline.** Before a write, `storebound check` and `--dry` must catch what the store would refuse
|
||||
(live-shape fixtures, id and pair checks). A failure belongs in the dry run, not in a 400 at write time; when a
|
||||
store refuses something the dry run passed, fix the check (pitfalls), not just the data.
|
||||
|
||||
Every hour of "please click this" is an hour the owner did not want to spend. If you catch yourself writing "you
|
||||
need to ...", do it instead, unless it is one of the owner steps in point 2.
|
||||
|
||||
## The other rules
|
||||
|
||||
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
|
||||
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
|
||||
|
||||
1. **The owner presses only the owner steps** (point 2 of the first rule). Prepare them completely, say what will
|
||||
happen, and let the owner press the button, or run the command only after a clear yes in chat. storebound's MCP
|
||||
server does not offer these at all. Everything else you run yourself.
|
||||
2. **Dry run first, then run it yourself.** Every write command has `--dry` (MCP: `dry_run`, default true). Run the
|
||||
dry run, check and show it (the rows that change, not just a count), then run the real command yourself (`--yes`
|
||||
where it asks for a confirmation) and read the result back. Wait for the owner's yes only before an owner step.
|
||||
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review),
|
||||
releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings,
|
||||
accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping
|
||||
a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in
|
||||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
|
|
@ -61,8 +21,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
target audience: ask the owner when the code does not prove the answer, all such questions in one batch at the
|
||||
start (first rule, point 3), and write the answers into the config. A wrong "no" is worse than a slow "ask".
|
||||
target audience: ask the owner when the code does not prove the answer. A wrong "no" is worse than a slow "ask".
|
||||
6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest".
|
||||
7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and
|
||||
you report the progress lines, not guesses.
|
||||
|
|
@ -71,20 +30,10 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in
|
||||
`.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits,
|
||||
and never ask for tester emails in chat (storebound masks them in its output).
|
||||
10. **Console forms without an API: drive them yourself, agent-first.** `storebound console plan <form> --json` (MCP
|
||||
`console_plan`) gives the start URL, steps, the answer sheet, the buttons you must never press and the verified UI
|
||||
facts. Drive the page with your own browser tool, adapt to what it shows, run long flows as an in-page async loop
|
||||
that writes `window.__log` (one evaluate call times out around 45 s), stop only before the final button (Publish,
|
||||
Submit, Create, a final Save) and tell the owner exactly what to press, then `storebound console verify <form>`.
|
||||
Never sign in, accept an agreement or grant a permission (a service account's app access) for the owner.
|
||||
`storebound console fill` is the optional scripted fast path; it never blocks you.
|
||||
11. **Console pages: always the absolute deep link.** When you send the owner to a console page, give the absolute
|
||||
deep link (storebound prints it; `storebound console plan` has start URLs), never just "go to App Store Connect"
|
||||
or "App Store Connect > App Information" alone.
|
||||
|
||||
## Tools
|
||||
|
||||
- CLI: `storebound <command>` (`storebound help`; outside the plugin: `npx storebound` on Node 20+ or `bunx storebound` on Bun); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
|
@ -104,17 +53,14 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
| `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game |
|
||||
| `aso-basics` | App store optimization basics for a mobile app's or game's text |
|
||||
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
|
||||
| `console-autofill` | Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default |
|
||||
| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes |
|
||||
| `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly |
|
||||
| `game-services` | Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section |
|
||||
| `listing-localization` | Translate the store listing of a mobile app or game into more languages |
|
||||
| `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` |
|
||||
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |
|
||||
| `portfolio-originality` | Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) |
|
||||
| `ppp-pricing` | Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp` |
|
||||
| `privacy-manifest` | Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game |
|
||||
| `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games |
|
||||
| `release-flows` | Repo-local workflows for a mobile app or game |
|
||||
| `release-management` | Ship updates safely after the first release |
|
||||
| `revenuecat-sync` | Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config |
|
||||
| `review-access` | Give App Store and Google Play reviewers working access to an app behind a sign-in |
|
||||
|
|
@ -125,7 +71,6 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
| `store-declarations` | Answer the store compliance forms for a mobile app or game |
|
||||
| `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores |
|
||||
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
||||
| `store-pitfalls` | Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each |
|
||||
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile app or game |
|
||||
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages |
|
||||
| `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config |
|
||||
|
|
|
|||
6
.gitignore
vendored
|
|
@ -15,9 +15,3 @@ apps/desktop/src-tauri/binaries/
|
|||
apps/desktop/src-tauri/gen/
|
||||
apps/desktop/.screens/
|
||||
.scratch/
|
||||
|
||||
# scan fixtures: a monorepo whose Capacitor plugins live in apps/native/node_modules
|
||||
!tests/fixtures/scan/monorepo/apps/native/node_modules/
|
||||
|
||||
# npm bundle (bun tools/build-node.ts; npm pack / publish build it)
|
||||
/dist/
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
{
|
||||
"mcpServers": {
|
||||
"storebound": {
|
||||
"command": "sh",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/bin/storebound",
|
||||
"args": [
|
||||
"-c",
|
||||
"r=\"${CLAUDE_PLUGIN_ROOT:-}\"; if [ -n \"$r\" ] && [ -x \"$r/bin/storebound\" ]; then exec \"$r/bin/storebound\" mcp; fi; if command -v storebound >/dev/null 2>&1; then exec storebound mcp; fi; exec npx -y storebound@latest mcp"
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
79
AGENTS.md
|
|
@ -8,53 +8,13 @@ file below and follow it step by step.
|
|||
|
||||
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
|
||||
|
||||
## First rule: do it, don't ask
|
||||
|
||||
storebound plus you, the AI agent, do the work. The owner is not your pair of hands.
|
||||
|
||||
1. **You do everything yourself:** API calls, uploads, builds, template and CSV downloads and exports, every console
|
||||
navigation (open, Get Started, Edit, Next, Continue, Save draft), console forms, and the verification afterwards.
|
||||
Never tell the owner "run this yourself" or "click X yourself" for any of these.
|
||||
2. **The owner keeps only the final public or irreversible buttons:** Submit for review (App Review or Beta App
|
||||
Review), releasing a version or completing / resuming a production rollout, App Privacy Publish, accepting legal
|
||||
agreements; plus deleting store data, changing live prices, sending review replies and inviting or removing
|
||||
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
|
||||
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:
|
||||
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
|
||||
`.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so.
|
||||
3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety,
|
||||
App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start
|
||||
(`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that
|
||||
are already in the config.
|
||||
4. **Default loop:** plan, then you drive (the API first, your browser tool for consoles without an API), then verify
|
||||
(read it back), then continue. No round trip to the owner in between.
|
||||
5. **Catch rejections offline.** Before a write, `storebound check` and `--dry` must catch what the store would refuse
|
||||
(live-shape fixtures, id and pair checks). A failure belongs in the dry run, not in a 400 at write time; when a
|
||||
store refuses something the dry run passed, fix the check (pitfalls), not just the data.
|
||||
|
||||
Every hour of "please click this" is an hour the owner did not want to spend. If you catch yourself writing "you
|
||||
need to ...", do it instead, unless it is one of the owner steps in point 2.
|
||||
|
||||
## The other rules
|
||||
|
||||
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
|
||||
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
|
||||
|
||||
1. **The owner presses only the owner steps** (point 2 of the first rule). Prepare them completely, say what will
|
||||
happen, and let the owner press the button, or run the command only after a clear yes in chat. storebound's MCP
|
||||
server does not offer these at all. Everything else you run yourself.
|
||||
2. **Dry run first, then run it yourself.** Every write command has `--dry` (MCP: `dry_run`, default true). Run the
|
||||
dry run, check and show it (the rows that change, not just a count), then run the real command yourself (`--yes`
|
||||
where it asks for a confirmation) and read the result back. Wait for the owner's yes only before an owner step.
|
||||
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review),
|
||||
releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings,
|
||||
accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping
|
||||
a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in
|
||||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
|
|
@ -62,8 +22,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
target audience: ask the owner when the code does not prove the answer, all such questions in one batch at the
|
||||
start (first rule, point 3), and write the answers into the config. A wrong "no" is worse than a slow "ask".
|
||||
target audience: ask the owner when the code does not prove the answer. A wrong "no" is worse than a slow "ask".
|
||||
6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest".
|
||||
7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and
|
||||
you report the progress lines, not guesses.
|
||||
|
|
@ -72,20 +31,10 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in
|
||||
`.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits,
|
||||
and never ask for tester emails in chat (storebound masks them in its output).
|
||||
10. **Console forms without an API: drive them yourself, agent-first.** `storebound console plan <form> --json` (MCP
|
||||
`console_plan`) gives the start URL, steps, the answer sheet, the buttons you must never press and the verified UI
|
||||
facts. Drive the page with your own browser tool, adapt to what it shows, run long flows as an in-page async loop
|
||||
that writes `window.__log` (one evaluate call times out around 45 s), stop only before the final button (Publish,
|
||||
Submit, Create, a final Save) and tell the owner exactly what to press, then `storebound console verify <form>`.
|
||||
Never sign in, accept an agreement or grant a permission (a service account's app access) for the owner.
|
||||
`storebound console fill` is the optional scripted fast path; it never blocks you.
|
||||
11. **Console pages: always the absolute deep link.** When you send the owner to a console page, give the absolute
|
||||
deep link (storebound prints it; `storebound console plan` has start URLs), never just "go to App Store Connect"
|
||||
or "App Store Connect > App Information" alone.
|
||||
|
||||
## Tools
|
||||
|
||||
- CLI: `storebound <command>` (`storebound help`; outside the plugin: `npx storebound` on Node 20+ or `bunx storebound` on Bun); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
|
@ -103,17 +52,14 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
- `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game
|
||||
- `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text
|
||||
- `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
|
||||
- `skills/console-autofill/SKILL.md`: Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default
|
||||
- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes
|
||||
- `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly
|
||||
- `skills/game-services/SKILL.md`: Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section
|
||||
- `skills/listing-localization/SKILL.md`: Translate the store listing of a mobile app or game into more languages
|
||||
- `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane`
|
||||
- `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game
|
||||
- `skills/portfolio-originality/SKILL.md`: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins)
|
||||
- `skills/ppp-pricing/SKILL.md`: Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp`
|
||||
- `skills/privacy-manifest/SKILL.md`: Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game
|
||||
- `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games
|
||||
- `skills/release-flows/SKILL.md`: Repo-local workflows for a mobile app or game
|
||||
- `skills/release-management/SKILL.md`: Ship updates safely after the first release
|
||||
- `skills/revenuecat-sync/SKILL.md`: Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config
|
||||
- `skills/review-access/SKILL.md`: Give App Store and Google Play reviewers working access to an app behind a sign-in
|
||||
|
|
@ -124,7 +70,6 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game
|
||||
- `skills/store-health/SKILL.md`: Watch a released mobile app's or game's crash and ANR health on both stores
|
||||
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
||||
- `skills/store-pitfalls/SKILL.md`: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each
|
||||
- `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile app or game
|
||||
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages
|
||||
- `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config
|
||||
|
|
@ -135,9 +80,5 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
## Working on storebound itself
|
||||
|
||||
- Bun + TypeScript strict, zero runtime dependencies. `bun run ci` must pass (adapters fresh, tests, typecheck, scrub).
|
||||
- Inner loop: `bun run ci:quick` (typecheck, the tests related to your change against origin/main, scrub; seconds).
|
||||
Before every push: the full `bun run ci` (every check and test, in parallel shards), and check its exit code.
|
||||
- Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`.
|
||||
- Every check, rule, template line, message and desktop view covers both stores (App Store and Google Play) and every
|
||||
surface (CLI, MCP, desktop, skills); when a store has no equivalent field, say where the same thing goes there.
|
||||
- Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com.
|
||||
|
|
|
|||
1545
CHANGELOG.md
|
|
@ -7,38 +7,9 @@ but fixes, store rule updates and new engines / AI tools are very welcome.
|
|||
|
||||
```sh
|
||||
bun install # Bun 1.1+; playwright is a dev dependency (renders, web capture)
|
||||
bun run ci:quick # inner loop: typecheck + the tests your change touches + scrub (seconds)
|
||||
bun run ci # full gate before pushing: every check and test (adapters, API tables, typecheck,
|
||||
# desktop build, Rust host when it changed, scrub); no browser
|
||||
bun run test:browser # only by hand: the suites that start Chrome / Chromium (tests/browser/*.browser.ts)
|
||||
bun run ci # adapters fresh, tests, typecheck, secrets / personal data scrub
|
||||
```
|
||||
|
||||
**Windows.** `.gitattributes` keeps every text file LF in the working tree (with `core.autocrlf=true` the skills
|
||||
came out CRLF and `bun tools/gen-adapters.ts` failed with "no frontmatter"). On a checkout made before that file
|
||||
existed, run `git rm -r --cached -q . && git reset --hard` once on a clean tree. The desktop app builds with
|
||||
`cd apps/desktop && bun run sidecar && bunx tauri build` (Rust via rustup; WiX and NSIS are downloaded by Tauri) into
|
||||
`src-tauri/target/release/bundle/nsis/*-setup.exe` and `bundle/msi/*.msi`.
|
||||
|
||||
**Browser tests run only by hand.** The suites that launch a browser (console fill / flow / session / persist, web
|
||||
capture, glyphs and ligatures, local fonts, feature-graphic fit, site overflow) live in `tests/browser/` as
|
||||
`*.browser.ts`, which `bun test`, `ci`, `ci:quick` and the Forgejo workflows never pick up. Run `bun run test:browser`
|
||||
when you change that code. The one browser step left in any automatic path is the desktop boot check inside
|
||||
`tools/desktop-release.ts mac` at release time: the built window must be seen rendering before a build ships.
|
||||
|
||||
**Which one when.** Run `bun run ci:quick` while you work: it diffs against `origin/main` (committed, staged,
|
||||
unstaged and new files), maps the changed files to the tests that import them (directly, through other modules, or
|
||||
by naming a fixture or page) and runs those, plus `tsc` (incremental) and the scrub. A change to `package.json`,
|
||||
`bun.lock`, `bunfig.toml`, `tsconfig.json` or the test preload runs every test. Run the full `bun run ci` before every
|
||||
push and check its exit code: it is the gate, `ci:quick` is not.
|
||||
|
||||
`tools/ci.ts` runs the steps as a task graph (independent steps at the same time, output prefixed with the step
|
||||
name, the first failure stops the rest, a time-per-step summary at the end). The tests run as parallel shards
|
||||
(CPU cores - 1, at most 8; `STOREBOUND_CI_SHARDS=n` overrides) balanced by the durations of the last run, kept in
|
||||
`node_modules/.cache/storebound-ci/`. So tests must be shard-safe: temp folders
|
||||
from `mkdtempSync`, servers on port 0, no fixed sleeps (wait for the event), no state shared through files in the
|
||||
checkout. The desktop Rust host (`cargo test`, `clippy`) runs only when `apps/desktop/src-tauri/` or
|
||||
`tools/build-sidecars.ts` changed against `origin/main` (Forgejo CI: against the pushed commit's parent).
|
||||
|
||||
Try the screenshot and video pipeline on the demo game without any store account: see
|
||||
[examples/demo-game/README.md](examples/demo-game/README.md).
|
||||
|
||||
|
|
@ -46,12 +17,6 @@ Try the screenshot and video pipeline on the demo game without any store account
|
|||
|
||||
- **Bun + TypeScript strict, zero runtime dependencies.** `fetch` against the official store APIs, `node:` built-ins,
|
||||
external tools (`ffmpeg`, `xcrun`, `adb`) only through argv builders. Playwright is resolved from the user's project.
|
||||
- **Runs on Node 20+ and Bun.** Development, tests and CI use Bun; users run the npm bundle with Node (`npx`) or Bun
|
||||
(`bunx`). The CLI never touches the `Bun` global, `bun:` modules, `import.meta.dir` or text imports: everything goes
|
||||
through `cli/lib/rt.ts` (spawn, which, sleep, serve, glob, hashing, stdin, the package folder, config imports), and
|
||||
text files the CLI ships are embedded by `bun tools/gen-embedded.ts` (templates/, `cli/shots/*.html`, Play's form
|
||||
export: run it after changing one). `tests/node-compat.test.ts` fails on a direct Bun use; `bun run ci` builds the
|
||||
bundle (`tools/build-node.ts`) and runs it with the real `node` (`tools/node-smoke.ts`).
|
||||
- **Pure where possible.** Rules, argv builders, plans and parsers are pure functions with tests in `tests/`; the IO
|
||||
stays in the command's `run`. Tests never need a store account, a simulator or a network.
|
||||
- **Every write command takes `--dry`** and is idempotent. New MCP write tools default to `dry_run: true`. Nothing
|
||||
|
|
@ -62,10 +27,6 @@ Try the screenshot and video pipeline on the demo game without any store account
|
|||
- **Skills are the single source.** Edit `skills/*/SKILL.md` or `docs/agents-core.md`, then run
|
||||
`bun tools/gen-adapters.ts`; never edit `AGENTS.md`, `GEMINI.md`, the plugin manifests or the Cursor / Copilot files
|
||||
by hand. Frontmatter is `name` + `description` only.
|
||||
- **New or renamed flags: run `bun tools/gen-flags.ts`.** The CLI rejects a flag a command does not read
|
||||
(`cli/data/flags.json`, generated from the commands and their imports in `cli/commands.ts`); a flag read with a
|
||||
computed name goes into `DYNAMIC` in that tool. `tests/cli-help.test.ts` fails on a stale table, on a command whose
|
||||
`--help` does anything but print its usage, and on an MCP / desktop tool that passes a flag its command does not take.
|
||||
- **No secrets, no real ids, no personal data** in code, tests, fixtures or examples: use `com.example.*`,
|
||||
`example.com` and obviously fake values. `bun run ci` runs the scrub.
|
||||
- **No hand-written SVG.** Charts come from visx, icons from Phosphor (`@phosphor-icons/react` in the desktop app, one
|
||||
|
|
@ -78,23 +39,8 @@ Try the screenshot and video pipeline on the demo game without any store account
|
|||
fails on new inline `<svg>` / `<path>` drawing in `apps/desktop/src` and `site/*.html` and on SVG files that are
|
||||
not vendored or rendered. These libraries are desktop
|
||||
dependencies (bundled by Vite) or devDependencies; the CLI package keeps zero runtime dependencies.
|
||||
- **Every bug found in real use becomes a guardrail.** Add an entry to `docs/pitfalls.md` and to
|
||||
`skills/store-pitfalls/SKILL.md` (symptom, cause, what to do, what guards it) and, where possible, a check or a test
|
||||
with recorded store answers that fails without the fix. A `--dry` run prints the plan (`dryPlan` in
|
||||
`cli/lib/dry.ts`), not only a count; `tests/pitfalls.test.ts` enforces it.
|
||||
- Plain English in docs and messages, short sentences, no marketing words.
|
||||
|
||||
## Releasing the npm package
|
||||
|
||||
`npm pack` and `npm publish` run `prepack`, which builds `dist/storebound.mjs` (the `bin`, `#!/usr/bin/env node`,
|
||||
gitignored) with `bun tools/build-node.ts`. Before publishing: `bun run ci` green (it smoke-tests the bundle with
|
||||
Node), `npm pack --dry-run` lists `dist/storebound.mjs`, the privacy scan on the tree and on the bundle, and a run of
|
||||
the packed tarball in an empty folder (`npx --yes ./storebound-<version>.tgz --version`, then `init`).
|
||||
|
||||
The npm package and the desktop app are one release with one version (`bun tools/desktop-version.ts --set <version>`
|
||||
writes it everywhere): publish the desktop artifacts of that version first (docs/desktop-release.md), then
|
||||
`npm publish`, so `npx storebound desktop` of the new CLI finds its own app.
|
||||
|
||||
## Pull requests
|
||||
|
||||
One topic per PR, `bun run ci` green, a line in `CHANGELOG.md` under an "Unreleased" heading, and for anything
|
||||
|
|
|
|||
75
GEMINI.md
|
|
@ -6,53 +6,13 @@ This extension ships Agent Skills (skills/) and the storebound MCP server for mo
|
|||
|
||||
These rules apply to every AI tool that uses storebound (skills, MCP server or the CLI in a terminal).
|
||||
|
||||
## First rule: do it, don't ask
|
||||
|
||||
storebound plus you, the AI agent, do the work. The owner is not your pair of hands.
|
||||
|
||||
1. **You do everything yourself:** API calls, uploads, builds, template and CSV downloads and exports, every console
|
||||
navigation (open, Get Started, Edit, Next, Continue, Save draft), console forms, and the verification afterwards.
|
||||
Never tell the owner "run this yourself" or "click X yourself" for any of these.
|
||||
2. **The owner keeps only the final public or irreversible buttons:** Submit for review (App Review or Beta App
|
||||
Review), releasing a version or completing / resuming a production rollout, App Privacy Publish, accepting legal
|
||||
agreements; plus deleting store data, changing live prices, sending review replies and inviting or removing
|
||||
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
|
||||
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:
|
||||
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
|
||||
`.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so.
|
||||
3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety,
|
||||
App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start
|
||||
(`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that
|
||||
are already in the config.
|
||||
4. **Default loop:** plan, then you drive (the API first, your browser tool for consoles without an API), then verify
|
||||
(read it back), then continue. No round trip to the owner in between.
|
||||
5. **Catch rejections offline.** Before a write, `storebound check` and `--dry` must catch what the store would refuse
|
||||
(live-shape fixtures, id and pair checks). A failure belongs in the dry run, not in a 400 at write time; when a
|
||||
store refuses something the dry run passed, fix the check (pitfalls), not just the data.
|
||||
|
||||
Every hour of "please click this" is an hour the owner did not want to spend. If you catch yourself writing "you
|
||||
need to ...", do it instead, unless it is one of the owner steps in point 2.
|
||||
|
||||
## The other rules
|
||||
|
||||
**Read `skills/store-pitfalls/SKILL.md` before any store task.** It lists the mistakes already made in real releases
|
||||
(store lists that lag after a create, dry runs without a plan, taken App Store names, byte limits, ...) and what to do.
|
||||
|
||||
1. **The owner presses only the owner steps** (point 2 of the first rule). Prepare them completely, say what will
|
||||
happen, and let the owner press the button, or run the command only after a clear yes in chat. storebound's MCP
|
||||
server does not offer these at all. Everything else you run yourself.
|
||||
2. **Dry run first, then run it yourself.** Every write command has `--dry` (MCP: `dry_run`, default true). Run the
|
||||
dry run, check and show it (the rows that change, not just a count), then run the real command yourself (`--yes`
|
||||
where it asks for a confirmation) and read the result back. Wait for the owner's yes only before an owner step.
|
||||
1. **The owner decides public and irreversible steps.** Submitting for review (App Review or Beta App Review),
|
||||
releasing a version, resuming or completing a rollout, canceling a submission, deleting products or listings,
|
||||
accepting agreements, sending review replies, inviting or removing testers, changing prices, starting or stopping
|
||||
a store experiment: explain what will happen and let the owner do it (or run the command only after a clear yes in
|
||||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
|
|
@ -60,8 +20,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
target audience: ask the owner when the code does not prove the answer, all such questions in one batch at the
|
||||
start (first rule, point 3), and write the answers into the config. A wrong "no" is worse than a slow "ask".
|
||||
target audience: ask the owner when the code does not prove the answer. A wrong "no" is worse than a slow "ask".
|
||||
6. **Pick builds by explicit number.** Use the build number / versionCode you just uploaded, never "the latest".
|
||||
7. **Long uploads run in the background with a log** (`storebound play images > .storebound/images.log 2>&1 &`) and
|
||||
you report the progress lines, not guesses.
|
||||
|
|
@ -70,20 +29,10 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
9. **Personal data stays local.** Tester lists, review reply drafts, health reports and analytics snapshots live in
|
||||
`.storebound/` (gitignored). Never put tester emails, reviewer names or crash logs into issues, docs or commits,
|
||||
and never ask for tester emails in chat (storebound masks them in its output).
|
||||
10. **Console forms without an API: drive them yourself, agent-first.** `storebound console plan <form> --json` (MCP
|
||||
`console_plan`) gives the start URL, steps, the answer sheet, the buttons you must never press and the verified UI
|
||||
facts. Drive the page with your own browser tool, adapt to what it shows, run long flows as an in-page async loop
|
||||
that writes `window.__log` (one evaluate call times out around 45 s), stop only before the final button (Publish,
|
||||
Submit, Create, a final Save) and tell the owner exactly what to press, then `storebound console verify <form>`.
|
||||
Never sign in, accept an agreement or grant a permission (a service account's app access) for the owner.
|
||||
`storebound console fill` is the optional scripted fast path; it never blocks you.
|
||||
11. **Console pages: always the absolute deep link.** When you send the owner to a console page, give the absolute
|
||||
deep link (storebound prints it; `storebound console plan` has start URLs), never just "go to App Store Connect"
|
||||
or "App Store Connect > App Information" alone.
|
||||
|
||||
## Tools
|
||||
|
||||
- CLI: `storebound <command>` (`storebound help`; outside the plugin: `npx storebound` on Node 20+ or `bunx storebound` on Bun); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
|
@ -103,17 +52,14 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
| `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game |
|
||||
| `aso-basics` | App store optimization basics for a mobile app's or game's text |
|
||||
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
|
||||
| `console-autofill` | Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default |
|
||||
| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes |
|
||||
| `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly |
|
||||
| `game-services` | Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section |
|
||||
| `listing-localization` | Translate the store listing of a mobile app or game into more languages |
|
||||
| `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` |
|
||||
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |
|
||||
| `portfolio-originality` | Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) |
|
||||
| `ppp-pricing` | Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp` |
|
||||
| `privacy-manifest` | Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game |
|
||||
| `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games |
|
||||
| `release-flows` | Repo-local workflows for a mobile app or game |
|
||||
| `release-management` | Ship updates safely after the first release |
|
||||
| `revenuecat-sync` | Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config |
|
||||
| `review-access` | Give App Store and Google Play reviewers working access to an app behind a sign-in |
|
||||
|
|
@ -124,7 +70,6 @@ need to ...", do it instead, unless it is one of the owner steps in point 2.
|
|||
| `store-declarations` | Answer the store compliance forms for a mobile app or game |
|
||||
| `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores |
|
||||
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
||||
| `store-pitfalls` | Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each |
|
||||
| `store-preflight` | Run and read the storebound readiness checks before submitting a mobile app or game |
|
||||
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages |
|
||||
| `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config |
|
||||
|
|
|
|||
921
README.md
|
|
@ -1,118 +1,881 @@
|
|||
<p><img src="https://git.crt.fyi/CRT/storebound/raw/branch/main/brand/logo-mark-256.png" width="96" height="96" alt="storebound logo"></p>
|
||||
<p><img src="brand/logo-mark-256.png" width="96" height="96" alt="storebound logo"></p>
|
||||
|
||||
# storebound
|
||||
|
||||
**From an empty folder to "Submit for review" on Google Play and the App Store.**
|
||||
|
||||
Your AI agent does all of it with storebound: builds, uploads, store text, screenshots in every language and size,
|
||||
in-app products and prices, the compliance forms, even the consoles that have no API. You only press Submit.
|
||||
**Website: [storebound.dev](https://storebound.dev) · npm: [storebound](https://www.npmjs.com/package/storebound) · `bunx storebound init`**
|
||||
|
||||
[](https://www.npmjs.com/package/storebound)
|
||||
[](https://git.crt.fyi/CRT/storebound/src/branch/main/LICENSE)
|
||||
[](#install-and-start)
|
||||
[](https://git.crt.fyi/CRT/storebound/src/branch/main/package.json)
|
||||
[](https://git.crt.fyi/CRT/storebound/src/branch/main/skills)
|
||||
[](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/mcp.md)
|
||||
[](LICENSE)
|
||||
[](CHANGELOG.md)
|
||||
[](https://bun.sh)
|
||||
[](package.json)
|
||||
[](skills)
|
||||
[](#mcp-server)
|
||||
|
||||
**Website: [storebound.dev](https://storebound.dev) · Docs: [docs/](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/README.md) · `npx storebound init`**
|
||||
**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, account
|
||||
deletion and review access, privacy, icons, screenshots and previews, with one config and your AI coding agent.**
|
||||
|
||||
[](https://storebound.dev/#teaser)
|
||||
Hey, I'm CRTkafa. I built this while getting my own game through both stores and hit every wall on the way: draft
|
||||
apps, edits that die when you touch the Console, the "first IAP must ship with a version" dance, Data safety CSVs that
|
||||
silently need one more answer, an IARC questionnaire, target audience, App Privacy labels that are saved but not
|
||||
published, screenshots in 7 sizes x 14 languages... I wrote each fix down as code or as a checklist. None of those
|
||||
walls is game-only: a to-do app with accounts and a subscription hits the same ones, plus a few of its own (a demo
|
||||
account for the reviewer, account deletion, subscription disclosures), so storebound covers apps and games alike. It
|
||||
works for me, so I open-sourced it. Use it too.
|
||||
|
||||
<sub>Watch the teaser on [storebound.dev](https://storebound.dev/#teaser): the demo game from an empty folder to both stores, then the desktop app.</sub>
|
||||
No account, no sign-up, no telemetry. A small Bun CLI that talks to the official store APIs,
|
||||
Agent Skills that walk your AI coding tool (or you) through the parts that are still console clicks, and an MCP server
|
||||
so agents can call the CLI safely. **storebound never presses Submit, Release or Publish for you.**
|
||||
|
||||
## Your agent does the whole job
|
||||
Pick a profile and start from honest templates: `init --profile app` (utility / productivity app, optional account,
|
||||
analytics, no ads; the default), `--profile subscription-app` (accounts + auto-renewable subscriptions) or
|
||||
`--profile game` (free-to-play with ads and IAP).
|
||||
|
||||
**Do it, don't ask.** You ask once ("get my app ready for both stores"); your agent and storebound do the work:
|
||||
the app records, builds and uploads, listings in every language, screenshots and previews in every store size, icons,
|
||||
in-app products and subscriptions priced in 175 countries, Data safety, App Privacy, age rating and every other form,
|
||||
and the console pages that have no API (the agent drives them from a `console plan`). Each step is planned first:
|
||||
It keeps going after launch: TestFlight groups and testers, crash and ANR vitals against the store thresholds, review
|
||||
replies you approve before they go out, prices for many products and regions from one CSV, store analytics next to
|
||||
your listing changes, and App Store product page tests from your screenshot variants.
|
||||
|
||||

|
||||

|
||||
|
||||
You press only the final public or irreversible buttons (Submit for review, releasing, App Privacy Publish, legal
|
||||
agreements) and answer, once and in one batch, the facts no file can prove. The full rules: [AGENTS.md](https://git.crt.fyi/CRT/storebound/src/branch/main/AGENTS.md);
|
||||
the whole journey step by step: [docs/journey.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/journey.md).
|
||||
## The journey
|
||||
|
||||
## You won't get rejected for the avoidable things
|
||||
Everything an app or game needs before review, in the order I do it. For each step: what storebound does through the store
|
||||
APIs (or on your machine), what the skill walks your agent through where the stores have no public API, and what stays
|
||||
your own click.
|
||||
|
||||
`storebound scan` reads your project (Xcode and Gradle files, manifests, lockfiles, SDKs, your listings) and the store
|
||||
state, and names every App Review or Play policy problem it can prove before the stores do: the guideline, the
|
||||
evidence as `file:line`, and the fix.
|
||||
- **storebound**: a CLI command (also an MCP tool). Every write has `--dry`; MCP write tools default to a dry run.
|
||||
- **skill + agent (UI)**: no public API exists for it. The named skill has the exact navigation and the prepared
|
||||
answers. An agent with browser tools (a Chrome extension, computer use, a Playwright MCP ...) can click through it
|
||||
while you watch; without one, you click with the skill as your checklist.
|
||||
- **you**: public, legal or money steps. The skills tell every agent to stop and hand these to you.
|
||||
|
||||

|
||||
| # | step | storebound (API / local) | skill + agent (UI) | you |
|
||||
|---|---|---|---|---|
|
||||
| 1 | **Set up** | `init --profile app\|game\|subscription-app` (config, `store/*.md`, declarations, App Privacy and privacy templates per profile), `install --agent <tool>`, `check` | Play: service account + API access invite; App Store: API team key (`play-first-release`, `appstore-first-release`) | developer accounts; Paid Applications agreement, banking and tax; Play payments profile |
|
||||
| 2 | **App records and bundle id** | `apple bundle` registers the bundle id, `apple status` finds the app record | App Store Connect > New App (no API); Play Console > Create app; the very first AAB upload when Play needs it from the Console | the declarations you accept when creating the Play app |
|
||||
| 3 | **Builds and testers** | `play next-version-code`, `play build`, `play upload --track internal`, `apple signing ensure`, `apple build`, `apple upload` (waits for processing), `apple encryption`, `apple testflight groups / what-to-test / info / distribute` (internal groups) | Play internal testers list, Apple sandbox testers (`play-first-release`, `testflight`) | `apple testflight testers` (Apple emails the invitations), external groups and Beta App Review (`distribute --submit-review`) |
|
||||
| 4 | **In-app products and subscriptions** | `play products` (regional prices from USD + your overrides, activated), `apple iap` (consumable, non-consumable, non-renewing; localizations, price schedule, availability), `apple iap-review`, `apple subscriptions` (groups, levels, equalized prices, intro and promotional offers, offer codes), `play subscriptions` (base plans, regional prices, offers), `catalog diff` (both stores against one catalog) | Play license testers, Apple sandbox testers, "Add for Review" of the first IAPs and subscriptions into the version's submission, Play promo codes (`store-iap-setup`, `store-subscriptions`) | custom offer codes (`apple subscriptions --codes` asks first) |
|
||||
| 5 | **Store listings, every language** | `play listing` (title, short / full description, contact email + website, promo video URL), `apple listing --version x --build N` (name, subtitle, description, keywords, promo text, URLs, privacy URL, manual release), `whats-new`, `check` (limits), `check --aso` | Play store settings: category and tags (`play-first-release`) | |
|
||||
| 6 | **Play questionnaires** | `play data-safety`: the whole Data safety form from `dataSafety` in the config (CSV import through the API) | Policy and programs > App content, answers prepared in `store/declarations.md` (`store-declarations`): privacy policy, app access with the demo account (`review-access`), delete-account URL (`account-deletion`), ads, content rating (IARC), target audience and content, advertising ID, news, government, financial and health features; Data safety summary check | the answers themselves are your statements: the agent asks when the code does not prove them |
|
||||
| 7 | **App Store questionnaires** | `apple appinfo` (categories, age rating declaration, content rights, Free price, availability), `apple encryption` (export compliance from `apple.usesNonExemptEncryption`, never guessed), `apple review-details` (contact, demo account from `.storebound/`, notes) | App Privacy nutrition labels from `store/app-privacy.md`, then **Publish** (`store-declarations`); encryption documentation when the answer is yes (`export-compliance`); the first availability record if the API refuses it | the export compliance answer (a legal statement, set once in the config) |
|
||||
| 8 | **Privacy and accounts** | privacy policy page template (`init`), `privacy-manifest --ios <path>` (PrivacyInfo.xcprivacy, required-reason APIs, SDK manifests), `validate` checks the policy, delete-account and terms URLs answer | host the pages, link them in both consoles and inside the app; in-app account deletion (`privacy-policy`, `privacy-manifest`, `account-deletion`) | |
|
||||
| 9 | **Icons** | `icons`: App Store 1024 without alpha, Play 512, adaptive + legacy Android launcher icons, web icons, Capacitor sources | | |
|
||||
| 10 | **Screenshots and previews** | `shots capture / render / check / gallery`, `play images`, `apple screenshots`, `shots record / video`, `apple previews`, `apple ppo create / upload` (App Store product page tests from `shots` variants; see [Store art](#store-art)) | Play store listing experiments (optional, `store-screenshots`) | uploading the promo video to YouTube; `apple ppo start / stop` |
|
||||
| 11 | **Validate** | `scan` (offline: rejection risks in the project files, see [Catch rejections before you submit](#catch-rejections-before-you-submit)), `check` (offline) and `validate` (read-only on both stores: every blocker in fix order, plus the local renders) | the UI-only items `validate` cannot see (`store-preflight` lists them) | |
|
||||
| 12 | **Submit** | `play release --version-code N --production draft`, `apple status` | Play: countries / regions, open the production draft and save it (`play-first-release`) | **Play: Send changes for review. App Store: Submit for Review.** |
|
||||
| 13 | **After review** | `apple status --wait-review`, `apple release --phased on / pause`, `play rollout --halt`, reply drafts (`review-rejections`) | | releasing the approved version, resuming or completing a phased release or rollout (terminal commands that ask first, `release-management`) |
|
||||
| 14 | **Live app** | `health [--weekly]` (crash / ANR vitals vs Play's thresholds, App Store diagnostics; also in `validate`), `reviews list / draft`, `analytics snapshot / compare`, `prices export`, `prices import --dry`, `apple ppo status` | `store-health`, `review-replies`, `store-analytics`; Play statistics come from the reports bucket (no API) | `reviews send` (approved drafts only), `prices import` (asks first) |
|
||||
|
||||
Every rule, what it proves and what only a reviewer can see: [docs/rejections.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/rejections.md).
|
||||
New personal Play developer accounts also need a closed test with 12+ testers for 14 days before production; the
|
||||
`play-first-release` skill covers it.
|
||||
|
||||
## The desktop app: every app, both stores, one window
|
||||
### API or console, honestly
|
||||
|
||||
Every app and game you ship on Google Play and the App Store side by side: releases, charts, catalog and prices,
|
||||
crash health, reviews, TestFlight and the rejection checks. Send for review from there too: a dry run first, then a
|
||||
confirm, then your click. Same storebound underneath, same version number as the CLI, and the same store accounts
|
||||
and app folders as your terminal (`~/.storebound`).
|
||||
- **Through the API** (storebound does it): bundle id, builds on tracks, versions and build selection, listings in
|
||||
every language, graphics, screenshots, app previews, in-app products and prices (also from one CSV), Play Data
|
||||
safety, Apple age rating, categories, content rights, price and availability, export compliance answer, App Review
|
||||
details with the demo account, subscriptions (Apple groups, levels, prices, introductory and promotional offers,
|
||||
offer codes; Play base plans, regional prices, offers), phased release and staged rollout, TestFlight groups / testers / What to Test / Test Information / build
|
||||
processing / expiring builds, crash and ANR vitals and App Store diagnostics, TestFlight feedback, review replies,
|
||||
App Store analytics reports, sales and finance reports, App Store Product Page Optimization tests, IAP and
|
||||
subscription review submissions, offer codes for one-time purchases, win-back offers, promoted IAPs, pre-orders,
|
||||
custom product pages and in-app events, and pulling live listing texts back.
|
||||
- **Console only** (no public API; the skill + your agent's browser, or you): creating the App Store Connect app record
|
||||
and the Play app, Play App content (IARC content rating, target audience, ads, advertising ID, app access,
|
||||
government / financial / health / news, app access with the demo account), Play category and tags, Play countries,
|
||||
App Privacy labels and their Publish, Play promo codes, Play pre-registration, Play store listing experiments, test results of both stores' experiments, promotional images of promoted IAPs.
|
||||
Play store statistics have no API either: storebound reads the monthly exports from your Play reports bucket.
|
||||
- **Only you**: agreements, banking and tax, and the final Send for review / Submit for Review (apps, IAPs, custom
|
||||
product pages, in-app events). Releases and rollouts after approval, Beta App Review, tester invitations, sending
|
||||
review replies, applying price changes, starting / stopping a product page test, creating offer codes, win-back
|
||||
offers, switching on promoted IAPs, pre-orders and expiring builds too. None of these is an MCP tool; the terminal commands ask first.
|
||||
|
||||

|
||||
## Catch rejections before you submit
|
||||
|
||||
<details>
|
||||
<summary>More screens: portfolio, growth charts, prices, checks, TestFlight, console plan</summary>
|
||||
App Store rejections cost days: you wait for review, read one sentence in the Resolution Center, fix it, and wait
|
||||
again. On Google Play a policy problem can mean a blocked update, a removal or a strike on the account. Most of the
|
||||
usual ones are visible in the project long before that. `storebound scan` reads the project itself, offline and
|
||||
read-only (Xcode project, Info.plist and build settings, entitlements, PrivacyInfo.xcprivacy, Podfile.lock,
|
||||
Package.resolved, Cartfile, Gradle files and version catalogs, AndroidManifest.xml (and the merged manifest of a local
|
||||
build), res/xml and strings.xml, CMake / ndk-build files, Unity ProjectVersion.txt, package.json,
|
||||
Expo app.json, capacitor.config, Cordova config.xml, pubspec, Unity Packages/manifest.json, ProjectSettings and
|
||||
External Dependency Manager files, Godot export presets), plus your config and listing files. It works out the stack
|
||||
and the SDKs (ads, analytics, attribution, crash, sign-in, payments, push, with versions and the file:line they come
|
||||
from) and reports every rejection risk it can prove, each with the guideline, the evidence, the fix, a severity and the
|
||||
skill to open. On the teaser fixture (`tests/fixtures/scan/teaser`):
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
```text
|
||||
$ storebound scan
|
||||
Rejection risks: 2 blocker, 3 high, 0 medium, 0 low
|
||||
1. BLOCKER 2.1(a) · App Store · Sign-in is required but there is no demo account for App Review
|
||||
at storebound.config.ts:12 reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' },
|
||||
at storebound.config.ts:11 accounts: { enabled: true },
|
||||
at Podfile.lock:3 Google Sign-In: GoogleSignIn 7.1.0
|
||||
2. BLOCKER 5.1.1(v) · App Store · Accounts can be created but no in-app account deletion was found
|
||||
at storebound.config.ts:11 accounts: { enabled: true },
|
||||
at Planner/LoginView.swift:11 Button("Create account") { Task { try await AccountApi.signUp() } }
|
||||
at Planner/LoginView.swift:17 static func signUp() async throws {
|
||||
3. HIGH 4.8 · App Store · Third-party login (Google / Facebook / ...) without Sign in with Apple or another equivalent login option
|
||||
at Podfile.lock:3 Google Sign-In: GoogleSignIn 7.1.0
|
||||
at Planner/LoginView.swift:9 GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController()) { _, _ in }
|
||||
4. HIGH 3.1.1 · App Store · Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found
|
||||
at storebound.config.ts:16 com.example.planner.pro (non_consumable)
|
||||
5. HIGH 5.1.2(i) · App Store · Tracking-capable code without App Tracking Transparency (Google AdMob, IDFA)
|
||||
at Podfile.lock:2 Google AdMob: Google-Mobile-Ads-SDK 11.10.0
|
||||
at Planner/Ads.swift:7 print(ASIdentifierManager.shared().advertisingIdentifier)
|
||||
```
|
||||
|
||||
</details>
|
||||
Every finding also has a `fix:` line and the skill. Below the risks comes the declarations proposal: the Play Data
|
||||
safety and App Store App Privacy answers, App Tracking Transparency and privacy manifest entries the detected SDKs and
|
||||
code imply, each marked **detected (file:line)** or **ask owner**, as a diff against `dataSafety` / `appPrivacy` in
|
||||
the config. Nothing is written unless you run `storebound scan --write` (only detected answers; questions stay
|
||||
questions). The MCP tool `scan` is read-only and cannot write; `validate` includes the open scan findings; the desktop
|
||||
app shows them on the Checks tab. A finding you decided is fine goes into the config with its reason:
|
||||
`scan: { ignore: [{ rule: 'demo-account', reason: '...' }] }`.
|
||||
|
||||
`npx storebound desktop` installs it for you (macOS, Windows, Linux; signature checked, no admin rights) and opens it on
|
||||
the current app folder. Manual downloads: [storebound.dev/#download](https://storebound.dev/#download). Internals: [docs/desktop.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/desktop.md).
|
||||
| rule | App Store | Google Play | what scan proves |
|
||||
|---|---|---|---|
|
||||
| `demo-account`, `play-app-access` | 2.1(a) | App access | a sign-in (config, auth SDKs, sign-in code) without `reviewAccess` or without the demo account in `.storebound/` |
|
||||
| `account-deletion`, `play-deletion-url` | 5.1.1(v) | User Data: account deletion | sign-up or social login without a deletion path in code or `accounts.inApp`; no `accounts.deletionUrl` |
|
||||
| `login-services` | 4.8 | | Google / Facebook / other third-party login without Sign in with Apple or another equivalent option |
|
||||
| `restore-purchases`, `external-purchase`, `play-payments` | 3.1.1 | Payments | non-consumables or subscriptions without a restore path; card / PayPal SDKs next to in-app products; "buy on our website" (Play: unless `play.billingPrograms` lists user choice billing or external offers) |
|
||||
| `subscription-info` | 3.1.2(c), 3.1.2 | | no Terms of Use URL, no Terms link or renewal wording in the description, no legal links or "Manage subscription" in the app |
|
||||
| `att` | 5.1.2(i) | | tracking-capable SDKs or IDFA without ATT; the prompt without its purpose string; the string without a prompt |
|
||||
| `purpose-strings`, `unused-permission` | 5.1.1(ii), 5.1.1(iv), ITMS-90683 | | a used permission without its NS*UsageDescription; empty or vague strings; declared but unused |
|
||||
| `privacy-manifest` | ITMS-91053 / 91061 | | no PrivacyInfo.xcprivacy, required-reason APIs not declared, SDKs older than their first manifest version |
|
||||
| `privacy-policy-link`, `play-privacy-policy` | 5.1.1(i) | User Data: privacy policy | no privacy link in the app's sources (Play: every app; medium when it collects data), an `http://` link |
|
||||
| `privacy-labels` | 5.1.2 | User Data: Data safety | SDK data types missing from `dataSafety`; Play also: an answer narrower than the SDK's disclosure (purposes, sharing), SDKs with no `dataSafety` at all |
|
||||
| `play-prominent-disclosure` | | User Data: prominent disclosure, Location permissions | background location without a disclosure that says "location" and "background"; location, contacts, calendar or phone number access without any disclosure or rationale text in sources or `strings.xml` |
|
||||
| `play-background-location`, `play-photo-video`, `play-all-files-access`, `play-accessibility`, `play-install-packages`, `play-health-connect`, `play-full-screen-intent`, `play-vpn` | | Location permissions, Photo and Video Permissions, All files access, AccessibilityService API, REQUEST_INSTALL_PACKAGES, Health Connect, Full-screen intent, VpnService | the restricted permission or service in the manifest (or the merged manifest of a local build), each with the core-use test and the Play Console declaration it needs; `isAccessibilityTool` lowers the accessibility finding to medium |
|
||||
| `play-fgs`, `play-exact-alarm`, `play-query-all-packages`, `play-sms-call-log` | | Foreground service types, exact alarms, package visibility, SMS and Call Log | foreground services without a type or its permission (and the Console declaration); USE_EXACT_ALARM; QUERY_ALL_PACKAGES; SMS and call log permissions |
|
||||
| `kids-ads`, `play-families-ads`, `play-families-ad-id`, `play-families-location` | 1.3 | Families | a Kids Category age band with third-party ads or analytics SDKs; `play.targetAges` under 13 with an ad SDK that is not Families self-certified (or older than its certified version), the AD_ID permission in a child-only app (mixed audience: ad / attribution SDKs need child-directed treatment), location in a child-only app |
|
||||
| `play-ad-id` | | Advertising ID | targetSdk 33+ with ad / attribution SDKs and no AD_ID permission (medium when the merged manifest proves it is missing; Google Mobile Ads adds it itself) |
|
||||
| `play-16kb` | | 16 KB page sizes (updates blocked from 2027-02-01) | Unity before 6000.0.38f1 / 2022.3.56f1 / 2021.3.48f1, React Native before 0.77, NDK before r28 for the app's own C/C++ without the 16 KB flags, AGP before 8.5.1 with uncompressed native libraries; else prebuilt `.so` files to check |
|
||||
| `play-ads-launch` | | Ads, Better Ads Experiences | an interstitial shown from `onCreate` of the launcher activity (Android native; other engines: review-only) |
|
||||
| `play-testing-requirement` | | Testing for new personal accounts | `play.accountType: 'personal'` created after 2023-11-13 (12 testers, 14 days of closed testing before production); low when the account type is not set |
|
||||
| `other-platforms` | 2.3.10 | | "Android", "Google Play" and other stores in the App Store text or screenshot captions |
|
||||
| `metadata-keywords`, `kids-terms`, `play-metadata` | 2.3.7, 2.3.8 | Metadata | other apps' names, prices and "best / #1" in name, subtitle or keywords; keyword lists; "For Kids" outside the Kids Category. Play title over 30 characters, emoji, ALL CAPS, rank / price / promotion terms; other apps in the title or short description; repeated keywords or keyword lists in the full description |
|
||||
| `play-impersonation` | | Impersonation | a well-known brand in the package name or app name (low: a check, not a verdict) |
|
||||
| `placeholder-text` | 2.1(a) | Metadata | lorem ipsum, TODO, template lines in the listings |
|
||||
| `min-functionality` | 4.2 | | Capacitor `server.url` / Cordova `<content src>` on a remote site; a few native files around a remote WKWebView |
|
||||
| `deprecated-api`, `private-api` | 2.5.1 (ITMS-90809) | | UIWebView; `App-Prefs:` / `prefs:root` URL schemes |
|
||||
| `ipv6`, `ats` | 2.5.5, App Transport Security | | IPv4 literals in server URLs; NSAllowsArbitraryLoads |
|
||||
| `export-compliance` | export compliance | | no ITSAppUsesNonExemptEncryption and no `apple.usesNonExemptEncryption`, or the two disagree (never guessed) |
|
||||
| `review-prompt` | 5.6.1, 3.2.2(x) / 5.6.3 | | a custom "rate us" prompt without the system API; rewards for ratings |
|
||||
| `play-target-sdk` | | Target API level | below API 36 (Wear OS / Automotive 35, TV / XR 34) for new apps and updates since 2026-08-31 |
|
||||
| `play-package-name` | | Play Console upload | the reserved `com.example` prefix |
|
||||
|
||||
## Works with your AI, safe by design
|
||||
Rules cite Apple's App Review Guidelines and the Play Policy Center / Play Console Help pages they come from (checked
|
||||
2026-10-11, in the code comments of `cli/lib/scan/rules.ts` and `cli/lib/scan/play-rules.ts`); the SDK table with each
|
||||
vendor's data disclosure page and Google's Families self-certified ads SDK list is `cli/lib/scan/sdks.ts`. Play config
|
||||
the rules read: `play.targetAges` (Target audience age groups), `play.accountType` / `play.accountCreated`, and
|
||||
`play.billingPrograms`. When the project was built locally, scan also reads the merged manifest under
|
||||
`build/intermediates` (the permissions libraries add); otherwise it says that it could not. Not a rule because no Play
|
||||
policy page covers it: device admin apps (BIND_DEVICE_ADMIN); not a policy at all: Play Integrity / anti-tamper.
|
||||
|
||||
Skills, an MCP server and the CLI for Claude Code, Codex, Cursor, Gemini CLI, Copilot, Windsurf, OpenCode or
|
||||
anything that reads `AGENTS.md`. Every write shows a dry run first; submit, release and delete are not MCP tools; keys
|
||||
stay in env vars or the gitignored `.storebound/`.
|
||||
**Checked at review, not by scan** (no file shows them): crashes and hangs on the reviewer's device (2.1, `store-health`),
|
||||
links that are dead at review time (`validate` checks the configured URLs), screenshots and descriptions that do not
|
||||
match the app (2.3, `store-screenshots`), unfinished UI (4.0), "too simple" and spam / template apps (4.2, 4.3,
|
||||
`portfolio-originality`), IAPs that fail in the sandbox (2.1(b), `store-iap-setup`), the content of the privacy policy
|
||||
(`privacy-policy`), local law (5.2). On Google Play: whether a restricted permission really serves the app's core
|
||||
purpose (the Console declaration and its video decide), the wording and timing of a prominent disclosure, ad
|
||||
placements in Unity, Flutter or React Native code, the Health apps declaration answers, and the alignment inside a
|
||||
prebuilt `.so` (scan lists them; `zipalign -c -P 16` and `check_elf_alignment.sh` check the built app). The
|
||||
`review-rejections` skill covers what to do when one of these comes back.
|
||||
|
||||

|
||||
## 5-minute quick start
|
||||
|
||||
Per-tool setup: [docs/getting-started.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/getting-started.md#install-for-your-ai-tool) · MCP tools:
|
||||
[docs/mcp.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/mcp.md) · Safety model: [docs/safety.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/safety.md).
|
||||
|
||||
## Install and start
|
||||
|
||||
You need [Node](https://nodejs.org) 20+ or [Bun](https://bun.sh) 1.1+ (and `ffmpeg` for icons, screenshots and video).
|
||||
You need [Bun](https://bun.sh) 1.1+ (and `ffmpeg` for icons, screenshots and video).
|
||||
|
||||
```sh
|
||||
cd my-app
|
||||
npx storebound init # storebound.config.ts + .storebound/ in this project (--profile app | subscription-app | game)
|
||||
npx storebound desktop # installs the desktop app once (asks first) and opens it on this folder
|
||||
bun add -d storebound playwright # or: bun add -d git+https://git.crt.fyi/CRT/storebound.git playwright
|
||||
bunx storebound init # --profile app (default) | subscription-app | game: config, store/*.md, declarations, privacy policy, .storebound/ (gitignored)
|
||||
# fill in storebound.config.ts and the store/ files
|
||||
bunx storebound check # offline: config, copy limits, Data safety answers, products, files
|
||||
```
|
||||
|
||||
One product, installed once per machine: the CLI (`npx` / `bunx`) and the desktop app have the same version, the same
|
||||
store accounts (`~/.storebound/credentials`, `npx storebound accounts`) and the same list of app folders. Each project
|
||||
has its `storebound.config.ts` and a gitignored `.storebound/` (upload keystore, review contact). Then
|
||||
`npx storebound install --agent claude` (or codex, cursor, gemini, copilot, windsurf, opencode) and
|
||||
`npx storebound check`. Every `npx storebound ...` works as `bunx storebound ...` too.
|
||||
Add credentials (below), then walk the journey with dry runs first:
|
||||
|
||||
Then ask your agent: "take my app to Google Play and the App Store". Claude Code plugin, credentials, coming from
|
||||
fastlane: [docs/getting-started.md](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/getting-started.md).
|
||||
```sh
|
||||
bunx storebound apple bundle --dry
|
||||
bunx storebound play listing --dry
|
||||
bunx storebound play products --dry && bunx storebound apple iap --dry
|
||||
bunx storebound apple subscriptions --dry && bunx storebound play subscriptions --dry
|
||||
bunx storebound apple review-details --dry # contact + demo account from .storebound/ (masked) + notes
|
||||
bunx storebound play data-safety --dry --csv store/data-safety.csv
|
||||
bunx storebound apple appinfo --dry
|
||||
bunx storebound icons --dry
|
||||
bunx storebound shots capture && bunx storebound shots render && bunx storebound shots gallery
|
||||
bunx storebound validate # read-only: what still blocks a submission, per store, in fix order
|
||||
bunx storebound catalog diff # read-only: products + subscriptions on both stores vs the config, prices per region
|
||||
```
|
||||
|
||||
## What it covers
|
||||
After launch:
|
||||
|
||||
Store screenshots of the demo game, rendered by storebound in every size and language:
|
||||
```sh
|
||||
bunx storebound apple testflight what-to-test --build 42 --dry # then distribute --build 42 --group Team
|
||||
bunx storebound health --weekly # vitals + diagnostics, .storebound/health/<date>.md
|
||||
bunx storebound reviews draft # reply drafts in .storebound/replies/, then reviews send
|
||||
bunx storebound prices export && bunx storebound prices import --dry
|
||||
bunx storebound analytics snapshot && bunx storebound analytics compare
|
||||
```
|
||||
|
||||

|
||||
Or ask your agent: "take my app to Google Play and the App Store", "fill in the store questionnaires", "set up the
|
||||
in-app purchases and a yearly subscription with a free trial on both stores", "do both stores sell the same
|
||||
catalog", "the reviewer could not sign in", "make store screenshots in 5 languages", "is my app ready to submit", "why was my
|
||||
update rejected", "put build 42 on TestFlight", "how are our crash rates", "answer the new reviews", "did the new
|
||||
screenshots help". The matching skill takes over.
|
||||
|
||||
- [The journey](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/journey.md): every step from setup to Submit, what is API, what the agent drives in a console, what stays yours
|
||||
- [Rejection scan](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/rejections.md): every rule with its App Store guideline or Play policy
|
||||
- [Commands](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/commands.md): the full command reference
|
||||
- [Store art](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/store-art.md): screenshots, fonts, previews, variants
|
||||
- [Growth extras and console forms](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/growth.md): PPP prices, Apple Ads, web presence, RevenueCat, `console plan` / `console fill`
|
||||
- [Many apps, release trains, workflows](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/studios.md) · [Listings in more languages](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/listing-languages.md) · [Every API endpoint](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/api.md)
|
||||
- [Skills](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/skills.md) · [MCP server](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/mcp.md) · [Safety model](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/safety.md) · [Idempotency](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/idempotency.md) · [Pitfalls](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/pitfalls.md)
|
||||
- [Desktop app](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/desktop.md) · [Desktop releases](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/desktop-release.md) · [FAQ](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/faq.md) · [Roadmap, contributing, credits](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/project.md)
|
||||
### Coming from fastlane
|
||||
|
||||
## Contributing and license
|
||||
`storebound import fastlane` turns an existing fastlane setup into storebound files. It only reads (no Ruby is run),
|
||||
never overwrites anything and prints what it could not map:
|
||||
|
||||
Issues and pull requests are welcome; see [CONTRIBUTING.md](https://git.crt.fyi/CRT/storebound/src/branch/main/CONTRIBUTING.md) (`bun run ci` must be green).
|
||||
MIT, see [LICENSE](https://git.crt.fyi/CRT/storebound/src/branch/main/LICENSE). Copyright (c) 2026 CRTkafa. Not affiliated with Google or Apple.
|
||||
```sh
|
||||
bunx storebound import fastlane --dry # the plan + report; default --dir: fastlane/, ios/fastlane/, android/fastlane/
|
||||
bunx storebound import fastlane # writes the files below; an existing file gets a <name>.imported.<ext> copy
|
||||
bunx storebound init # adds the remaining templates, keeps the imported files
|
||||
bunx storebound check
|
||||
```
|
||||
|
||||
| fastlane | storebound |
|
||||
|---|---|
|
||||
| Appfile `app_identifier`, `package_name` | `apple.bundleId`, `play.packageName` |
|
||||
| deliver `metadata/<locale>/*.txt` (+ `default/`) | `store/appstore.md` per App Store locale; URLs, copyright, categories and review notes in the config |
|
||||
| supply `metadata/android/<lang>/*.txt`, newest `changelogs/<versionCode>.txt` | `store/listing.md` per Play language |
|
||||
| deliver and supply language folders | `languages[]` with both store codes (`tr` + `tr-TR`, `zh-Hans` + `zh-CN`, `he` + `iw-IL`) |
|
||||
| `screenshots/<locale>/`, `images/phoneScreenshots/`, `tenInchScreenshots/` | `store/shots/frames/<lang>/<phone\|tablet>/NN.png` with a `folder` capture source |
|
||||
| supply `icon`, `featureGraphic` | `play.icon`, `store/renders/<lang>/feature/1024x500.*` |
|
||||
|
||||
Keys and accounts are never copied: `json_key_file`, the API key, team ids, the App Review contact and demo account are
|
||||
named in the report with where they go (`.storebound/credentials.json`). Submission and release flags, `price_tier`,
|
||||
the age rating config, lanes and signing (`match`) are listed with their storebound counterpart. The
|
||||
`migrate-from-fastlane` skill walks an agent through it.
|
||||
|
||||
### Credentials (never in the repo)
|
||||
|
||||
Read from environment variables, or from `.storebound/credentials.json` in your project (gitignored by `init`):
|
||||
|
||||
| name | what |
|
||||
|---|---|
|
||||
| `PLAY_SERVICE_ACCOUNT` | path to the Google Cloud service account JSON key (or the JSON itself) with access to your app in Play Console |
|
||||
| `ASC_KEY_ID`, `ASC_ISSUER_ID` | App Store Connect API team key (Users and Access > Integrations) |
|
||||
| `ASC_P8` | path to `AuthKey_<id>.p8` (default `~/.appstoreconnect/private_keys/AuthKey_<id>.p8`) |
|
||||
| `ASC_VENDOR_NUMBER` | vendor number for `reports apple-sales` / `apple-finance` (Payments and Financial Reports) |
|
||||
| `ANDROID_KEYSTORE`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD` | upload key for `play build` (path to the .jks / .p12 and its passwords; handed to Gradle through the environment) |
|
||||
| `reviewContact` | (file only) App Review contact name / phone / email |
|
||||
| `reviewDemoAccount` / `REVIEW_DEMO_USER`, `REVIEW_DEMO_PASSWORD` | demo account for App Review (`reviewAccess.signInRequired`); never in the config or the repo, masked in logs |
|
||||
|
||||
Several store accounts on one machine: credential profiles (`~/.storebound/credentials/<profile>.json`, the same names
|
||||
except the per-app upload keystore)
|
||||
picked with `--account <profile>` or by a workspace ([Many apps and studios](#many-apps-and-studios)).
|
||||
|
||||
## Install for your AI tool
|
||||
|
||||
Every route gives the agent the same skills and the same MCP tools. Nothing here requires Claude: the skills are
|
||||
plain Markdown and the CLI is a normal command.
|
||||
|
||||
| tool | install |
|
||||
|---|---|
|
||||
| Claude Code | `/plugin marketplace add https://git.crt.fyi/CRT/storebound.git` then `/plugin install storebound@crtkafa` (skills, MCP server, `storebound` on PATH). Or per project: `bunx storebound install --agent claude` |
|
||||
| OpenAI Codex | `bunx storebound install --agent codex` (skills in `.agents/skills`, MCP in `.codex/config.toml`; Codex reads that file for trusted projects). The repo is also a Codex plugin (`.codex-plugin/plugin.json`, skills only) |
|
||||
| Gemini CLI | `gemini extensions install https://git.crt.fyi/CRT/storebound.git` (skills, MCP server, `GEMINI.md`). Or `bunx storebound install --agent gemini` |
|
||||
| Cursor | `bunx storebound install --agent cursor` (skills in `.agents/skills`, `.cursor/mcp.json`); the repo's `.cursor/rules/storebound.mdc` is an agent-requested rule you can copy |
|
||||
| VS Code / GitHub Copilot | `bunx storebound install --agent copilot` (skills in `.github/skills`, `.vscode/mcp.json`) |
|
||||
| Windsurf (Devin Desktop) | `bunx storebound install --agent windsurf` (skills in `.agents/skills`, MCP in your global `mcp_config.json`) |
|
||||
| OpenCode | `bunx storebound install --agent opencode` (skills in `.opencode/skills`, `opencode.json`) |
|
||||
| anything that reads `AGENTS.md` | copy or link `AGENTS.md` (rules + skill index) and use the CLI |
|
||||
|
||||
`install` takes several agents at once (`--agent codex,cursor`), `--dry` to preview, `--no-skills` / `--no-mcp`,
|
||||
and `--command "<cmd>"` to choose how the MCP server starts. It only adds or updates the `storebound` entry and its
|
||||
own skill folders; everything else in those files stays as it is, and re-running it is safe.
|
||||
|
||||
## Commands
|
||||
|
||||
Every write command takes `--dry`; re-runs are idempotent; output is one timestamped line per step, so long jobs can
|
||||
run in the background with a log (`storebound shots render > .storebound/render.log 2>&1 &`).
|
||||
|
||||
<details>
|
||||
<summary><b>Setup and checks</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `init [--profile app\|game\|subscription-app]` | local | copy the templates of a profile (default app), gitignore `.storebound/` |
|
||||
| `import fastlane [--dir fastlane] [--profile ...]` | local | config, `store/appstore.md`, `store/listing.md` and screenshot frames from a fastlane setup; never overwrites, reports what is not mapped |
|
||||
| `install --agent <tool>` | local | skills + MCP entry for an AI tool |
|
||||
| `mcp` | local | stdio MCP server wrapping the commands |
|
||||
| `serve --stdio` | local | JSON-RPC session for the storebound desktop app (see [Desktop machine interface](#desktop-machine-interface)) |
|
||||
| `inspect [--json]` | local | offline summary of the config: name, store ids, languages, products |
|
||||
| `check` | local | config, copy limits, data safety, products, subscriptions, profile (delete-account URL, demo account, terms URL), files; warns on untranslated release notes |
|
||||
| `catalog diff [--store] [--threshold 10]` | API, read-only | one catalog vs both stores: missing / extra / mismatched products and subscriptions, US and override prices, locales, offers, per-region price differences between the stores; exit 1 on mismatches |
|
||||
| `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims |
|
||||
| `scan [--store apple\|play] [--json] [--write]` | local, read-only | rejection risks in the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill; Data safety / App Privacy / ATT / privacy manifest proposal as a diff (`--write` adds the detected answers to the config); exit 1 on blockers |
|
||||
| `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left |
|
||||
| `originality --against <folders> [--json]` | local, read-only | Guideline 4.3 check vs your other apps: name, listing text, icon and screenshot perceptual hashes, project structure; scores, near-duplicate flags, suggestions; exit 1 when flagged |
|
||||
| `whats-new [--since <tag>]` | local | draft player-facing release notes from git log into both listing files |
|
||||
| `whats-new --languages en,de,tr` / `check` / `apply` | local | one file per language (`store/whats-new/`) for your agent (or a `--translate` hook of yours) to translate, per-store limits (Play 500, App Store 4000), then into both listing files |
|
||||
| `catalog pull [--write]` | API, read-only + local | IAP and subscription texts on the stores vs the config: a proposal diff (`.storebound/pull/catalog.json`); the config is never rewritten |
|
||||
| `ads scan --ios <path>` | local | AdAttributionKit / SKAdNetwork: ad network ids, postback copy endpoints, attribution windows and cooldown, conversion value updates; exit 1 on a blocker |
|
||||
| `privacy-manifest --ios <path>` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests |
|
||||
| `api list \| coverage \| apple\|play <operation>` | API | every App Store Connect / Google Play operation (see [Every endpoint](#every-endpoint)); GET runs, writes are dry unless `--yes` in a terminal |
|
||||
| `desktop [--download]` | local | open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, `--download` saves it to ~/Downloads after checking its signature (never installs) |
|
||||
| `doctor [--json]` | local | which local tools are here (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install the missing ones |
|
||||
| `icons` | local | App Store 1024 (no alpha), Play 512, web, Capacitor sources, Android legacy launcher icons |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Google Play</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `play listing` | API | app details, title / short / full description per language, promo video URL (`play.video`) |
|
||||
| `play listing pull [--write]` | API, read-only + local | live listings back into `store/listing.md`: diff first, writes only with `--write` |
|
||||
| `play images [--variant b]` | API | icon, feature graphic, phone / 7" / 10" screenshots, one edit per language |
|
||||
| `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate |
|
||||
| `play subscriptions [--csv]` | API | subscriptions: listings + benefits, one auto-renewing base plan, regional prices, intro and extra offers, activate (plan first, asks) |
|
||||
| `play data-safety` | API | Data safety form (CSV import); `--csv` writes the file |
|
||||
| `play build [--version-code N] [--flavor f]` | local + API read | Gradle `bundleRelease` (Flutter `flutter build appbundle`; Capacitor, React Native, Unity export found) with the next free versionCode and the upload key from env / `.storebound` (passed through the environment, never argv); AAB checked and copied to `build/android/` |
|
||||
| `play upload [<aab>] --track internal\|alpha\|beta` | API | AAB to a testing track with release notes; versionCode checked first; `--dry` is read-only, a real run asks |
|
||||
| `play release <aab>` | API | upload + tracks (`--internal completed --production draft`, `--production inProgress --fraction 0.05`), release notes |
|
||||
| `play rollout` | API | `--fraction x`, `--halt`, `--resume`, `--complete` (asks first, except halt) |
|
||||
| `play next-version-code` | API, read-only | next free versionCode |
|
||||
| `play status` | API, read-only | tracks, listings, products |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>App Store</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `apple bundle` | API | register the bundle id, find the app record |
|
||||
| `apple listing --version x.y.z [--build N]` | API | version (manual release), the build with exactly that number, texts per locale |
|
||||
| `apple listing pull [--version x.y.z] [--write]` | API, read-only + local | live texts back into `store/appstore.md`: diff first, writes only with `--write` |
|
||||
| `apple screenshots [--variant b]` | API | 6.9" + 6.5" (+ 13" iPad with `apple.ipad`, + 6.3" with `apple.iphoneMedium`) per locale, MD5-idempotent |
|
||||
| `apple previews [--poster 5]` | API | app preview videos per locale, checked first, MD5-idempotent, poster frame |
|
||||
| `apple iap` / `apple iap-review` | API | IAPs (consumable, non-consumable, non-renewing), localizations, price schedules, availability / review screenshots |
|
||||
| `apple iap-submit [--with-version] [--no-submit]` | API | IAP / subscription / group versions into a review submission (the first of a type together with the app version); asks before adding and before submitting |
|
||||
| `apple offer-codes [--codes]` | API | offer code campaigns for one-time purchases; custom and one-time-use codes only with `--codes` (asks; codes saved to `.storebound/offer-codes/`) |
|
||||
| `apple win-back` | API | win-back offers for lapsed subscribers (asks: they go live on their start date) |
|
||||
| `apple promoted [--enable]` | API | promoted in-app purchases: create (disabled), order, switch on (asks) |
|
||||
| `apple preorder status \| enable --release-date \| end` | API | pre-orders per territory (enable / end ask first) |
|
||||
| `apple cpp list \| create \| upload \| submit \| visible` | API | custom product pages from the config and a shots variant; submit / visible ask first |
|
||||
| `apple events list \| create \| upload \| submit` | API | in-app events with schedule, localizations, card and details images; submit asks first |
|
||||
| `apple subscriptions [--csv] [--codes]` | API | groups, subscriptions, levels, localizations, availability, equalized prices + overrides + CSV (scheduled changes), introductory and promotional offers, offer code campaigns, review screenshots (plan first, asks; custom codes only with `--codes`) |
|
||||
| `apple appinfo` | API | categories, age rating, content rights, Free, territories |
|
||||
| `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) |
|
||||
| `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) |
|
||||
| `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) |
|
||||
| `apple signing status` | API, read-only | bundle id capabilities, distribution certificates (with / without a private key on this Mac), App Store profiles per bundle id, installed or not |
|
||||
| `apple signing ensure [--keychain] [--no-install]` | API | missing capabilities, a distribution certificate from a key made here (kept 0600 in `.storebound/signing/`, never printed), App Store profiles installed for Xcode; dry first, asks; Developer ID needs the Account Holder (403 explained) |
|
||||
| `apple build [--version x.y.z] [--build-number N]` | local + API read | xcodebuild archive + exportArchive with a generated ExportOptions.plist (app-store-connect, team, signing style, profiles) and the API key; next build number; Capacitor, React Native, Flutter, Unity projects found |
|
||||
| `apple upload [<ipa>] [--via api\|altool]` | API | IPA through the App Store Connect API build upload (or altool), build number checked, waits until VALID (exit 0 / 1 / 7); dry first, asks |
|
||||
| `apple next-build` | API, read-only | next safe build number |
|
||||
| `apple status` | API | versions, builds, IAPs, submissions; `--wait-review` (exit 0 / 1 / 7); `--cancel-submission <id>` |
|
||||
| `apple ppo status \| create --variant b \| upload --variant b` | API | Product Page Optimization test from `shots` variants: treatments, localizations, screenshot sets |
|
||||
| `apple ppo start \| stop` | API | start / stop the test (asks first; a stopped test cannot be restarted) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>TestFlight</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `apple testflight status` | API, read-only | groups, testers and builds per group, recent builds with internal / external beta states |
|
||||
| `apple testflight groups` | API | create the groups of `apple.testflight.groups` that are missing |
|
||||
| `apple testflight testers [--csv f] [--remove] [--invite]` | API | testers from a CSV in `.storebound/` into their groups (asks first; emails masked) |
|
||||
| `apple testflight what-to-test --build N` | API | "What to Test" per locale from `store/appstore.md` (`whatToTest`, else `whatsNew`) |
|
||||
| `apple testflight info` | API | Beta App Description, feedback email, URLs, Beta App Review contact and notes |
|
||||
| `apple testflight distribute --build N --group a,b [--submit-review]` | API | the build to groups; external groups and Beta App Review ask first |
|
||||
| `apple testflight wait --build N [--timeout 60m]` | API, read-only | until processing ends, with progress; exit 0 VALID / 1 FAILED / 7 timeout |
|
||||
| `apple testflight expire --keep N \| --older-than D` | API | expire old builds (never attached or processing ones); dry run, then asks |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>After launch</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `health [--weekly] [--days 7]` | API, read-only | Play vitals (user-perceived crash / ANR vs 1.09 % / 0.47 %, devices, top issues), App Store metrics, diagnostics, TestFlight crashes; `--weekly` writes a Markdown report |
|
||||
| `reviews list [--unanswered]` | API, read-only | recent reviews of both stores |
|
||||
| `reviews draft` | API + local | one reply draft per unanswered review in `.storebound/replies/` |
|
||||
| `reviews send` | API | sends drafts with `approved: true` (checks length and incentives, asks first) |
|
||||
| `prices export` | API + local | current prices of every product, both stores, as `store/prices.csv` |
|
||||
| `prices import [--reconvert]` | API | diff table, then (asks first) Apple price schedules incl. future-dated changes and Play regional prices |
|
||||
| `analytics setup` | API | App Store analytics report request (once, Admin key) |
|
||||
| `analytics snapshot [--days 28]` | API + local | impressions, page views, downloads (App Store), visitors, acquisitions, installs (Play reports bucket) -> `.storebound/analytics/` |
|
||||
| `analytics compare` | local | snapshots vs the git history of the store files: before / after each listing change |
|
||||
| `reports apple-sales \| apple-finance \| play-earnings \| play-sales` | API, read-only + local | sales / finance reports into `.storebound/reports/`, summary per product and currency, CSV export |
|
||||
| `triage [--days 14]` | API, read-only | TestFlight crash and screenshot feedback, Play error reports: grouped by signature with devices, OS versions, builds |
|
||||
| `aso rank [--storefronts us,de]` | network + local | App Store rank per keyword and storefront plus competitors from the public iTunes Search API (rate limited) -> `.storebound/aso/` |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Screenshots and video</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `shots capture [--source web\|ios-sim\|android-emu\|folder]` | local | raw frames from your running app or game |
|
||||
| `shots fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...) |
|
||||
| `shots render [--variant b \| --variants]` | local | every store size and language in the game or app style, feature graphic, contact sheet, overflow report |
|
||||
| `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) |
|
||||
| `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, videos, folder frames |
|
||||
| `shots gallery` | local | `<renders>/index.html` review page |
|
||||
| `shots record [--source ...]` | local | app or gameplay clips: web (Chromium screencast), simulator, emulator, folder |
|
||||
| `shots video [--target iphone,ipad,youtube]` | local | app previews + promo video with captions, poster, checks |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Many apps and release trains</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `ws init` | local | find the app folders below and write `storebound.workspace.json` (globs like `games/*`) |
|
||||
| `ws list [--all]` | local | apps (folders + store-only apps), studios, accounts and whether each credential profile has its keys |
|
||||
| `ws status [--offline] [--apps a,b]` | API, read-only | portfolio table: every app x both stores (live / rollout % / next version), catalog parity, check; parallel |
|
||||
| `ws check`, `ws validate [--apps a,b]` | local / API, read-only | the offline check / the readiness report of every app in one table |
|
||||
| `ws run <command> --apps a,b \| --all [--apply]` | per command | any read command in every app; writes as dry runs unless `--apply`; never submit / release / rollout / send |
|
||||
| `ws apps import --account <profile>` | API, read-only + local cache | the apps a store account sees, paired with the folders (the desktop's rules) |
|
||||
| `ws desktop export [--out f \| --merge [--apply]]`, `ws desktop import` | local | the workspace to and from the desktop app's state (labels, never keys) |
|
||||
| `release status [--app a,b] [--versions]` | API, read-only | both stores on one train per version: build > testing > review > live > rollout % |
|
||||
| `release plan <version> [--app a]` | API, read-only | what is left for that version on each store, in fix order, with the owner's next step |
|
||||
|
||||
</details>
|
||||
|
||||
## Growth extras
|
||||
|
||||
Optional commands for after (or around) the first release. Each has `--dry` and `--json`; store and API writes ask in
|
||||
a terminal first and are never offered over MCP.
|
||||
|
||||
- **Purchasing power prices:** `storebound prices ppp [--base 4.99] [--source worldbank|bigmac|file]` proposes a price
|
||||
per region from the bundled World Bank ICP PPP conversion factors (`cli/data/ppp-worldbank.json`, CC BY 4.0, dated
|
||||
and cited; refresh with `bun tools/update-ppp.ts`), clamped to `prices.ppp.floor`..`ceiling` of the US price and
|
||||
snapped to each store's price points. It writes a sheet in the `prices import` format (default
|
||||
`store/prices-ppp.csv`) and shows the diff; `storebound prices import --csv store/prices-ppp.csv --dry` applies it.
|
||||
Skill: `ppp-pricing`.
|
||||
- **Apple Ads:** `storebound ads apple status | campaigns | report [--by campaign|keyword] [--csv out.csv]`: spend,
|
||||
taps, installs, CPA, read-only (OAuth client credentials from env / `.storebound/`, never printed). `bid`, `budget`
|
||||
and `pause` print old -> new and ask first. Skill: `apple-ads`.
|
||||
- **Web presence:** `storebound web init [--landing]` writes `apple-app-site-association`,
|
||||
`.well-known/assetlinks.json` (Play app signing SHA-256), the Smart App Banner tag and an optional minimal landing
|
||||
page (store marks from simple-icons, privacy / support links from the config). `storebound web check <domain>`
|
||||
verifies the live files: 200 without redirects, JSON content type, valid JSON, ids match the config. Skill: `web-presence`.
|
||||
- **Ad-hoc and internal sharing:** `storebound apple adhoc devices | register | profile | options | export` (UDIDs
|
||||
masked; registering asks first) and `storebound play share --aab app.aab` (Play internal app sharing; asks first,
|
||||
prints the install link). Skill: `adhoc-distribution`.
|
||||
- **RevenueCat (optional):** `storebound revenuecat diff | sync` mirrors products, subscriptions, entitlements and a
|
||||
default offering into a RevenueCat project (REST API v2, secret key from env / `.storebound/`). sync only creates and
|
||||
attaches, never deletes. Runtime entitlements, receipts and paywalls stay RevenueCat's job. Skill: `revenuecat-sync`.
|
||||
- **Console autofill for forms without an API:** `storebound console fill <form>` (`apple-app-record`,
|
||||
`apple-age-rating`, `apple-app-privacy`, `play-content-rating`, `play-target-audience`) opens a visible Chromium
|
||||
with a profile you sign in to yourself, fills what the config proves, highlights the rest and stops before any
|
||||
Save / Submit / Publish: you click. When the page has changed it falls back to step-by-step guidance with copyable
|
||||
answers. **Console pages change; this is AI-assisted: review every field and save it yourself.** Desktop: "Fill in
|
||||
console" on the App info tab. Never over MCP. Skill: `console-autofill`.
|
||||
|
||||
MCP gets only the safe parts: `prices_ppp`, `web_init`, `apple_adhoc_options` (local files, dry run by default) and
|
||||
the reads `ads_apple_status`, `ads_apple_campaigns`, `ads_apple_report`, `web_check`, `apple_adhoc_devices`,
|
||||
`revenuecat_diff`.
|
||||
|
||||
## Many apps and studios
|
||||
|
||||
A studio with twenty games, or a developer with apps under two store accounts, works from one folder above the app
|
||||
folders. `storebound ws init` writes `storebound.workspace.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"apps": ["games/*", { "path": "apps/notes", "apple": "solo-apple" }],
|
||||
"studios": [
|
||||
{ "name": "Acme Games", "color": "indigo", "apps": ["games/*"],
|
||||
"accounts": [{ "store": "apple", "profile": "acme-apple" }, { "store": "play", "profile": "acme-play" }] }
|
||||
],
|
||||
"accounts": [{ "store": "apple", "profile": "solo-apple", "label": "Solo" }],
|
||||
"ignore": ["games/old-*"],
|
||||
"overrides": { "pairs": [], "unpairs": [], "links": [], "appStudio": [] },
|
||||
"concurrency": 4
|
||||
}
|
||||
```
|
||||
|
||||
- **apps**: folders or globs (only folders with a `storebound.config.*` count; `node_modules` and dot folders are
|
||||
skipped). An object entry names the folder's own credential profiles.
|
||||
- **studios**: name, colour (the desktop's set), the store accounts and the app folders (globs) that belong to it.
|
||||
- **accounts**: store accounts without a studio. An account is a store and a **credential profile** name, never a key.
|
||||
- **ignore**: folder globs, `app:<store app key>` and `account:<profile>`, as in the desktop's ignore list.
|
||||
- **overrides**: the desktop's pairing corrections (`pairs`, `unpairs`, `links` of a store app to a folder,
|
||||
`appStudio`), with folders named by their path. A `storebound.workspace.ts` with `export default { ... }` works too.
|
||||
|
||||
Which keys an app uses: its own entry's profiles, else the single account of that store in its studio, else the
|
||||
single account of that store in the workspace, else the folder's own credentials (env or `.storebound/`).
|
||||
|
||||
**Credential profiles** keep many accounts apart on one machine: `~/.storebound/credentials/<profile>.json` with the
|
||||
account names of `.storebound/credentials.json` (`PLAY_SERVICE_ACCOUNT`, `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_P8`,
|
||||
`ASC_VENDOR_NUMBER`; the Android upload keystore belongs to the app and stays in the project;
|
||||
relative key paths are relative to that folder, which `STOREBOUND_CREDENTIALS_DIR` can move), or env
|
||||
`STOREBOUND_PROFILE_<NAME>_<KEY>` (for CI). Any command takes `--account <profile>`. `ws list` shows per account whether
|
||||
its profile has keys; no command prints a key.
|
||||
|
||||
`ws status`, `ws check`, `ws validate` and `ws run` read the apps a few at a time (`concurrency`, 1-8, or
|
||||
`--concurrency`), each app with its own keys handed to its child process only. `ws run` takes any read command and
|
||||
the MCP tool set; write commands get `--dry` unless `--apply`, and submit, release, rollout, send, start / stop,
|
||||
testers and `--yes` are refused: those stay with the owner in the app folder.
|
||||
|
||||
`ws apps import --account <profile>` lists the apps a store account sees (as `apps list`) into
|
||||
`.storebound/workspace/` and pairs them with the folders by the desktop's rules (`cli/lib/identity.ts`, the same code):
|
||||
a folder takes the store apps its config names, the remaining iOS and Android apps pair by id, close id or name,
|
||||
`unpairs` keep two apart, and the rest are store-only apps that `ws status` reads too.
|
||||
|
||||
**The desktop app** keeps the same model (studios, accounts, folders, overrides). `ws desktop import` turns its
|
||||
`state.json` (or `--state <file>`) into a workspace file and lists the credential profiles to create: the desktop's
|
||||
keychain is never read. `ws desktop export` prints the workspace as a desktop state (`--out <file>`), and
|
||||
`--merge --apply` adds it to the desktop's `state.json` while the app is closed (a backup is kept; nothing is
|
||||
removed; new accounts get their keys in the desktop's Accounts screen).
|
||||
|
||||
MCP: `workspace_list` (offline) and `workspace_status` (read-only).
|
||||
|
||||
## Release trains
|
||||
|
||||
One version, both stores, one track: **build > testing > review > live > rollout**. The CLI and the desktop's Releases
|
||||
tab share the code (`cli/lib/train.ts`, `cli/lib/portfolio.ts`), so both show the same stage for the same store state.
|
||||
|
||||
```
|
||||
$ storebound release status
|
||||
app version train App Store Google Play
|
||||
------ ------- ------- ---------------------- -----------------------------
|
||||
Puzzle 2.3.0 current rollout 20% (build 45) rollout 10% (build 230)
|
||||
Puzzle 2.4.0 next build testing (build 240, internal)
|
||||
```
|
||||
|
||||
`release plan <version>` lists what is left for that version on each store in fix order: config problems (`check`),
|
||||
the version on the store (how to create it when it is missing), store blockers (`validate`, while nothing is
|
||||
submitted), the next move and the warnings. Owner steps (submit for review, promote to production, release an approved
|
||||
version, raise or complete a rollout) are named with where the owner does them; storebound does not do them. A store
|
||||
it cannot read is "unknown", never "not there". Both commands work in an app folder (that app) and in a workspace
|
||||
(every app, or `--app a,b`); `--json` gives the structured result. MCP: `release_status`, `release_plan` (read-only).
|
||||
## Every endpoint
|
||||
|
||||
The commands above cover the journey. For anything else, `storebound api` calls **every operation** of the App Store
|
||||
Connect API (1303 operations, OpenAPI 4.5.1) and of the Google Play Developer APIs (Android Publisher v3: 145,
|
||||
Play Developer Reporting v1beta1: 25), generated from the official specs pinned in `specs/` (source URLs, dates and
|
||||
SHA-256 in `specs/SOURCES.json`). Same credentials, same retries on 429 / 5xx (Retry-After honoured), JSON:API
|
||||
documents on the Apple side.
|
||||
|
||||
```sh
|
||||
storebound api list --store apple --search "customerReviews" # find an operation
|
||||
storebound api apple apps_getCollection --param 'filter[bundleId]=com.example.app'
|
||||
storebound api apple GET /v1/apps/123/appStoreVersions --all-pages # METHOD path works too
|
||||
storebound api play reviews.list --param packageName=com.example.app --all-pages --json
|
||||
storebound api play POST /v1beta1/apps/com.example.app/crashRateMetricSet:query --body query.json
|
||||
storebound api coverage # counts per API and resource, what commands wrap
|
||||
```
|
||||
|
||||
- **GET runs right away** (so do the Reporting API `:query` calls and other POSTs that only read).
|
||||
- **Every write is a dry run by default**: it prints the exact request (method, URL, body; the credential is never
|
||||
shown) and is only sent with `--yes` from an interactive terminal.
|
||||
- **Owner-only operations** (submit, release, delete, cancel, refunds, prices, testers and users, review replies,
|
||||
product page tests, Play `edits.commit`, app signing; the list is in `cli/api/gate.ts`) also ask you to type the
|
||||
operation id before anything is sent.
|
||||
- **Agents read, never write**: MCP has one tool for this, `api_get` (GET operations only). Under MCP or the desktop
|
||||
app no write goes out, whatever the flags.
|
||||
- Small on purpose: one table row per operation plus generic helpers (`cli/api/`), typed from the rows (path and
|
||||
required parameters, JSON:API request and response shapes). `bun tools/gen-api.ts` regenerates the tables and
|
||||
[docs/api-coverage.md](docs/api-coverage.md) (every operation, its gate and the commands that already call it);
|
||||
CI fails when they are stale.
|
||||
|
||||
## Store art
|
||||
|
||||
Screenshots and previews are one step of the journey, but the one that takes the longest by hand, so storebound
|
||||
does a lot here. Two looks: `shots.style: 'game'` (sunburst, sparkles, badges) and `shots.style: 'app'` (calm
|
||||
gradient, a clean device frame, headline + subline). Everything below was made by storebound itself from two tiny
|
||||
fictional demos: [a game](examples/demo-game) ("Prism Puddle", procedural art) and [an app](examples/demo-app)
|
||||
("Tidy Lists", one static page with sample data): raw frames captured from the web build, captions in several
|
||||
languages, every store size, a review gallery and an app preview video. No store account needed to try it.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
| Play feature graphic | App preview (App Store, 886 x 1920) |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||

|
||||
|
||||
<details>
|
||||
<summary>Contact sheet of one language (every size, packed into a grid)</summary>
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
### How it works
|
||||
|
||||
1. **Frames.** Give your app or game a few switches (language, demo data or a fixed seed, no ads, jump to a screen,
|
||||
freeze, autoplay) and
|
||||
let `shots capture` take the frames: Playwright for a web build, `simctl` for anything that runs in the iOS
|
||||
Simulator (Unity, Godot, Flutter, React Native, native, Capacitor), `adb` for an Android emulator or device, or bring a folder of
|
||||
your own frames. The status bar is cropped off and redrawn clean (9:41, full battery).
|
||||
2. **Copy.** Per language and scene: eyebrow, two-line title, subtitle, badges. Fonts are subset from Google Fonts to
|
||||
exactly your characters, so Japanese, Chinese, Korean, Arabic (right to left) and Hindi just work.
|
||||
3. **Render.** Every store size at exact pixels: iPhone 6.9" and 6.5", 13" iPad (if your app runs on iPad), Play
|
||||
phone, 7" and 10" tablets, the 1024 x 500 feature graphic. 24-bit RGB, no alpha (both stores reject it).
|
||||
4. **Check and review.** `shots check` applies the store rules locally (sources cited in `cli/shots/spec.ts`);
|
||||
`shots gallery` puts everything on one page with problems outlined. `validate` repeats the checks next to the
|
||||
store state.
|
||||
5. **Variants.** Other first screenshot, order or copy as `shots.variants`, rendered side by side, for a Play store
|
||||
listing experiment or an App Store Product Page Optimization test (set up in the consoles; storebound makes and
|
||||
checks the images).
|
||||
6. **Video.** `shots record` films the autoplay mode, `shots video` cuts 15-30 s App Store previews (886 x 1920,
|
||||
1200 x 1600) and a 9:16 / 16:9 promo for YouTube with captions in every language, `apple previews` uploads them.
|
||||
Play takes a YouTube URL in `play.video`.
|
||||
|
||||
Details: the [store-screenshots](skills/store-screenshots/SKILL.md) and [app-previews](skills/app-previews/SKILL.md)
|
||||
skills.
|
||||
|
||||
## Skills
|
||||
|
||||
In journey order. Each one says which steps are API (storebound) and which are console clicks, with the exact
|
||||
navigation.
|
||||
|
||||
| skill | for |
|
||||
|---|---|
|
||||
| `migrate-from-fastlane` | `storebound import fastlane`: ids, listings, languages and screenshots from fastlane; keys and accounts stay out |
|
||||
| `play-first-release` | Google Play from zero to "In review" |
|
||||
| `appstore-first-release` | App Store from API key to "Waiting for review", incl. xcodebuild with the API key |
|
||||
| `build-and-sign` | API signing (capabilities, certificate, profiles), `apple build` / `apple upload`, `play build` / `play upload`, for native, Capacitor, React Native, Flutter and Unity projects |
|
||||
| `testflight` | beta groups, testers from a CSV that never enters git, What to Test, Test Information, Beta App Review, waiting for processing, expiring old builds |
|
||||
| `store-iap-setup` | in-app products on both stores (consumable, non-consumable, non-renewing), prices and the price sheet CSV, catalog diff, testers, review submissions through the API and the first-IAP-with-version rule |
|
||||
| `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission |
|
||||
| `review-access` | demo account for reviewers (App Review fields, Play App access), never committed |
|
||||
| `account-deletion` | Apple 5.1.1(v) in-app deletion, Play delete-account web page and Data safety |
|
||||
| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing, keyword ranks via the iTunes Search API |
|
||||
| `app-store-promotion` | IAP offer codes, win-back offers, promoted IAPs, pre-orders (Play pre-registration: console guide), custom product pages, in-app events |
|
||||
| `store-declarations` | every questionnaire: Play Data safety (API) and App content (IARC, target audience, ads, advertising ID, app access, government / financial / health), Apple App Privacy labels and age rating |
|
||||
| `export-compliance` | encryption answer, Info.plist key, declarations; never exempt by default |
|
||||
| `privacy-policy` | one policy page for all your apps with a per-app services table (templates per profile) |
|
||||
| `privacy-manifest` | PrivacyInfo.xcprivacy, required-reason APIs, SDK manifests (ITMS-91053 / 91061) |
|
||||
| `app-icons` | one artwork to every icon, adaptive / legacy launcher pitfalls |
|
||||
| `store-screenshots` | capture from any engine, copy, fonts, render, checks, gallery, variants, App Store product page tests, Play experiments, upload |
|
||||
| `app-previews` | app or gameplay clips, App Store previews, Play promo video, checks, upload |
|
||||
| `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` and `release plan` before submitting; `ws check` / `ws validate` for many apps |
|
||||
| `release-management` | updates: release trains (`release status`, `release plan`), Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait |
|
||||
| `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` before submitting |
|
||||
| `store-api` | any App Store Connect / Google Play operation without a command: find it, read freely, writes dry until the owner sends them |
|
||||
| `release-management` | updates: Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait, pulling console edits back |
|
||||
| `store-health` | crash / ANR vitals vs Play's bad behavior thresholds, App Store diagnostics, weekly report, crash and feedback triage |
|
||||
| `review-replies` | reply drafts, tone, no incentives, store limits, the owner approves and sends |
|
||||
| `store-analytics` | App Store analytics reports, Play reports bucket, before / after listing changes, sales / finance / earnings reports |
|
||||
| `whats-new` | player-facing release notes from git, one file per language for your agent to translate, store limits checked |
|
||||
| `review-rejections` | triage a rejection (fix / clarify / push back / appeal), reply template, the guidelines apps and games hit |
|
||||
| `ads-mediation-checks` | AdMob, AppLovin MAX and LevelPlay: ids, debug tools, adapters, app-ads.txt, SKAdNetwork, AdAttributionKit (`ads scan`), no-fill (`ads-levelplay-checks` stays as a pointer) |
|
||||
| `portfolio-originality` | Guideline 4.3 gate for developers shipping many similar apps or games, with `storebound originality` scores |
|
||||
|
||||
## MCP server
|
||||
|
||||
`storebound mcp` speaks MCP over stdio, tools only: spec revision **2026-07-28** (stateless: `server/discover`,
|
||||
per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same process, clients that still open with
|
||||
`initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory
|
||||
(the server's working directory, or `STOREBOUND_PROJECT`) and returns the output.
|
||||
|
||||
- One tool per command. Read-only: `scan`, `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`,
|
||||
`analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`,
|
||||
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `workspace_list`, `workspace_status`,
|
||||
`release_status`, `release_plan`. Local writes: `import_fastlane`, `whats_new`, `icons`,
|
||||
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `api_get` (any App Store Connect or
|
||||
Google Play GET operation by id). Local writes: `import_fastlane`, `whats_new`, `icons`,
|
||||
`health_report`, `reviews_draft`, `prices_export`, `analytics_snapshot`, `shots_capture`, `shots_render`,
|
||||
`shots_gallery`, `shots_record`, `shots_video`. Store writes: `play_listing`, `play_images`, `play_products`,
|
||||
`play_data_safety`, `play_subscriptions`, `play_release_testing`, `apple_bundle`, `apple_iap`, `apple_iap_review`,
|
||||
`apple_subscriptions`, `apple_listing`,
|
||||
`apple_screenshots`, `apple_previews`, `apple_appinfo`, `apple_review_details`, `apple_encryption`,
|
||||
`apple_phased_release`, `apple_testflight_groups`, `apple_testflight_what_to_test`, `apple_testflight_info`,
|
||||
`apple_testflight_distribute` (internal groups only), `apple_ppo_create`, `apple_ppo_upload`, `analytics_setup`.
|
||||
- Annotations say what is read-only, destructive (replaces data), idempotent and network-bound.
|
||||
- No MCP SDK: a small newline-delimited JSON-RPC server (server/discover, initialize, ping, tools/list, tools/call,
|
||||
cancellation), so storebound keeps zero runtime dependencies.
|
||||
|
||||
Manual config for a tool that `install` does not know: command `bunx` with args `["storebound", "mcp"]` (or the
|
||||
absolute path of `bin/storebound` plus `mcp`).
|
||||
|
||||
### Desktop machine interface
|
||||
|
||||
`storebound serve --stdio` is what the desktop app (`apps/desktop`, in progress) runs as its sidecar: newline-delimited
|
||||
JSON-RPC on the same core as the MCP server (tool list, validation, forbidden flags, child-process runner), with typed
|
||||
methods (`check`, `validate`, `apple.status`, `play.listing`, ... plus `project.inspect` and `portfolio.status` over
|
||||
many project folders), structured results (the commands' `--json` output), progress notifications and cancellation.
|
||||
The first request is `session.hello` with a per-session secret only the host knows. Write methods are dry runs unless
|
||||
the call carries a single-use confirm token (HMAC over method, arguments and expiry) that the host mints after the
|
||||
owner confirmed a native dialog showing that dry run. There is no method that submits, releases or publishes; Play
|
||||
testing releases and phased release changes stay out of the desktop profile too. Types: `cli/lib/desktop-protocol.ts`.
|
||||
`bun tools/build-sidecars.ts` compiles the CLI for macOS, Linux and Windows (`bun build --compile`). Design, safety
|
||||
model and the Dependencies screen (tool sources and licenses): [docs/desktop.md](docs/desktop.md).
|
||||
|
||||
## Safety model
|
||||
|
||||
- **Credentials** live in env vars or the gitignored `.storebound/credentials.json`, never in the config or the repo.
|
||||
storebound only talks to the official store APIs (plus Google Fonts, your own Play reports bucket and your own URLs);
|
||||
see [SECURITY.md](SECURITY.md).
|
||||
- **Dry run everywhere.** Every write command takes `--dry`; every MCP write tool has `dry_run`, **default true**.
|
||||
Raw API writes (`storebound api`) are dry unless `--yes` is given in an interactive terminal; owner-only operations
|
||||
also need the operation id typed, and MCP only gets the read-only `api_get`.
|
||||
- **Nothing public or irreversible through an agent.** Submitting for review (App Review and Beta App Review),
|
||||
releasing a version, production releases, resuming or completing a rollout or phased release, canceling a
|
||||
submission, deleting, inviting or removing testers, sending review replies, applying prices and starting or
|
||||
stopping a product page test and creating custom offer codes are not MCP tools. Subscription syncs through MCP only
|
||||
create what is new; price changes of live subscriptions wait for a terminal run. They stay terminal commands that ask for confirmation, and the skills tell every agent to ask the owner
|
||||
first ([docs/agents-core.md](docs/agents-core.md)).
|
||||
- **Personal data stays local.** Tester lists, the App Review demo account, reply drafts, health reports and analytics
|
||||
snapshots live in the gitignored `.storebound/` (the demo account is masked in every log line); tester emails are masked in every log line, and the config refuses a tester CSV path
|
||||
outside `.storebound/`.
|
||||
- **Idempotent writes.** Re-running a command converges (MD5 checks for screenshots and previews, one Play edit per
|
||||
language), so a failed upload is fixed by running it again.
|
||||
- **Simulators and emulators**: storebound shuts down only a simulator it booted itself and never boots, wipes or
|
||||
reboots an Android emulator or device.
|
||||
|
||||
## FAQ
|
||||
|
||||
**Is it only for games?** No. It started with my game, but every command is about store records, not engines or
|
||||
genres. `init --profile app` and `--profile subscription-app` give you templates for a utility app with accounts and
|
||||
for a subscription app (Data safety, App Privacy, declarations, listing and screenshot copy), the `app` screenshot
|
||||
style, account deletion and demo account checks, and subscriptions on both stores. Game-only advice (IARC game
|
||||
questions, gameplay footage, ad mediation) is marked as such in the skills.
|
||||
|
||||
**Do I need Claude (or any AI tool)?** No. The CLI is a normal command and the skills are Markdown checklists you can
|
||||
read yourself. The AI integrations are optional adapters generated from the same files.
|
||||
|
||||
**Does it fill the questionnaires?** The ones with an API, yes: Play Data safety (the whole form from `dataSafety` in
|
||||
the config; the import replaces the form, so the config is the single truth), Apple age rating, content rights,
|
||||
categories, price and availability, the export compliance answer and the App Review details. The stores have no
|
||||
public API for Play's App content cards (IARC content rating, target audience, ads, advertising ID, app access,
|
||||
government / financial / health / news) or for Apple's App Privacy labels. For those, `init` gives you prepared
|
||||
answers (`store/declarations.md`, `store/app-privacy.md`, per profile: a utility app with an account, a subscription
|
||||
app, or a free-to-play game with ads and IAP),
|
||||
and the `store-declarations` skill has the exact clicks: an agent with browser tools can fill them in while you
|
||||
watch, or you copy them in yourself. Either way the answers are your statements to the stores: change what does not
|
||||
match your app, and the agent asks you whenever the code does not prove an answer. `validate` cannot see these
|
||||
forms, so `store-preflight` lists them as a manual check.
|
||||
|
||||
**My app or game is Unity / Godot / Flutter / React Native / native, not web.** Screenshots and clips come from the iOS Simulator
|
||||
(`ios-sim`), an Android emulator or device (`android-emu`) or a folder you fill with any tool; only the rendering of
|
||||
the store images uses a headless browser. The store commands do not care about the engine at all: they work on
|
||||
your AAB / build numbers and listing files.
|
||||
|
||||
**Is my store account safe?** storebound uses the official APIs with keys you create and can revoke, never your
|
||||
password. Store writes are dry runs until you say otherwise, and the public steps (submit, release) stay with you.
|
||||
Use an App Store Connect key with the App Manager role and a Play service account limited to your app.
|
||||
|
||||
**Why Bun?** One fast runtime with TypeScript, `fetch`, a test runner and a static server built in: no build step and
|
||||
zero runtime dependencies. It needs Bun installed (it does not run on plain Node).
|
||||
|
||||
**Does it upload my video to YouTube?** No. Play only takes a YouTube URL, and uploading to YouTube needs your Google
|
||||
account; `shots video` makes the file, you upload it and paste the URL into `play.video`.
|
||||
|
||||
**Can it run store experiments for me?** On the App Store, mostly: `apple ppo create / upload` builds a Product Page
|
||||
Optimization test from your `shots` variants (treatments, locales, screenshots) and you start it (`apple ppo start`
|
||||
asks first). Results per treatment are only shown in App Store Connect. Play store listing experiments have no API:
|
||||
storebound renders and checks the variant images, you set the experiment up in Play Console.
|
||||
|
||||
**Does it answer reviews by itself?** No. It drafts one file per review, your agent helps write the replies, and only
|
||||
the drafts you mark `approved: true` are sent, by you, after a confirmation. Replies that offer something for a rating
|
||||
are refused.
|
||||
|
||||
## Roadmap
|
||||
|
||||
Wave 2 (TestFlight, vitals, review replies, price sheets, analytics, MCP 2026-07-28, Product Page Optimization) shipped
|
||||
in 0.4.0. 0.5.0 made storebound app-first (profiles, app screenshot style, account deletion, review access) and
|
||||
brought the full in-app catalog: subscriptions on both stores with offers and offer codes, non-renewing products and
|
||||
the cross-store `catalog diff`. Next, roughly in this order:
|
||||
|
||||
- Play prepaid base plans for `non_renewing`, and a `prices export` that includes subscriptions.
|
||||
- The App Asset Library (API 4.5.1) for screenshots, custom product pages and in-app events once the screenshot sets
|
||||
it replaces stop working.
|
||||
- Play store listing experiments and their results, as soon as Google offers an API.
|
||||
- App preview treatments and alternate icons in Product Page Optimization tests.
|
||||
- The iPhone Duo screenshot classes Apple lists for apps built with the iOS 27.1 SDK (required from April 2027).
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and pull requests are welcome: store rule updates (with a source), new capture sources, adapters for more AI
|
||||
tools. See [CONTRIBUTING.md](CONTRIBUTING.md); `bun run ci` must be green.
|
||||
|
||||
<details>
|
||||
<summary><b>Agent support: formats and what is not verified</b></summary>
|
||||
|
||||
Checked against each tool's own docs in October 2026:
|
||||
|
||||
- **Agent Skills**: frontmatter is only `name` (lowercase-hyphen, equals the folder) and `description`; the generator
|
||||
fails if a skill adds anything else.
|
||||
- **Claude Code**: plugin manifest + root `.mcp.json` with `${CLAUDE_PLUGIN_ROOT}`; `claude plugin validate .` passes.
|
||||
- **Codex**: `.codex-plugin/plugin.json` with `"skills": "./skills/"`. Not verified: whether Codex starts the root
|
||||
`.mcp.json` from a plugin and expands `${CLAUDE_PLUGIN_ROOT}` there, so use `install --agent codex` for the MCP
|
||||
server. OpenAI also documents a newer portable root `plugin.json`; not shipped yet.
|
||||
- **Gemini CLI**: `gemini-extension.json` with `${extensionPath}${/}`, `GEMINI.md` as context, `skills/` inside the
|
||||
extension. Google now points unpaid users to Antigravity CLI; not tested there. The `.gemini/skills` folder used by
|
||||
`install --agent gemini` is not verified (the extension route is).
|
||||
- **Windsurf**: the current docs name `~/.config/devin/mcp_config.json`; `install` keeps using
|
||||
`~/.codeium/windsurf/mcp_config.json` when that file already exists (older installs).
|
||||
- **MCP**: built for 2026-07-28 (final, modelcontextprotocol.io) and dual-era: `initialize` clients get 2025-11-25
|
||||
(or 2025-06-18 / 2025-03-26 / 2024-11-05). Tested with both handshakes on one stdio process, not yet against every
|
||||
client listed above.
|
||||
- **Not verified against a live account yet** (no credentials during development; request builders are tested with
|
||||
fixtures from the official docs): the scale of the Play Reporting API rates (read as fractions, 0.0109 = 1.09 %),
|
||||
the App Store review reply limit (5970 characters is commonly reported; Apple documents none, storebound only
|
||||
warns), the TestFlight "What to Test" limit (4000 assumed), whether an analytics segment checksum covers the gzip
|
||||
file or its content (both are accepted), that a new App Store price schedule replaces the old one (Apple's example
|
||||
implies it), stopping a Product Page Optimization test with `started: false`, and `APP_IPHONE_61` for the 6.3"
|
||||
iPhone set. From 0.5.0 (request bodies follow Apple's and Google's published schemas, tested with fixtures, not
|
||||
yet run against a live account): free promotional offers and offer codes sent with territories but no price point,
|
||||
subscription prices and introductory offers created inline through `PATCH /v1/subscriptions/{id}`, Play
|
||||
pay-as-you-go offers as a `relativeDiscount`, Play "developer determined" offers as offers without targeting plus an
|
||||
offer tag, the ISO 8601 strings for Play billing periods (Google lists them only in words), the Play subscription
|
||||
benefit length (40, from Play Console), the Data safety sign-up method ids (`PSL_ACM_*`, Google publishes none:
|
||||
compare with a Console export) and the delete-account URL question id (use `dataSafety.extra`). From the store
|
||||
operations (built from the App Store Connect API 4.5.1 OpenAPI spec and the cited Help pages, tested with recorded
|
||||
answers, not yet run live): the first IAP of a type sent through `reviewSubmissionItems` next to the app version
|
||||
(`--no-submit` leaves the draft for the UI if Apple refuses it), free IAP offer code and win-back prices without a
|
||||
price point, the order request for promoted purchases, the Play earnings / sales zip names beyond the documented
|
||||
prefix (storebound lists the prefix), and where Xcode stores `AttributionCopyEndpoint` (top level or inside an
|
||||
`AdAttributionKit` dictionary: both are read).
|
||||
- **Apple IAP description**: 45 characters (App Store Connect Help, "In-app purchase information"); an older App Store
|
||||
marketing page says 55. storebound checks 45.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Develop</b></summary>
|
||||
|
||||
```sh
|
||||
bun install
|
||||
bun run ci # adapters fresh (gen-adapters --check), tests, typecheck, secrets / personal data scrub
|
||||
bun tools/gen-adapters.ts # after editing skills/*/SKILL.md or docs/agents-core.md
|
||||
```
|
||||
|
||||
`skills/*/SKILL.md` and `docs/agents-core.md` are the single source; `AGENTS.md`, `GEMINI.md`, the plugin manifests,
|
||||
`.github/copilot-instructions.md` and `.cursor/rules/storebound.mdc` are generated and committed, and CI fails when
|
||||
they are stale.
|
||||
|
||||
</details>
|
||||
|
||||
## Thanks and idea sources
|
||||
|
||||
Some skills were sparked by other people's open work. I wrote my own text; the ideas deserve the credit:
|
||||
|
||||
- [rorkai/app-store-connect-cli-skills](https://github.com/rorkai/app-store-connect-cli-skills) (MIT): App Store Connect
|
||||
workflow ideas.
|
||||
- [rshankras/claude-code-apple-skills](https://github.com/rshankras/claude-code-apple-skills) (MIT): Apple platform and
|
||||
App Store topic ideas.
|
||||
|
||||
Built with Bun and plain `fetch` against the Google Play Developer API v3, the Play Developer Reporting API and the App
|
||||
Store Connect API. Screenshot
|
||||
fonts come from Google Fonts at render time (Noto, Lilita One, Montserrat; SIL Open Font License 1.1). Not affiliated
|
||||
with Google or Apple.
|
||||
|
||||
## License
|
||||
|
||||
MIT, see [LICENSE](LICENSE). Copyright (c) 2026 CRTkafa.
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
<!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>
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@storebound/desktop",
|
||||
"version": "0.8.78",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -118,11 +118,7 @@
|
|||
if (t && t !== window && (t.src || t.href)) { record('load', 'could not load ' + (t.src || t.href)); return; }
|
||||
record('window.onerror', ev.error || ev.message, ev.error && ev.error.stack);
|
||||
}, true);
|
||||
// tauri-plugin-notification's init script asks for the notification permission at load (macOS, Linux); the webview
|
||||
// has no plugin API by design (capabilities/main.json), so that call is refused: expected, not an error
|
||||
function pluginProbe(e) { return /plugin:notification\|is_permission_granted not allowed/.test(text(e)); }
|
||||
window.addEventListener('unhandledrejection', function (ev) {
|
||||
if (pluginProbe(ev.reason)) { ev.preventDefault(); return; }
|
||||
if (!booted()) record('unhandledrejection', ev.reason, ev.reason && ev.reason.stack);
|
||||
});
|
||||
// React's root reports an error no boundary caught (the tree is gone) here: src/main.tsx onUncaughtError
|
||||
|
|
|
|||
119
apps/desktop/src-tauri/Cargo.lock
generated
|
|
@ -227,20 +227,6 @@ version = "1.1.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "auto-launch"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17918dba7ecf78b9a14507ec9f984e7977d13fad87dc86d61038980a45d128cf"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"os_info",
|
||||
"smappservice-rs",
|
||||
"thiserror 2.0.21",
|
||||
"windows-registry",
|
||||
"windows-result",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
|
|
@ -869,15 +855,6 @@ dependencies = [
|
|||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||
dependencies = [
|
||||
"dirs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "7.0.0"
|
||||
|
|
@ -2469,18 +2446,6 @@ dependencies = [
|
|||
"memoffset",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.31.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify-rust"
|
||||
version = "4.18.2"
|
||||
|
|
@ -2759,30 +2724,6 @@ dependencies = [
|
|||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-security"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-service-management"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b213642d6959cc6023ceb1217aa595eaaf09b8094ce95127c103cab611fe65e8"
|
||||
dependencies = [
|
||||
"block2",
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-security",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-ui-kit"
|
||||
version = "0.3.2"
|
||||
|
|
@ -2877,21 +2818,6 @@ dependencies = [
|
|||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "os_info"
|
||||
version = "3.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"log",
|
||||
"nix 0.31.3",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
"objc2-ui-kit",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "os_pipe"
|
||||
version = "1.2.3"
|
||||
|
|
@ -4000,18 +3926,6 @@ version = "1.16.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
|
||||
|
||||
[[package]]
|
||||
name = "smappservice-rs"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52703b97a53101cf5d4580e0737aaa634ce1fdcfc123c16b2a9658e358013488"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
"objc2-service-management",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
|
|
@ -4096,13 +4010,12 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
|||
|
||||
[[package]]
|
||||
name = "storebound-desktop"
|
||||
version = "0.8.78"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"keyring",
|
||||
"libc",
|
||||
"reqwest",
|
||||
"rusqlite",
|
||||
"rustls",
|
||||
|
|
@ -4111,7 +4024,6 @@ dependencies = [
|
|||
"sha2",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-autostart",
|
||||
"tauri-plugin-deep-link",
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-notification",
|
||||
|
|
@ -4124,9 +4036,6 @@ dependencies = [
|
|||
"tempfile",
|
||||
"tokio",
|
||||
"url",
|
||||
"webview2-com",
|
||||
"windows-core",
|
||||
"winreg",
|
||||
"zip",
|
||||
]
|
||||
|
||||
|
|
@ -4340,7 +4249,7 @@ dependencies = [
|
|||
"anyhow",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"dirs 7.0.0",
|
||||
"dirs",
|
||||
"dunce",
|
||||
"embed_plist",
|
||||
"getrandom 0.3.4",
|
||||
|
|
@ -4390,7 +4299,7 @@ checksum = "59563ca5b331fd97f27ee9672ec8d36d33bb3c9e2c9f6710a1a5687256052e45"
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
"dirs 7.0.0",
|
||||
"dirs",
|
||||
"glob",
|
||||
"heck 0.5.0",
|
||||
"json-patch",
|
||||
|
|
@ -4460,20 +4369,6 @@ dependencies = [
|
|||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-autostart"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bce56ceb0a99b8ab5eebc977ba9ffc62391b862648cb9ab76fc8bc7231b8f7e2"
|
||||
dependencies = [
|
||||
"auto-launch",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-deep-link"
|
||||
version = "2.6.1"
|
||||
|
|
@ -4636,7 +4531,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "855a336eb389d2c1502244fd48fa2d8cb487a430f691bbaed025195f99a04489"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 7.0.0",
|
||||
"dirs",
|
||||
"flate2",
|
||||
"futures-util",
|
||||
"http",
|
||||
|
|
@ -5122,7 +5017,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dirs 7.0.0",
|
||||
"dirs",
|
||||
"libappindicator",
|
||||
"muda",
|
||||
"objc2",
|
||||
|
|
@ -5945,7 +5840,7 @@ dependencies = [
|
|||
"block2",
|
||||
"cookie",
|
||||
"crossbeam-channel",
|
||||
"dirs 7.0.0",
|
||||
"dirs",
|
||||
"dom_query",
|
||||
"dpi",
|
||||
"dunce",
|
||||
|
|
@ -6059,7 +5954,7 @@ dependencies = [
|
|||
"futures-sink",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"nix 0.29.0",
|
||||
"nix",
|
||||
"ordered-stream",
|
||||
"rand 0.8.8",
|
||||
"serde",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "storebound-desktop"
|
||||
version = "0.8.78"
|
||||
version = "0.1.0"
|
||||
description = "storebound desktop: every game's releases on both stores in one window"
|
||||
license = "MIT"
|
||||
edition = "2021"
|
||||
|
|
@ -19,7 +19,7 @@ path = "src/main.rs"
|
|||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2.12", features = ["tray-icon"] }
|
||||
tauri = { version = "2.12", features = [] }
|
||||
# Spawns the storebound sidecar from Rust only; no capability grants the plugin's JS API.
|
||||
tauri-plugin-shell = "2"
|
||||
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
|
||||
|
|
@ -31,7 +31,6 @@ tauri-plugin-dialog = "2"
|
|||
tauri-plugin-notification = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-autostart = "2"
|
||||
# Store credentials: macOS Keychain, Windows Credential Manager, Secret Service on Linux.
|
||||
keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service", "crypto-rust"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
|
@ -49,13 +48,6 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
|||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
zip = { version = "4", default-features = false, features = ["deflate-flate2-zlib-rs"] }
|
||||
|
||||
# Release builds turn off WebView2's browser context menu and accelerator keys (Back, Refresh, Print, Save as).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
webview2-com = "0.39"
|
||||
windows-core = "0.62"
|
||||
# reads Startup apps' StartupApproved value (already in the tree through the autostart plugin)
|
||||
winreg = "0.56"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
|
|
@ -65,6 +57,3 @@ lto = true
|
|||
opt-level = "s"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ include!("src/commands_list.rs");
|
|||
fn main() {
|
||||
tauri_build::try_build(
|
||||
tauri_build::Attributes::new()
|
||||
.app_manifest(tauri_build::AppManifest::new().commands(Box::leak([COMMANDS, CARD_COMMANDS, MENU_COMMANDS].concat().into_boxed_slice()))),
|
||||
.app_manifest(tauri_build::AppManifest::new().commands(COMMANDS)),
|
||||
)
|
||||
.expect("tauri build script failed");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
{
|
||||
"$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"
|
||||
]
|
||||
}
|
||||
|
|
@ -35,7 +35,6 @@
|
|||
"allow-studio-remove",
|
||||
"allow-studio-logo",
|
||||
"allow-account-update",
|
||||
"allow-account-set-play-developer",
|
||||
"allow-account-check",
|
||||
"allow-store-apps-refresh",
|
||||
"allow-store-apps-cached",
|
||||
|
|
@ -44,21 +43,15 @@
|
|||
"allow-cache-info",
|
||||
"allow-data-reveal",
|
||||
"allow-notify",
|
||||
"allow-tray-update",
|
||||
"allow-card-snapshot",
|
||||
"allow-app-reset",
|
||||
"allow-update-check",
|
||||
"allow-update-install",
|
||||
"allow-project-import-fastlane",
|
||||
"allow-export-save",
|
||||
"allow-price-sheet-pick",
|
||||
"allow-image-pick",
|
||||
"allow-project-reveal",
|
||||
"allow-project-locate",
|
||||
"allow-state-reset",
|
||||
"allow-log-webview",
|
||||
"allow-ai-fix-info",
|
||||
"allow-ai-fix-run",
|
||||
"allow-ai-fix-undo"
|
||||
"allow-log-webview"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +0,0 @@
|
|||
{
|
||||
"$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"
|
||||
]
|
||||
}
|
||||
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 2 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 8.1 KiB After Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 4.6 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 158 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 228 KiB After Width: | Height: | Size: 119 KiB |
|
|
@ -1,11 +0,0 @@
|
|||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-account-set-play-developer"
|
||||
description = "Enables the account_set_play_developer command without any pre-configured scope."
|
||||
commands.allow = ["account_set_play_developer"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-account-set-play-developer"
|
||||
description = "Denies the account_set_play_developer command without any pre-configured scope."
|
||||
commands.deny = ["account_set_play_developer"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ai-fix-info"
|
||||
description = "Enables the ai_fix_info command without any pre-configured scope."
|
||||
commands.allow = ["ai_fix_info"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ai-fix-info"
|
||||
description = "Denies the ai_fix_info command without any pre-configured scope."
|
||||
commands.deny = ["ai_fix_info"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ai-fix-run"
|
||||
description = "Enables the ai_fix_run command without any pre-configured scope."
|
||||
commands.allow = ["ai_fix_run"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ai-fix-run"
|
||||
description = "Denies the ai_fix_run command without any pre-configured scope."
|
||||
commands.deny = ["ai_fix_run"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ai-fix-undo"
|
||||
description = "Enables the ai_fix_undo command without any pre-configured scope."
|
||||
commands.allow = ["ai_fix_undo"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ai-fix-undo"
|
||||
description = "Denies the ai_fix_undo command without any pre-configured scope."
|
||||
commands.deny = ["ai_fix_undo"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-image-pick"
|
||||
description = "Enables the image_pick command without any pre-configured scope."
|
||||
commands.allow = ["image_pick"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-image-pick"
|
||||
description = "Denies the image_pick command without any pre-configured scope."
|
||||
commands.deny = ["image_pick"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# 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"]
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-tray-update"
|
||||
description = "Enables the tray_update command without any pre-configured scope."
|
||||
commands.allow = ["tray_update"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-tray-update"
|
||||
description = "Denies the tray_update command without any pre-configured scope."
|
||||
commands.deny = ["tray_update"]
|
||||
|
|
@ -1,10 +1,8 @@
|
|||
//! Store accounts. The secret part (Play service account JSON, App Store Connect .p8 key with its key id and issuer)
|
||||
//! lives in the machine's credential profiles, shared with the CLI (profiles.rs: ~/.storebound/credentials, files
|
||||
//! 0600); the app data folder keeps the label, the kind, the studio and the profile name. Versions before 0.8 kept
|
||||
//! the secret in the OS keychain (service `dev.storebound.desktop`): `Keychain` is still here to move those entries
|
||||
//! into profiles once (profiles::sync). Secrets are never sent to the webview: they are read right before a sidecar
|
||||
//! call and handed to it in that call's params (memory only), which passes them to the command as environment
|
||||
//! variables.
|
||||
//! goes into the OS credential store under the service `dev.storebound.desktop`; only a label, the kind and the
|
||||
//! creation time are kept in the app data folder. Secrets are never sent to the webview: they are read from the
|
||||
//! keychain right before a sidecar call and handed to it in that call's params (memory only), which passes them to
|
||||
//! the storebound command as environment variables.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
|
|
@ -27,14 +25,6 @@ pub struct Account {
|
|||
/// The studio this account belongs to (workspace::Studio id), if any.
|
||||
#[serde(default)]
|
||||
pub studio: Option<String>,
|
||||
/// The credential profile that holds the key (~/.storebound/credentials/<profile>.json, shared with the CLI).
|
||||
/// None only for an account of an earlier version whose keychain entry has not moved yet.
|
||||
#[serde(default)]
|
||||
pub profile: Option<String>,
|
||||
/// Play only: the developer account id (PLAY_DEVELOPER_ID in its credential profile, shared with the CLI), for
|
||||
/// Play Console deep links. Read from the profile on every list; never a secret.
|
||||
#[serde(default, rename = "developerId", skip_serializing_if = "Option::is_none")]
|
||||
pub developer_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The keychain entry of one account (JSON).
|
||||
|
|
@ -62,13 +52,10 @@ impl Secret {
|
|||
Secret::Apple { key_id, issuer_id, p8 } => {
|
||||
into.insert("ASC_KEY_ID".into(), Value::String(key_id.clone()));
|
||||
into.insert("ASC_ISSUER_ID".into(), Value::String(issuer_id.clone()));
|
||||
// a profile without ASC_P8: the CLI finds ~/.appstoreconnect/private_keys/AuthKey_<id>.p8 itself
|
||||
if !p8.is_empty() {
|
||||
into.insert("ASC_P8".into(), Value::String(p8.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Google service account JSON key: client_email and a PEM private key.
|
||||
|
|
@ -123,7 +110,7 @@ pub fn check_label(s: &str) -> Result<String, String> {
|
|||
Ok(s.to_string())
|
||||
}
|
||||
|
||||
/// The OS keychain entries of earlier versions (read once to move them into profiles, then deleted); a map in tests.
|
||||
/// Where secrets live. The OS keychain in the app; a map in tests.
|
||||
pub trait SecretStore: Send + Sync {
|
||||
fn set(&self, id: &str, secret: &Secret) -> Result<(), String>;
|
||||
fn get(&self, id: &str) -> Result<Secret, String>;
|
||||
|
|
|
|||
|
|
@ -1,471 +0,0 @@
|
|||
//! "Fix with AI": one scan finding handed to the owner's local Claude Code CLI, run headless in the app folder.
|
||||
//!
|
||||
//! The host spawns exactly two programs here, never anything the webview names: the `claude` binary found on PATH
|
||||
//! (or its usual install folders) and `git`. claude runs with `-p` and only the file tools (Read, Edit, Write, Grep,
|
||||
//! Glob); Bash, the web tools, sub-agents and notebooks are disallowed, so it cannot run commands, reach the network
|
||||
//! or push. The prompt is built here from the finding's fields (the webview cannot pass free text). A run needs the app
|
||||
//! folder to be clean in git, so everything changed afterwards is the run's own work: the window shows that diff with
|
||||
//! Keep and Undo, and Undo restores exactly the files this run changed (recorded here, not sent by the webview).
|
||||
//! Every run has a 10 minute timeout with a heartbeat line every 15 s; a cancel or the app's exit kills the process
|
||||
//! group by PID.
|
||||
use std::collections::HashMap;
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{mpsc, Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// The only tools the agent gets.
|
||||
pub const ALLOWED_TOOLS: &str = "Read,Edit,Write,Grep,Glob";
|
||||
/// Tools it never gets (commands, network, sub-agents, notebooks), even if a settings file allows them.
|
||||
pub const DISALLOWED_TOOLS: &str = "Bash,WebFetch,WebSearch,Task,Agent,NotebookEdit,KillShell,BashOutput";
|
||||
pub const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
pub const HEARTBEAT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// The finding as the scan reports it (only these fields; lengths checked).
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct AiFinding {
|
||||
pub rule: String,
|
||||
pub guideline: String,
|
||||
pub store: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub evidence: Vec<Evidence>,
|
||||
pub fix: String,
|
||||
pub skill: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Evidence {
|
||||
pub file: String,
|
||||
pub line: u64,
|
||||
#[serde(default)]
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
fn short(s: &str, max: usize) -> String {
|
||||
let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
let t = one.trim();
|
||||
if t.chars().count() > max {
|
||||
format!("{}...", t.chars().take(max).collect::<String>())
|
||||
} else {
|
||||
t.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn ident(s: &str) -> bool {
|
||||
!s.is_empty() && s.len() <= 64 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
}
|
||||
|
||||
/// A path inside the app folder: relative, no `..`, no option-looking start.
|
||||
pub fn safe_rel(p: &str) -> bool {
|
||||
!p.is_empty()
|
||||
&& p.len() <= 1000
|
||||
&& !p.starts_with('-')
|
||||
&& !p.starts_with('/')
|
||||
&& !p.starts_with('\\')
|
||||
&& !p.contains(':')
|
||||
&& !p.chars().any(|c| c.is_control())
|
||||
&& !p.split(['/', '\\']).any(|seg| seg == "..")
|
||||
}
|
||||
|
||||
pub fn check_finding(f: &AiFinding) -> Result<(), String> {
|
||||
if !ident(&f.rule) || !ident(&f.skill) {
|
||||
return Err("bad rule or skill".into());
|
||||
}
|
||||
if f.store != "apple" && f.store != "play" {
|
||||
return Err("bad store".into());
|
||||
}
|
||||
if f.title.is_empty() || f.title.len() > 2000 || f.fix.len() > 4000 || f.guideline.len() > 200 || f.evidence.len() > 20 {
|
||||
return Err("finding too long".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The prompt for one finding. The same text is what "Copy for AI" copies.
|
||||
pub fn build_prompt(f: &AiFinding) -> Result<String, String> {
|
||||
check_finding(f)?;
|
||||
let store = if f.store == "apple" { "App Store" } else { "Google Play" };
|
||||
let mut ev = String::new();
|
||||
for e in f.evidence.iter().filter(|e| safe_rel(&e.file)).take(5) {
|
||||
ev.push_str(&format!("- {}:{}", e.file, e.line));
|
||||
if let Some(t) = e.text.as_deref().filter(|t| !t.trim().is_empty()) {
|
||||
ev.push_str(&format!(" ({})", short(t, 200)));
|
||||
}
|
||||
ev.push('\n');
|
||||
}
|
||||
if ev.is_empty() {
|
||||
ev.push_str("- (no file named: find where it lives first)\n");
|
||||
}
|
||||
Ok(format!(
|
||||
"Fix one {store} rejection risk that `storebound scan` found in this app folder.\n\n\
|
||||
Finding ({rule}, {guideline}): {title}\n\
|
||||
Evidence:\n{ev}\
|
||||
Suggested fix: {fix}\n\
|
||||
Background: the storebound skill \"{skill}\" covers this topic.\n\n\
|
||||
Rules:\n\
|
||||
- Change only what this finding needs, in as few files and lines as possible. No refactoring, reformatting or unrelated edits.\n\
|
||||
- Only read and edit files in this folder. Do not run commands, install packages, use the network, commit or push.\n\
|
||||
- Never invent an answer only the owner can give (export compliance, Data safety, App Privacy, age rating, a purpose the app does not have). If the fix needs one, change nothing and say what the owner must decide.\n\
|
||||
- Keep the project's style (indentation, quoting, file format).\n\
|
||||
- When done, say in one to three lines what you changed and why.\n",
|
||||
rule = f.rule,
|
||||
guideline = short(&f.guideline, 200),
|
||||
title = short(&f.title, 600),
|
||||
fix = short(&f.fix, 1500),
|
||||
skill = f.skill,
|
||||
))
|
||||
}
|
||||
|
||||
// ---- finding claude ----
|
||||
|
||||
/// Folders a GUI app's PATH usually lacks but a terminal install of Claude Code uses.
|
||||
fn extra_dirs(home: Option<&Path>) -> Vec<PathBuf> {
|
||||
let mut v = Vec::new();
|
||||
if let Some(h) = home {
|
||||
v.push(h.join(".claude/local"));
|
||||
v.push(h.join(".local/bin"));
|
||||
v.push(h.join(".npm-global/bin"));
|
||||
v.push(h.join(".bun/bin"));
|
||||
v.push(h.join(".volta/bin"));
|
||||
}
|
||||
v.push(PathBuf::from("/opt/homebrew/bin"));
|
||||
v.push(PathBuf::from("/usr/local/bin"));
|
||||
v
|
||||
}
|
||||
|
||||
/// The search PATH: the process PATH plus the usual install folders (node for an npm install lives there too).
|
||||
pub fn search_path(path_env: Option<&str>, home: Option<&Path>) -> Vec<PathBuf> {
|
||||
let mut v: Vec<PathBuf> = path_env.map(|p| std::env::split_paths(p).collect()).unwrap_or_default();
|
||||
for d in extra_dirs(home) {
|
||||
if !v.contains(&d) {
|
||||
v.push(d);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn find_claude_in(dirs: &[PathBuf]) -> Option<PathBuf> {
|
||||
let names: &[&str] = if cfg!(windows) { &["claude.exe", "claude.cmd"] } else { &["claude"] };
|
||||
dirs.iter().flat_map(|d| names.iter().map(move |n| d.join(n))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
fn home() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
|
||||
}
|
||||
|
||||
pub fn find_claude() -> Option<PathBuf> {
|
||||
find_claude_in(&search_path(std::env::var("PATH").ok().as_deref(), home().as_deref()))
|
||||
}
|
||||
|
||||
/// The arguments claude runs with (the prompt is the only variable part).
|
||||
pub fn claude_args(prompt: &str) -> Vec<String> {
|
||||
[
|
||||
"-p", prompt, "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits", "--allowedTools", ALLOWED_TOOLS,
|
||||
"--disallowedTools", DISALLOWED_TOOLS,
|
||||
]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The claude process for one prompt in the app folder: only a binary named claude, only `claude_args`.
|
||||
pub fn claude_command(claude: &Path, dir: &Path, prompt: &str) -> Result<Command, String> {
|
||||
let name = claude.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
if !matches!(name, "claude" | "claude.exe" | "claude.cmd") || !claude.is_absolute() {
|
||||
return Err("not the claude binary".into());
|
||||
}
|
||||
let mut cmd = Command::new(claude);
|
||||
cmd.current_dir(dir).args(claude_args(prompt));
|
||||
if let Ok(p) = std::env::join_paths(search_path(std::env::var("PATH").ok().as_deref(), home().as_deref())) {
|
||||
cmd.env("PATH", p);
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
// ---- git ----
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct Change {
|
||||
/// Path relative to the repository root.
|
||||
pub path: String,
|
||||
/// Porcelain status: "M", "D", "A" or "??" (new, untracked).
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> Result<String, String> {
|
||||
let out = Command::new("git").current_dir(dir).args(args).stdin(Stdio::null()).output().map_err(|e| format!("git: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("git {}: {}", args.first().unwrap_or(&""), String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).to_string())
|
||||
}
|
||||
|
||||
/// `git status --porcelain -z` of the app folder (renames reported as their new path).
|
||||
pub fn parse_status(z: &str) -> Vec<Change> {
|
||||
let mut v = Vec::new();
|
||||
let mut parts = z.split('\0').filter(|s| !s.is_empty());
|
||||
while let Some(e) = parts.next() {
|
||||
if e.len() < 4 {
|
||||
continue;
|
||||
}
|
||||
let (xy, path) = (&e[..2], &e[3..]);
|
||||
if xy.starts_with('R') || xy.starts_with('C') {
|
||||
parts.next(); // the old path
|
||||
}
|
||||
let status = if xy == "??" { "??".to_string() } else { xy.trim().chars().next().map(String::from).unwrap_or_default() };
|
||||
v.push(Change { path: path.to_string(), status });
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Repository root and the app folder's dirty files. Err when the folder is not in a git repository.
|
||||
pub fn status(dir: &Path) -> Result<(PathBuf, Vec<Change>), String> {
|
||||
let top = git(dir, &["rev-parse", "--show-toplevel"]).map_err(|_| "the app folder is not in a git repository: Undo needs git".to_string())?;
|
||||
let top = PathBuf::from(top.trim());
|
||||
let z = git(dir, &["status", "--porcelain", "-z", "--untracked-files=all", "--", "."])?;
|
||||
Ok((top, parse_status(&z)))
|
||||
}
|
||||
|
||||
/// What Undo does with the changes of one run: tracked files are checked out again, files the run created are removed.
|
||||
/// Only paths of that run, only relative ones inside the repository.
|
||||
pub fn undo_plan(run: &[Change]) -> (Vec<String>, Vec<String>) {
|
||||
let mut restore = Vec::new();
|
||||
let mut remove = Vec::new();
|
||||
for c in run.iter().filter(|c| safe_rel(&c.path)) {
|
||||
if c.status == "??" || c.status == "A" {
|
||||
remove.push(c.path.clone());
|
||||
} else {
|
||||
restore.push(c.path.clone());
|
||||
}
|
||||
}
|
||||
(restore, remove)
|
||||
}
|
||||
|
||||
pub fn undo(top: &Path, run: &[Change]) -> Result<Vec<String>, String> {
|
||||
let (restore, remove) = undo_plan(run);
|
||||
if !restore.is_empty() {
|
||||
let mut a: Vec<&str> = vec!["checkout", "HEAD", "--"];
|
||||
a.extend(restore.iter().map(String::as_str));
|
||||
git(top, &a)?;
|
||||
}
|
||||
for p in &remove {
|
||||
let abs = top.join(p);
|
||||
if abs.starts_with(top) && abs.is_file() {
|
||||
std::fs::remove_file(&abs).map_err(|e| format!("{p}: {e}"))?;
|
||||
}
|
||||
}
|
||||
Ok(restore.into_iter().chain(remove).collect())
|
||||
}
|
||||
|
||||
/// The diff of a run's changes (new files shown whole), at most 200 kB.
|
||||
pub fn diff(top: &Path, run: &[Change]) -> String {
|
||||
let tracked: Vec<&str> = run.iter().filter(|c| c.status != "??" && safe_rel(&c.path)).map(|c| c.path.as_str()).collect();
|
||||
let mut out = String::new();
|
||||
if !tracked.is_empty() {
|
||||
let mut a = vec!["diff", "--no-color", "HEAD", "--"];
|
||||
a.extend(tracked);
|
||||
out.push_str(&git(top, &a).unwrap_or_default());
|
||||
}
|
||||
for c in run.iter().filter(|c| c.status == "??" && safe_rel(&c.path)) {
|
||||
let text = std::fs::read_to_string(top.join(&c.path)).unwrap_or_default();
|
||||
out.push_str(&format!("--- /dev/null\n+++ b/{}\n{}\n", c.path, text.lines().map(|l| format!("+{l}")).collect::<Vec<_>>().join("\n")));
|
||||
}
|
||||
if out.len() > 200_000 {
|
||||
out.truncate(out.char_indices().take_while(|(i, _)| *i < 200_000).last().map(|(i, _)| i).unwrap_or(0));
|
||||
out.push_str("\n... (cut)");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---- running with a timeout, a heartbeat and kill by PID ----
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct Outcome {
|
||||
pub code: Option<i32>,
|
||||
pub timed_out: bool,
|
||||
pub cancelled: bool,
|
||||
/// The agent's final words (stream-json "result"), else the last output lines.
|
||||
pub summary: String,
|
||||
}
|
||||
|
||||
/// Running agents by job: PID and the cancel flag.
|
||||
type Running = Mutex<HashMap<String, (u32, Arc<AtomicBool>)>>;
|
||||
static RUNNING: OnceLock<Running> = OnceLock::new();
|
||||
fn running() -> &'static Running {
|
||||
RUNNING.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
/// Kills the whole process group (claude starts helpers) of a PID.
|
||||
pub fn kill_tree(pid: u32) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// the agent runs in its own process group (pgid = its pid); never signal any other group, least of all ours
|
||||
// (a CI run once died of SIGTERM in the middle of these tests)
|
||||
let pgid = pid as libc::pid_t;
|
||||
// SAFETY: getpgrp has no preconditions; killpg only sends a signal to the group named
|
||||
let own = unsafe { libc::getpgrp() };
|
||||
if pgid <= 1 || pgid == own {
|
||||
return;
|
||||
}
|
||||
unsafe { libc::killpg(pgid, libc::SIGTERM) };
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
unsafe { libc::killpg(pgid, libc::SIGKILL) };
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = Command::new("taskkill").args(["/T", "/F", "/PID", &pid.to_string()]).status();
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels the run of this job; true when one was running.
|
||||
pub fn cancel(job: &str) -> bool {
|
||||
let hit = running().lock().ok().and_then(|m| m.get(job).cloned());
|
||||
if let Some((pid, flag)) = hit {
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
kill_tree(pid);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// App exit: no agent outlives the window.
|
||||
pub fn kill_all() {
|
||||
let all: Vec<(u32, Arc<AtomicBool>)> = running().lock().map(|m| m.values().cloned().collect()).unwrap_or_default();
|
||||
for (pid, flag) in all {
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
kill_tree(pid);
|
||||
}
|
||||
}
|
||||
|
||||
/// One progress line of claude's stream-json output (None: nothing worth showing).
|
||||
pub fn progress_line(line: &str) -> Option<String> {
|
||||
let v: Value = serde_json::from_str(line).ok()?;
|
||||
match v["type"].as_str()? {
|
||||
"assistant" => {
|
||||
let mut out = Vec::new();
|
||||
for c in v["message"]["content"].as_array()? {
|
||||
match c["type"].as_str() {
|
||||
Some("text") => out.push(short(c["text"].as_str().unwrap_or_default().lines().next().unwrap_or_default(), 200)),
|
||||
Some("tool_use") => {
|
||||
let i = &c["input"];
|
||||
let what = i["file_path"].as_str().or(i["pattern"].as_str()).or(i["path"].as_str()).unwrap_or_default();
|
||||
out.push(short(&format!("{} {}", c["name"].as_str().unwrap_or("tool"), what), 200));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let s = out.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
(!s.is_empty()).then_some(s)
|
||||
}
|
||||
"result" => Some(short(v["result"].as_str().unwrap_or("done"), 400)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `cmd` in its own process group, calls `on_line` with each progress line (and a heartbeat while it is quiet),
|
||||
/// kills it on timeout or when `job` is cancelled.
|
||||
pub fn run(mut cmd: Command, job: &str, timeout: Duration, heartbeat: Duration, mut on_line: impl FnMut(&str)) -> Result<Outcome, String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd.spawn().map_err(|e| format!("could not start: {e}"))?;
|
||||
let pid = child.id();
|
||||
let flag = Arc::new(AtomicBool::new(false));
|
||||
if let Ok(mut m) = running().lock() {
|
||||
m.insert(job.to_string(), (pid, flag.clone()));
|
||||
}
|
||||
let (tx, rx) = mpsc::channel::<String>();
|
||||
let out = child.stdout.take();
|
||||
let tx2 = tx.clone();
|
||||
let reader = std::thread::spawn(move || {
|
||||
if let Some(o) = out {
|
||||
for l in BufReader::new(o).lines().map_while(Result::ok) {
|
||||
let _ = tx2.send(l);
|
||||
}
|
||||
}
|
||||
});
|
||||
let err = child.stderr.take();
|
||||
let err_reader = std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
if let Some(mut e) = err {
|
||||
let _ = e.read_to_string(&mut s);
|
||||
}
|
||||
s
|
||||
});
|
||||
drop(tx);
|
||||
let start = Instant::now();
|
||||
let mut last = Instant::now();
|
||||
let mut summary = String::new();
|
||||
let mut tail: Vec<String> = Vec::new();
|
||||
let mut timed_out = false;
|
||||
let code = loop {
|
||||
match rx.recv_timeout(Duration::from_millis(200)) {
|
||||
Ok(l) => {
|
||||
last = Instant::now();
|
||||
if let Some(p) = progress_line(&l) {
|
||||
if l.contains("\"type\":\"result\"") {
|
||||
summary = p.clone();
|
||||
}
|
||||
on_line(&p);
|
||||
} else if !l.trim_start().starts_with('{') && !l.trim().is_empty() {
|
||||
on_line(&short(&l, 300));
|
||||
tail.push(short(&l, 300));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) | Err(mpsc::RecvTimeoutError::Disconnected) => {}
|
||||
}
|
||||
if flag.load(Ordering::SeqCst) {
|
||||
kill_tree(pid);
|
||||
}
|
||||
if start.elapsed() > timeout && !timed_out {
|
||||
timed_out = true;
|
||||
on_line(&format!("timed out after {} s: stopping it", timeout.as_secs()));
|
||||
kill_tree(pid);
|
||||
let _ = child.kill();
|
||||
}
|
||||
if last.elapsed() >= heartbeat {
|
||||
last = Instant::now();
|
||||
on_line(&format!("still working ({} s)", start.elapsed().as_secs()));
|
||||
}
|
||||
if let Ok(Some(st)) = child.try_wait() {
|
||||
// drain what is left
|
||||
while let Ok(l) = rx.recv_timeout(Duration::from_millis(50)) {
|
||||
if let Some(p) = progress_line(&l) {
|
||||
if l.contains("\"type\":\"result\"") {
|
||||
summary = p.clone();
|
||||
}
|
||||
on_line(&p);
|
||||
}
|
||||
}
|
||||
break st.code();
|
||||
}
|
||||
};
|
||||
let _ = reader.join();
|
||||
let errs = err_reader.join().unwrap_or_default();
|
||||
if let Ok(mut m) = running().lock() {
|
||||
m.remove(job);
|
||||
}
|
||||
if summary.is_empty() {
|
||||
tail.extend(errs.lines().map(|l| short(l, 300)).filter(|l| !l.is_empty()));
|
||||
summary = tail.iter().rev().take(4).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
}
|
||||
Ok(Outcome { code, timed_out, cancelled: flag.load(Ordering::SeqCst), summary })
|
||||
}
|
||||
|
||||
// ---- runs recorded for Undo ----
|
||||
|
||||
/// Finished runs by id: repository root and the files the run changed (what Undo may restore).
|
||||
pub type Runs = Mutex<HashMap<String, (PathBuf, Vec<Change>)>>;
|
||||
static RUNS: OnceLock<Runs> = OnceLock::new();
|
||||
pub fn runs() -> &'static Runs {
|
||||
RUNS.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
|
@ -1,188 +0,0 @@
|
|||
//! 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};
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
//! App commands. Each one first checks the calling window and page (policy::require_main). Secrets never cross into
|
||||
//! the webview: account files are picked in native dialogs and read here, and credentials go from the machine's
|
||||
//! credential profiles (profiles.rs, shared with the CLI) straight into the sidecar call.
|
||||
//! the webview: account files are picked in native dialogs and read here, and credentials go from the keychain
|
||||
//! straight into the sidecar call.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
|
@ -12,9 +12,6 @@ use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
|||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
use crate::accounts::{self, Account, AccountKind, Secret, SecretStore};
|
||||
use crate::ai_fix;
|
||||
use crate::profiles::{self, ProfileStore};
|
||||
use crate::registry;
|
||||
use crate::cache::{Cache, Entry};
|
||||
use crate::downloads;
|
||||
use crate::policy::{self, Kind};
|
||||
|
|
@ -27,12 +24,7 @@ pub struct AppState {
|
|||
pub sidecar: Sidecar,
|
||||
pub data_dir: PathBuf,
|
||||
pub saved: Mutex<Saved>,
|
||||
/// The machine's credential profiles (~/.storebound/credentials, shared with the CLI): where keys live.
|
||||
pub profiles: ProfileStore,
|
||||
/// Keychain entries of versions before 0.8, moved into profiles once by `sync_machine`.
|
||||
pub legacy: Box<dyn SecretStore>,
|
||||
/// The machine's app folder list (~/.storebound/projects.json, shared with the CLI).
|
||||
pub registry: PathBuf,
|
||||
pub secrets: Box<dyn SecretStore>,
|
||||
pub cache: Cache,
|
||||
pub downloads: downloads::Jobs,
|
||||
}
|
||||
|
|
@ -44,16 +36,6 @@ fn guard(w: &WebviewWindow) -> Res<()> {
|
|||
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>> {
|
||||
s.saved.lock().map_err(|_| Fail::host("state poisoned"))
|
||||
}
|
||||
|
|
@ -62,51 +44,6 @@ fn persist(s: &AppState, st: &Saved) -> Res<()> {
|
|||
store::save(&s.data_dir, st).map_err(Fail::host)
|
||||
}
|
||||
|
||||
/// Brings the state in line with the machine's shared stores: accounts with the credential profiles (and moves old
|
||||
/// keychain entries into profiles), the folder list with the registry. Logged without values; saved when it changed.
|
||||
pub fn sync_machine(s: &AppState) -> Res<()> {
|
||||
let mut st = saved(s)?;
|
||||
let report = profiles::sync(&mut st.accounts, &s.profiles, s.legacy.as_ref(), &store::now_iso());
|
||||
for m in &report.migrated {
|
||||
crate::logs::host("info", &format!("account moved from the keychain into a credential profile: {m}"));
|
||||
}
|
||||
for a in &report.added {
|
||||
crate::logs::host("info", &format!("account from a credential profile: {a}"));
|
||||
}
|
||||
for n in &report.notes {
|
||||
crate::logs::host("warn", n);
|
||||
}
|
||||
let folders = match registry::sync(&mut st, &s.registry) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
crate::logs::host("warn", &format!("app folder list not synced: {e}"));
|
||||
false
|
||||
}
|
||||
};
|
||||
let ignored = registry::pull_ignored(&mut st, &s.registry);
|
||||
if report.changed() || folders || ignored {
|
||||
persist(s, &st)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After the app changed its folder list: the shared registry gets it (keeping folders another tool added).
|
||||
fn publish_folders(s: &AppState, st: &Saved, removed: &[String]) {
|
||||
if let Err(e) = registry::publish(st, &s.registry, removed) {
|
||||
crate::logs::host("warn", &format!("app folder list not written: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// One account's keys, read from its credential profile right now.
|
||||
fn secret_of(s: &AppState, id: &str) -> Result<Secret, String> {
|
||||
let (profile, kind) = {
|
||||
let st = s.saved.lock().map_err(|_| "state poisoned".to_string())?;
|
||||
let a = st.accounts.iter().find(|a| a.id == id).ok_or("unknown account")?;
|
||||
(a.profile.clone().ok_or("the account's key has not moved from the keychain yet: restart storebound, or add the key again")?, a.kind)
|
||||
};
|
||||
s.profiles.secret(&profile, kind)
|
||||
}
|
||||
|
||||
fn job_of(job: Option<String>) -> Res<Option<String>> {
|
||||
match job {
|
||||
Some(j) if !valid_job(&j) => Err(Fail::host("bad job id")),
|
||||
|
|
@ -119,8 +56,8 @@ fn project_params(s: &AppState, project_id: &str) -> Res<(Project, Map<String, V
|
|||
let p = saved(s)?.projects.iter().find(|p| p.id == project_id).cloned().ok_or_else(|| Fail::host("unknown project"))?;
|
||||
let mut creds = Map::new();
|
||||
for id in [&p.play_account, &p.apple_account].into_iter().flatten() {
|
||||
// A missing key is not fatal: the command says which credential it lacks.
|
||||
if let Ok(secret) = secret_of(s, id) {
|
||||
// A missing keychain entry is not fatal: the command says which credential it lacks.
|
||||
if let Ok(secret) = s.secrets.get(id) {
|
||||
secret.to_credentials(&mut creds);
|
||||
}
|
||||
}
|
||||
|
|
@ -144,7 +81,7 @@ fn target_params(s: &AppState, t: &StoreTarget) -> Res<Map<String, Value>> {
|
|||
drop(st);
|
||||
let mut creds = Map::new();
|
||||
for id in t.accounts() {
|
||||
if let Ok(secret) = secret_of(s, id) {
|
||||
if let Ok(secret) = s.secrets.get(id) {
|
||||
secret.to_credentials(&mut creds);
|
||||
}
|
||||
}
|
||||
|
|
@ -157,7 +94,7 @@ fn account_creds(s: &AppState, id: &str) -> Res<Map<String, Value>> {
|
|||
return Err(Fail::host("unknown account"));
|
||||
}
|
||||
let mut creds = Map::new();
|
||||
secret_of(s, id).map_err(Fail::host)?.to_credentials(&mut creds);
|
||||
s.secrets.get(id).map_err(Fail::host)?.to_credentials(&mut creds);
|
||||
Ok(creds)
|
||||
}
|
||||
|
||||
|
|
@ -205,8 +142,8 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
|
|||
if matches!(kind, Some(Kind::Read | Kind::Write | Kind::Owner)) {
|
||||
let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?;
|
||||
if id.starts_with("store:") {
|
||||
// a store-only app: store reads, and the few writes that send only what the call carries (dry runs here)
|
||||
if kind != Some(Kind::Read) && !policy::store_only_write(&method, kind) {
|
||||
// a store-only app: store reads only, through the sidecar's generated config
|
||||
if kind != Some(Kind::Read) {
|
||||
return Err(Fail::host("store-only apps are read-only: link a folder to change anything"));
|
||||
}
|
||||
let target = StoreTarget::parse(&id).map_err(Fail::host)?;
|
||||
|
|
@ -217,7 +154,7 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
|
|||
o.insert("credentials".into(), Value::Object(creds));
|
||||
}
|
||||
let res = r.call_job(&method, p, job.as_deref()).await?;
|
||||
if kind == Some(Kind::Read) && readable(&res) {
|
||||
if res["ok"] == Value::Bool(true) && !res["data"].is_null() {
|
||||
let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso());
|
||||
}
|
||||
return Ok(res);
|
||||
|
|
@ -235,19 +172,13 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
|
|||
let res = r.call_job(&method, p, job.as_deref()).await?;
|
||||
if let Some(id) = cache_project {
|
||||
// only results that read something: a failed store read must not hide the last good one
|
||||
if readable(&res) {
|
||||
if res["ok"] == Value::Bool(true) && !res["data"].is_null() {
|
||||
let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso());
|
||||
}
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// A result worth caching: it carries data and is ok, or "findings" (scan / check / validate / health exit 1 with their
|
||||
/// result printed: by design, not a failure). A failed read must not hide the last good one.
|
||||
fn readable(res: &Value) -> bool {
|
||||
!res["data"].is_null() && (res["ok"] == Value::Bool(true) || res["outcome"] == Value::String("findings".into()))
|
||||
}
|
||||
|
||||
/// The last cached result of a read (`project_id` "*" for the portfolio), with its time; null when never read.
|
||||
#[tauri::command]
|
||||
pub fn cache_get(window: WebviewWindow, state: State<'_, AppState>, method: String, project_id: String, args: Option<Value>) -> Res<Option<Entry>> {
|
||||
|
|
@ -268,7 +199,7 @@ pub async fn job_cancel(window: WebviewWindow, state: State<'_, AppState>, job:
|
|||
if !valid_job(&job) {
|
||||
return Err(Fail::host("bad job id"));
|
||||
}
|
||||
let mut hit = state.downloads.cancel(&job) | ai_fix::cancel(&job);
|
||||
let mut hit = state.downloads.cancel(&job);
|
||||
if let Some(r) = state.sidecar.current().await {
|
||||
hit |= r.cancel_job(&job) > 0;
|
||||
hit |= r.cancel_job(&format!("{job}:p")) > 0;
|
||||
|
|
@ -305,7 +236,7 @@ pub fn tilde(text: &str, home: Option<&str>) -> String {
|
|||
/// Human summary shown above the dry run in the confirm dialog.
|
||||
pub fn dialog_summary(title: &str, description: &str, project: &str, network: bool, destructive: bool) -> String {
|
||||
let mut s = format!("{title} · {project}\n\n{description}\n\n");
|
||||
s.push_str(if network { "This changes your store records (not public until you submit or release it)." } else { "This changes local files only." });
|
||||
s.push_str(if network { "This changes your store records (not public until you submit or release in the console)." } else { "This changes local files only." });
|
||||
if destructive {
|
||||
s.push_str("\nIt replaces what is there now.");
|
||||
}
|
||||
|
|
@ -317,21 +248,6 @@ pub fn owner_summary(title: &str, description: &str, project: &str) -> String {
|
|||
format!("{title} · {project}\n\n{description}\n\nThis is your decision: it changes what users get on the store right away. storebound does it only because you press the button below.")
|
||||
}
|
||||
|
||||
/// Summary of an owner action that sends the app to review or production (policy::SUBMIT_METHODS): what goes out and
|
||||
/// that it may go live by itself once approved.
|
||||
pub fn submit_summary(title: &str, description: &str, project: &str) -> String {
|
||||
format!("{title} · {project}\n\n{description}\n\nThis is your decision: it sends the app to the store's review. Once approved it can go live without another click (App Store: the version's release setting; Google Play: with managed publishing off). storebound does it only because you press the button below.")
|
||||
}
|
||||
|
||||
/// The dialog text above the dry run of one write or owner action.
|
||||
pub fn summary_for(method: &str, kind: Kind, title: &str, description: &str, project: &str, network: bool, destructive: bool) -> String {
|
||||
match kind {
|
||||
Kind::Owner if policy::SUBMIT_METHODS.contains(&method) => submit_summary(title, description, project),
|
||||
Kind::Owner => owner_summary(title, description, project),
|
||||
_ => dialog_summary(title, description, project, network, destructive),
|
||||
}
|
||||
}
|
||||
|
||||
/// Dialog title and the confirm button of a write: owner actions name the action on the button.
|
||||
pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) {
|
||||
if kind == Kind::Owner {
|
||||
|
|
@ -345,7 +261,7 @@ pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) {
|
|||
/// the uncertain ones marked for the owner, and the note that the owner reviews and saves in the browser.
|
||||
pub fn console_fill_dialog(project: &str, data: &Value) -> (String, String, String) {
|
||||
let title = data["title"].as_str().unwrap_or("Console form");
|
||||
let mut s = format!("{title} · {project}\n\nA browser window opens on the console page. It uses storebound's own browser profile: the first time, sign in there yourself (storebound never types passwords); the sign-in is kept for the next runs. Your own Chrome's cookies are never copied (Google ties them to your device and could sign you out). storebound opens the form, fills the fields below and marks the ones you answer.\n\n{}\n", policy::CONSOLE_FILL_NOTE);
|
||||
let mut s = format!("{title} · {project}\n\nA browser window opens on the console page. Sign in there yourself; storebound fills the fields below and marks the ones you answer.\n\n{}\n", policy::CONSOLE_FILL_NOTE);
|
||||
let answers = data["answers"].as_array().cloned().unwrap_or_default();
|
||||
let mut lines: Vec<String> = answers
|
||||
.iter()
|
||||
|
|
@ -412,9 +328,6 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
|
|||
Value::Object(o) => Value::Object(o),
|
||||
_ => return Err(Fail::host("args must be an object")),
|
||||
};
|
||||
if project_id.starts_with("store:") {
|
||||
return store_write_with_confirm(&window, &app, &state, &r, &method, kind, &d, &project_id, args, job.as_deref()).await;
|
||||
}
|
||||
let (proj, creds) = project_params(&state, &project_id)?;
|
||||
let mut dry_params = json!({ "project": proj.path, "args": args, "dryRun": true });
|
||||
if !creds.is_empty() {
|
||||
|
|
@ -427,7 +340,7 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
|
|||
let (title, text, ok) = if method == policy::CONSOLE_FILL {
|
||||
console_fill_dialog(&proj.name, &dry["data"])
|
||||
} else {
|
||||
let summary = summary_for(&method, kind, &d.title, &d.description, &proj.name, d.network, d.destructive);
|
||||
let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) };
|
||||
let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default()));
|
||||
let (title, ok) = dialog_labels(kind, &d.title);
|
||||
(title, text, ok)
|
||||
|
|
@ -446,42 +359,6 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
|
|||
Ok(json!({ "confirmed": true, "stage": "done", "dryRun": dry, "result": result }))
|
||||
}
|
||||
|
||||
/// `write_with_confirm` for a store-only app (no folder): only STORE_ONLY_WRITES, with the store ids (`virtual`) and the
|
||||
/// accounts of the store target; the dry run, the same native dialog, then a token bound to `{ virtual, args }`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn store_write_with_confirm(window: &WebviewWindow, app: &AppHandle, state: &State<'_, AppState>, r: &std::sync::Arc<crate::sidecar::Running>, method: &str, kind: Kind, d: &crate::sidecar::Descriptor, project_id: &str, args: Value, job: Option<&str>) -> Res<Value> {
|
||||
if !policy::store_only_write(method, Some(kind)) {
|
||||
return Err(Fail::host("store-only apps are read-only for this: link a folder to change it"));
|
||||
}
|
||||
let target = StoreTarget::parse(project_id).map_err(Fail::host)?;
|
||||
let creds = target_params(state, &target)?;
|
||||
let virt = target.virtual_project();
|
||||
let name = virt["name"].as_str().unwrap_or("store app").to_string();
|
||||
let mut dry_params = json!({ "virtual": virt, "args": args, "dryRun": true });
|
||||
if !creds.is_empty() {
|
||||
dry_params["credentials"] = Value::Object(creds.clone());
|
||||
}
|
||||
let dry = r.call_job(method, dry_params, job).await?;
|
||||
if dry["ok"] != Value::Bool(true) {
|
||||
return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry }));
|
||||
}
|
||||
let summary = summary_for(method, kind, &d.title, &d.description, &name, d.network, d.destructive);
|
||||
let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default()));
|
||||
let (title, ok) = dialog_labels(kind, &d.title);
|
||||
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
|
||||
if !confirm_dialog_with(window, title, tilde(&text, home.as_deref()), ok).await? {
|
||||
return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry }));
|
||||
}
|
||||
let bound = json!({ "virtual": virt, "args": args });
|
||||
let token = r.mint(method, &bound).map_err(Fail::host)?;
|
||||
let mut real = json!({ "virtual": virt, "args": args, "dryRun": false, "confirmToken": token });
|
||||
if !creds.is_empty() {
|
||||
real["credentials"] = Value::Object(creds);
|
||||
}
|
||||
let result = r.call_job(method, real, job).await?;
|
||||
Ok(json!({ "confirmed": true, "stage": "done", "dryRun": dry, "result": result }))
|
||||
}
|
||||
|
||||
/// An app folder as the window sees it: `missing` when the folder is gone (moved, renamed, deleted, or an old
|
||||
/// worktree), so the app shows "Folder not found" with Locate / Remove instead of reading it.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
|
|
@ -490,21 +367,15 @@ pub struct ProjectView {
|
|||
#[serde(flatten)]
|
||||
pub project: Project,
|
||||
pub missing: bool,
|
||||
/// The storebound version the folder's package.json pins when it is not this app's (its bundled CLI): the window
|
||||
/// says "project uses storebound X, app is Y".
|
||||
pub storebound_pin: Option<String>,
|
||||
}
|
||||
|
||||
pub fn project_view(p: &Project) -> ProjectView {
|
||||
let dir = Path::new(&p.path);
|
||||
ProjectView { project: p.clone(), missing: !dir.is_dir(), storebound_pin: workspace::pinned_storebound(dir).filter(|pin| workspace::pin_differs(pin, env!("CARGO_PKG_VERSION"))) }
|
||||
ProjectView { project: p.clone(), missing: !Path::new(&p.path).is_dir() }
|
||||
}
|
||||
|
||||
/// The app folders: the machine's shared list (registry.rs), with the app's accounts per folder.
|
||||
#[tauri::command]
|
||||
pub fn projects_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<ProjectView>> {
|
||||
guard(&window)?;
|
||||
sync_machine(&state)?;
|
||||
Ok(saved(&state)?.projects.iter().map(project_view).collect())
|
||||
}
|
||||
|
||||
|
|
@ -537,7 +408,6 @@ pub async fn project_locate(window: WebviewWindow, app: AppHandle, state: State<
|
|||
}
|
||||
let view = project_view(p);
|
||||
persist(&state, &st)?;
|
||||
publish_folders(&state, &st, &[]);
|
||||
crate::logs::host("info", &format!("app folder located: {}", view.project.path));
|
||||
Ok(Some(view))
|
||||
}
|
||||
|
|
@ -577,7 +447,6 @@ async fn add_folder(app: &AppHandle, state: &AppState, dir: &Path) -> Res<Projec
|
|||
let mut st = saved(state)?;
|
||||
st.projects.push(project.clone());
|
||||
persist(state, &st)?;
|
||||
publish_folders(state, &st, &[]);
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
|
|
@ -724,25 +593,6 @@ pub async fn price_sheet_pick(window: WebviewWindow, state: State<'_, AppState>,
|
|||
Ok(Some(p.to_string_lossy().to_string()))
|
||||
}
|
||||
|
||||
/// An image (PNG / JPEG) to replace one store image with, picked in a native dialog. None = cancelled. The path goes
|
||||
/// back to the window only as the `from` argument of art.replace (a write: dry run, dialog, then the copy into the app
|
||||
/// folder).
|
||||
#[tauri::command]
|
||||
pub async fn image_pick(window: WebviewWindow, state: State<'_, AppState>, project_id: String) -> Res<Option<String>> {
|
||||
guard(&window)?;
|
||||
let start = saved(&state)?.projects.iter().find(|p| p.id == project_id).map(|p| PathBuf::from(&p.path)).ok_or_else(|| Fail::host("unknown project"))?;
|
||||
let w = window.clone();
|
||||
let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title("Choose an image (PNG or JPEG)").add_filter("Image", &["png", "jpg", "jpeg"]).set_directory(start).set_parent(&w).blocking_pick_file())
|
||||
.await
|
||||
.map_err(|e| Fail::host(e.to_string()))?;
|
||||
let Some(picked) = picked else { return Ok(None) };
|
||||
let p = picked.into_path().map_err(|e| Fail::host(e.to_string()))?;
|
||||
if !p.extension().is_some_and(|e| ["png", "jpg", "jpeg"].iter().any(|x| e.eq_ignore_ascii_case(x))) {
|
||||
return Err(Fail::host("pick a .png or .jpg file"));
|
||||
}
|
||||
Ok(Some(p.to_string_lossy().to_string()))
|
||||
}
|
||||
|
||||
/// Shows a folder or file of an app folder in the file manager (`rel` empty: the app folder), or opens it with
|
||||
/// `open` (a folder, or the gallery page storebound writes: <renders>/index.html in the default browser).
|
||||
#[tauri::command]
|
||||
|
|
@ -774,16 +624,13 @@ pub fn project_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, Ap
|
|||
pub fn project_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> {
|
||||
guard(&window)?;
|
||||
let mut st = saved(&state)?;
|
||||
let removed: Vec<String> = st.projects.iter().filter(|p| p.id == id).map(|p| p.path.clone()).collect();
|
||||
st.projects.retain(|p| p.id != id);
|
||||
st.overrides.links.retain(|l| l.project != id);
|
||||
let (ig, key) = (format!("project:{id}"), format!("project:{id}"));
|
||||
st.overrides.ignored.retain(|i| i != &ig);
|
||||
st.overrides.app_studio.retain(|a| a.key != key);
|
||||
let _ = state.cache.forget_project(&id);
|
||||
persist(&state, &st)?;
|
||||
publish_folders(&state, &st, &removed);
|
||||
Ok(())
|
||||
persist(&state, &st)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
|
@ -812,12 +659,7 @@ pub fn project_set_accounts(window: WebviewWindow, state: State<'_, AppState>, i
|
|||
#[tauri::command]
|
||||
pub fn accounts_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<Account>> {
|
||||
guard(&window)?;
|
||||
sync_machine(&state)?;
|
||||
let mut out = saved(&state)?.accounts.clone();
|
||||
for a in out.iter_mut().filter(|a| a.kind == accounts::AccountKind::Play) {
|
||||
a.developer_id = a.profile.as_deref().and_then(|p| state.profiles.play_developer_id(p));
|
||||
}
|
||||
Ok(out)
|
||||
Ok(saved(&state)?.accounts.clone())
|
||||
}
|
||||
|
||||
fn check_studio(state: &AppState, studio: &Option<String>) -> Res<()> {
|
||||
|
|
@ -829,28 +671,17 @@ fn check_studio(state: &AppState, studio: &Option<String>) -> Res<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// A new key goes into the machine's credential profiles (the profile that already has this key, else one named after
|
||||
/// the label), so the CLI sees it too. The same key twice is one account.
|
||||
fn add_account(state: &AppState, label: &str, secret: Secret, studio: Option<String>) -> Res<Account> {
|
||||
let label = accounts::check_label(label).map_err(Fail::host)?;
|
||||
check_studio(state, &studio)?;
|
||||
let profile = state.profiles.place(&label, &secret);
|
||||
state.profiles.save(&profile, &label, &secret).map_err(Fail::host)?;
|
||||
let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso(), studio };
|
||||
state.secrets.set(&acc.id, &secret).map_err(Fail::host)?;
|
||||
let mut st = saved(state)?;
|
||||
if let Some(a) = st.accounts.iter_mut().find(|a| a.kind == secret.kind() && a.profile.as_deref() == Some(profile.as_str())) {
|
||||
a.label = label;
|
||||
if studio.is_some() {
|
||||
a.studio = studio;
|
||||
}
|
||||
let out = a.clone();
|
||||
persist(state, &st)?;
|
||||
return Ok(out);
|
||||
}
|
||||
let id = profiles::account_id(secret.kind(), &profile);
|
||||
let id = if st.accounts.iter().any(|a| a.id == id) { store::new_id()? } else { id };
|
||||
let acc = Account { id, label, kind: secret.kind(), created: store::now_iso(), studio, profile: Some(profile), developer_id: None };
|
||||
st.accounts.push(acc.clone());
|
||||
persist(state, &st)?;
|
||||
if let Err(e) = persist(state, &st) {
|
||||
let _ = state.secrets.delete(&acc.id);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
|
|
@ -868,7 +699,7 @@ async fn pick_file(window: &WebviewWindow, title: &'static str, filter: (&'stati
|
|||
std::fs::read_to_string(&path).map(Some).map_err(|e| Fail::host(e.to_string()))
|
||||
}
|
||||
|
||||
/// Google Play: pick the service account JSON key in a native dialog; it goes into a credential profile (0600).
|
||||
/// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only.
|
||||
#[tauri::command]
|
||||
pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String, studio: Option<String>) -> Res<Option<Account>> {
|
||||
guard(&window)?;
|
||||
|
|
@ -879,8 +710,7 @@ pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>,
|
|||
add_account(&state, &label, Secret::Play { service_account: sa }, studio).map(Some)
|
||||
}
|
||||
|
||||
/// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all into a credential
|
||||
/// profile (0600).
|
||||
/// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain.
|
||||
#[tauri::command]
|
||||
pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String, studio: Option<String>) -> Res<Option<Account>> {
|
||||
guard(&window)?;
|
||||
|
|
@ -896,18 +726,8 @@ pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>
|
|||
#[tauri::command]
|
||||
pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> {
|
||||
guard(&window)?;
|
||||
state.secrets.delete(&id).map_err(Fail::host)?;
|
||||
let mut st = saved(&state)?;
|
||||
let acc = st.accounts.iter().find(|a| a.id == id).cloned().ok_or_else(|| Fail::host("unknown account"))?;
|
||||
// the key leaves the shared profile (moved to credentials/.removed/, never deleted outright), or the keychain
|
||||
match &acc.profile {
|
||||
Some(p) => {
|
||||
if state.profiles.names().contains(p) && state.profiles.kinds(p).contains(&acc.kind) {
|
||||
let stamp = store::now_iso().replace(['-', ':'], "");
|
||||
state.profiles.remove(p, acc.kind, &stamp).map_err(Fail::host)?;
|
||||
}
|
||||
}
|
||||
None => state.legacy.delete(&id).map_err(Fail::host)?,
|
||||
}
|
||||
st.accounts.retain(|a| a.id != id);
|
||||
let ignored = format!("account:{id}");
|
||||
st.overrides.ignored.retain(|i| i != &ignored);
|
||||
|
|
@ -1134,7 +954,7 @@ pub async fn studio_logo(window: WebviewWindow, state: State<'_, AppState>, id:
|
|||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// Renames an account or moves it to another studio (the key in its credential profile stays as it is).
|
||||
/// Renames an account or moves it to another studio (the key in the keychain stays as it is).
|
||||
#[tauri::command]
|
||||
pub fn account_update(window: WebviewWindow, state: State<'_, AppState>, id: String, label: String, studio: Option<String>) -> Res<Account> {
|
||||
guard(&window)?;
|
||||
|
|
@ -1149,23 +969,6 @@ pub fn account_update(window: WebviewWindow, state: State<'_, AppState>, id: Str
|
|||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sets or clears the Play developer account id of a Play account (PLAY_DEVELOPER_ID in its credential profile, the
|
||||
/// same field `storebound accounts play-developer` writes): Play Console links then open each app's own page.
|
||||
#[tauri::command]
|
||||
pub fn account_set_play_developer(window: WebviewWindow, state: State<'_, AppState>, id: String, developer_id: Option<String>) -> Res<Account> {
|
||||
guard(&window)?;
|
||||
let st = saved(&state)?;
|
||||
let mut a = st.accounts.iter().find(|a| a.id == id).cloned().ok_or_else(|| Fail::host("unknown account"))?;
|
||||
if a.kind != accounts::AccountKind::Play {
|
||||
return Err(Fail::host("a Play account only"));
|
||||
}
|
||||
let profile = a.profile.clone().ok_or_else(|| Fail::host("this account has no credential profile yet"))?;
|
||||
let v = developer_id.as_deref().map(str::trim).filter(|v| !v.is_empty());
|
||||
state.profiles.set_play_developer_id(&profile, v).map_err(Fail::host)?;
|
||||
a.developer_id = state.profiles.play_developer_id(&profile);
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// Does the account's key work, and can it see apps (sidecar `account.check`). Not cached: it is a live answer.
|
||||
#[tauri::command]
|
||||
pub async fn account_check(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option<String>) -> Res<Value> {
|
||||
|
|
@ -1188,21 +991,9 @@ pub async fn store_apps_refresh(window: WebviewWindow, app: AppHandle, state: St
|
|||
let value = r.call_job("apps.list", json!({ "credentials": creds, "args": { "icons": icons } }), job.as_deref()).await?;
|
||||
let at = store::now_iso();
|
||||
state.cache.put(&format!("acct:{id}"), "apps.list", &json!({}), &value, &at).map_err(Fail::host)?;
|
||||
let st = saved(&state)?;
|
||||
let value = match st.accounts.iter().find(|a| a.id == id) {
|
||||
Some(a) => store_only_into(&st.accounts, a, Some(value.clone()), ®istry::read_store_apps(&state.registry), &at).unwrap_or(value),
|
||||
None => value,
|
||||
};
|
||||
Ok(Entry { value, at })
|
||||
}
|
||||
|
||||
/// One account's app list with the machine's store-only apps of its credential profile added (registry.rs).
|
||||
fn store_only_into(all: &[Account], a: &Account, list: Option<Value>, apps: &[registry::StoreOnly], at: &str) -> Option<Value> {
|
||||
let store = match a.kind { AccountKind::Apple => "apple", AccountKind::Play => "play" };
|
||||
let only = all.iter().filter(|x| x.kind == a.kind).count() == 1;
|
||||
registry::with_store_only(list, store, a.profile.as_deref(), only, apps, at)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct AccountApps {
|
||||
account: String,
|
||||
|
|
@ -1213,19 +1004,11 @@ pub struct AccountApps {
|
|||
#[tauri::command]
|
||||
pub fn store_apps_cached(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<AccountApps>> {
|
||||
guard(&window)?;
|
||||
let accounts = saved(&state)?.accounts.clone();
|
||||
let store_only = registry::read_store_apps(&state.registry);
|
||||
accounts
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let entry = state.cache.get(&format!("acct:{}", a.id), "apps.list", &json!({})).map_err(Fail::host)?;
|
||||
// apps live on a store with no project on this machine (`storebound apps add --store … --app-id …`)
|
||||
let at = entry.as_ref().map(|e| e.at.clone()).unwrap_or_else(store::now_iso);
|
||||
let entry = match store_only_into(&accounts, a, entry.as_ref().map(|e| e.value.clone()), &store_only, &at) {
|
||||
Some(value) => Some(Entry { value, at }),
|
||||
None => entry,
|
||||
};
|
||||
Ok(AccountApps { account: a.id.clone(), entry })
|
||||
let ids: Vec<String> = saved(&state)?.accounts.iter().map(|a| a.id.clone()).collect();
|
||||
ids.into_iter()
|
||||
.map(|account| {
|
||||
let entry = state.cache.get(&format!("acct:{account}"), "apps.list", &json!({})).map_err(Fail::host)?;
|
||||
Ok(AccountApps { account, entry })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -1238,10 +1021,6 @@ pub fn overrides_set(window: WebviewWindow, state: State<'_, AppState>, override
|
|||
let mut st = saved(&state)?;
|
||||
st.overrides = overrides.clone();
|
||||
persist(&state, &st)?;
|
||||
// apps the shared list knows carry their ignore flags there (the CLI's watch and portfolio reads honour them)
|
||||
if let Err(e) = registry::push_ignored(&st, &state.registry) {
|
||||
crate::logs::host("warn", &format!("ignored apps not written to the app list: {e}"));
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
|
||||
|
|
@ -1251,10 +1030,6 @@ pub fn settings_set(window: WebviewWindow, state: State<'_, AppState>, settings:
|
|||
guard(&window)?;
|
||||
workspace::check_settings(&settings).map_err(Fail::host)?;
|
||||
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();
|
||||
persist(&state, &st)?;
|
||||
drop(st);
|
||||
|
|
@ -1299,90 +1074,11 @@ pub fn data_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, AppSt
|
|||
/// A desktop notification (review state changed, a new 1-2 star review, a crash rate over the threshold). The window
|
||||
/// decides when, from Settings > Notifications; text is plain and short.
|
||||
#[tauri::command]
|
||||
pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String, target: Option<String>) -> Res<()> {
|
||||
pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String) -> Res<()> {
|
||||
guard(&window)?;
|
||||
use tauri_plugin_notification::NotificationExt;
|
||||
let cut = |s: &str, n: usize| s.chars().filter(|c| !c.is_control()).take(n).collect::<String>();
|
||||
app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string()))?;
|
||||
// desktop notifications have no click callback: remember where this one points; the window goes there when it is next shown
|
||||
if let Some(t) = target {
|
||||
crate::tray::set_pending(&t);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The window's summary for the tray (tooltip, attention flag, apps with their state, menu words) after a read.
|
||||
#[tauri::command]
|
||||
pub fn tray_update(window: WebviewWindow, app: AppHandle, summary: crate::tray::TraySummary) -> Res<()> {
|
||||
guard(&window)?;
|
||||
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(())
|
||||
app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string()))
|
||||
}
|
||||
|
||||
/// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders
|
||||
|
|
@ -1394,7 +1090,7 @@ pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res
|
|||
let yes = tauri::async_runtime::spawn_blocking(move || {
|
||||
w.app_handle()
|
||||
.dialog()
|
||||
.message("Forgets studios, labels, pairing, the ignore list, settings and saved store reads of this app.\n\nThe store accounts in ~/.storebound/credentials and the app folder list in ~/.storebound/projects.json stay: the storebound CLI uses them too (remove an account in Accounts first to remove its key). Downloaded tools stay. This cannot be undone.")
|
||||
.message("Removes every store key from the system keychain and forgets studios, accounts, app folders (the folders and their files stay), pairing, the ignore list, settings and saved store reads.\n\nDownloaded tools stay. This cannot be undone.")
|
||||
.title("Reset storebound desktop?")
|
||||
.kind(MessageDialogKind::Warning)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Reset".into(), "Cancel".into()))
|
||||
|
|
@ -1407,15 +1103,13 @@ pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res
|
|||
return Ok(false);
|
||||
}
|
||||
let mut st = saved(&state)?;
|
||||
// keys of earlier versions still in the keychain go; the shared credential profiles stay (the CLI uses them)
|
||||
for a in st.accounts.iter().filter(|a| a.profile.is_none()) {
|
||||
state.legacy.delete(&a.id).map_err(Fail::host)?;
|
||||
for a in &st.accounts {
|
||||
state.secrets.delete(&a.id).map_err(Fail::host)?;
|
||||
}
|
||||
*st = Saved::default();
|
||||
persist(&state, &st)?;
|
||||
drop(st);
|
||||
state.cache.clear().map_err(Fail::host)?;
|
||||
sync_machine(&state)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
|
|
@ -1429,7 +1123,7 @@ pub async fn state_reset(window: WebviewWindow, app: AppHandle, state: State<'_,
|
|||
let yes = tauri::async_runtime::spawn_blocking(move || {
|
||||
w.app_handle()
|
||||
.dialog()
|
||||
.message("storebound forgets its studios, pairing and settings, and starts again from the machine's accounts and app folders.\n\nNothing is deleted: the saved state is kept as a backup file in the app data folder, store keys stay in ~/.storebound/credentials, and your app folders are not touched.")
|
||||
.message("storebound forgets its list of app folders, accounts, studios, pairing and settings, and starts empty.\n\nNothing is deleted: the saved state is kept as a backup file in the app data folder, store keys stay in the system keychain, and your app folders are not touched.")
|
||||
.title("Reset saved state?")
|
||||
.kind(MessageDialogKind::Warning)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Reset and keep a backup".into(), "Cancel".into()))
|
||||
|
|
@ -1493,7 +1187,7 @@ pub struct UpdateInfo {
|
|||
pub date: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plugin_updater::Update>> {
|
||||
async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plugin_updater::Update>> {
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
let url = url::Url::parse(updates::endpoint(channel)).map_err(|e| Fail::host(e.to_string()))?;
|
||||
if !updates::endpoint_allowed(&url) {
|
||||
|
|
@ -1504,8 +1198,6 @@ pub async fn find_update(app: &AppHandle, channel: &str) -> Res<Option<tauri_plu
|
|||
.endpoints(vec![url])
|
||||
.map_err(|e| Fail::host(e.to_string()))?
|
||||
.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(¤t.to_string(), &remote.version.to_string()))
|
||||
.build()
|
||||
.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())))
|
||||
|
|
@ -1595,8 +1287,6 @@ async fn open_folder(app: &AppHandle, dir: &Path) -> Res<()> {
|
|||
)));
|
||||
}
|
||||
let path = dir.to_string_lossy().to_string();
|
||||
// `storebound desktop` put the folder on the machine's list first: then it is selected without a question
|
||||
sync_machine(&state)?;
|
||||
let known = saved(&state)?.projects.iter().find(|p| p.path == path).map(|p| p.id.clone());
|
||||
let id = match known {
|
||||
Some(id) => id,
|
||||
|
|
@ -1611,142 +1301,3 @@ async fn open_folder(app: &AppHandle, dir: &Path) -> Res<()> {
|
|||
let _ = app.emit_to(policy::MAIN, "deep-link-folder", id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Fix with AI (src/ai_fix.rs): the owner's local Claude Code CLI on one scan finding ----
|
||||
|
||||
fn project_dir(state: &AppState, project_id: &str) -> Res<PathBuf> {
|
||||
let p = saved(state)?.projects.iter().find(|p| p.id == project_id).cloned().ok_or_else(|| Fail::host("unknown project"))?;
|
||||
Ok(PathBuf::from(p.path))
|
||||
}
|
||||
|
||||
/// Whether claude is installed, the prompt (also what "Copy for AI" copies) and what is dirty in git.
|
||||
#[tauri::command]
|
||||
pub async fn ai_fix_info(window: WebviewWindow, state: State<'_, AppState>, project_id: String, finding: ai_fix::AiFinding) -> Res<Value> {
|
||||
guard(&window)?;
|
||||
let prompt = ai_fix::build_prompt(&finding).map_err(Fail::host)?;
|
||||
let dir = project_dir(&state, &project_id)?;
|
||||
let claude = ai_fix::find_claude();
|
||||
let (git, dirty) = match tauri::async_runtime::spawn_blocking(move || ai_fix::status(&dir)).await.map_err(|e| Fail::host(e.to_string()))? {
|
||||
Ok((_, d)) => (Ok(()), d),
|
||||
Err(e) => (Err(e), Vec::new()),
|
||||
};
|
||||
Ok(json!({ "claude": claude.is_some(), "prompt": prompt, "git": git.is_ok(), "gitError": git.err(), "dirty": dirty }))
|
||||
}
|
||||
|
||||
/// Runs claude on one finding in the app folder (clean git tree only), streams "ai-fix" lines, returns the run's changes.
|
||||
#[tauri::command]
|
||||
pub async fn ai_fix_run(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, project_id: String, finding: ai_fix::AiFinding, job: String) -> Res<Value> {
|
||||
guard(&window)?;
|
||||
if !valid_job(&job) {
|
||||
return Err(Fail::host("bad job id"));
|
||||
}
|
||||
let prompt = ai_fix::build_prompt(&finding).map_err(Fail::host)?;
|
||||
let dir = project_dir(&state, &project_id)?;
|
||||
let claude = ai_fix::find_claude().ok_or_else(|| Fail::host("Claude Code (claude) was not found on PATH"))?;
|
||||
let handle = app.clone();
|
||||
let res = tauri::async_runtime::spawn_blocking(move || -> Result<Value, String> {
|
||||
let (top, dirty) = ai_fix::status(&dir)?;
|
||||
if !dirty.is_empty() {
|
||||
return Ok(json!({ "refused": "dirty", "dirty": dirty }));
|
||||
}
|
||||
let cmd = ai_fix::claude_command(&claude, &dir, &prompt)?;
|
||||
let emit_job = job.clone();
|
||||
let out = ai_fix::run(cmd, &job, ai_fix::TIMEOUT, ai_fix::HEARTBEAT, |line| {
|
||||
let _ = handle.emit_to(policy::MAIN, "ai-fix", json!({ "job": emit_job, "line": line }));
|
||||
})?;
|
||||
let (_, changes) = ai_fix::status(&dir)?;
|
||||
let diff = ai_fix::diff(&top, &changes);
|
||||
let run_id = job.clone();
|
||||
if let Ok(mut m) = ai_fix::runs().lock() {
|
||||
m.insert(run_id.clone(), (top, changes.clone()));
|
||||
}
|
||||
Ok(json!({ "runId": run_id, "outcome": out, "changes": changes, "diff": diff }))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| Fail::host(e.to_string()))?;
|
||||
res.map_err(Fail::host)
|
||||
}
|
||||
|
||||
/// Undo of one run: restores exactly the files that run changed (recorded by the host) and removes the ones it created.
|
||||
#[tauri::command]
|
||||
pub async fn ai_fix_undo(window: WebviewWindow, run_id: String) -> Res<Vec<String>> {
|
||||
guard(&window)?;
|
||||
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)
|
||||
}
|
||||
|
||||
// ---- 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(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,6 @@ pub const COMMANDS: &[&str] = &[
|
|||
"studio_remove",
|
||||
"studio_logo",
|
||||
"account_update",
|
||||
"account_set_play_developer",
|
||||
"account_check",
|
||||
"store_apps_refresh",
|
||||
"store_apps_cached",
|
||||
|
|
@ -36,26 +35,14 @@ pub const COMMANDS: &[&str] = &[
|
|||
"cache_info",
|
||||
"data_reveal",
|
||||
"notify",
|
||||
"tray_update",
|
||||
"card_snapshot",
|
||||
"app_reset",
|
||||
"update_check",
|
||||
"update_install",
|
||||
"project_import_fastlane",
|
||||
"export_save",
|
||||
"price_sheet_pick",
|
||||
"image_pick",
|
||||
"project_reveal",
|
||||
"project_locate",
|
||||
"state_reset",
|
||||
"log_webview",
|
||||
"ai_fix_info",
|
||||
"ai_fix_run",
|
||||
"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"];
|
||||
|
|
|
|||
|
|
@ -1,22 +1,16 @@
|
|||
//! storebound desktop: a Tauri shell around the storebound CLI, which runs as a sidecar (`storebound serve --stdio`).
|
||||
//! The GUI never talks to a store itself; every store call is a storebound command.
|
||||
pub mod accounts;
|
||||
pub mod ai_fix;
|
||||
pub mod cache;
|
||||
pub mod card;
|
||||
pub mod commands;
|
||||
pub mod confirm;
|
||||
pub mod downloads;
|
||||
pub mod logs;
|
||||
pub mod menu_panel;
|
||||
pub mod policy;
|
||||
pub mod profiles;
|
||||
pub mod registry;
|
||||
pub mod selftest;
|
||||
pub mod updates;
|
||||
pub mod sidecar;
|
||||
pub mod store;
|
||||
pub mod tray;
|
||||
pub mod workspace;
|
||||
|
||||
include!("commands_list.rs");
|
||||
|
|
@ -24,9 +18,7 @@ include!("commands_list.rs");
|
|||
use std::sync::Mutex;
|
||||
|
||||
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu, WINDOW_SUBMENU_ID};
|
||||
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
|
||||
use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime, WindowEvent};
|
||||
use tauri_plugin_autostart::{MacosLauncher, ManagerExt};
|
||||
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
|
||||
|
|
@ -39,178 +31,11 @@ pub fn linux_webkit_env() {
|
|||
}
|
||||
}
|
||||
|
||||
/// Started by the logon entry (`--hidden`): the app runs in the tray and shows no window.
|
||||
fn started_hidden() -> bool {
|
||||
std::env::args().any(|a| a == "--hidden")
|
||||
}
|
||||
|
||||
/// Tray icon: a left click shows the tray card (card.rs), a right click the app's own menu panels (menu_panel.rs, with
|
||||
/// the tree from tray.rs: open the window, read the stores, the apps with their state, mute, updates, Settings and Quit,
|
||||
/// the only real quit on Windows and Linux, where closing the window keeps the app running in the tray). The window
|
||||
/// 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<()> {
|
||||
let handle = app.handle();
|
||||
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() {
|
||||
b = b.icon(icon.clone());
|
||||
}
|
||||
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::Quit) => app.exit(0),
|
||||
Some(tray::Action::Event(word)) => {
|
||||
let _ = app.emit_to(policy::MAIN, "tray-action", word);
|
||||
}
|
||||
Some(tray::Action::Route(route)) => {
|
||||
show_main(app);
|
||||
let _ = app.emit_to(policy::MAIN, "tray-route", route);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
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 {
|
||||
let now_wall = SystemTime::now();
|
||||
let gap = now_wall.duration_since(last_wall).map(|d| d.as_secs()).unwrap_or(0);
|
||||
last_wall = now_wall;
|
||||
let kicked = updates::take_kick();
|
||||
if updates::check_due(first, kicked, gap, last_check.elapsed().as_secs()) {
|
||||
let why = if first { "start" } else if kicked { "channel switched" } else if gap > updates::TICK_SECS + 60 { "resume" } else { "every 15 min" };
|
||||
first = false;
|
||||
last_check = Instant::now();
|
||||
defers = auto_update_once(&app, why, defers).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(updates::TICK_SECS)).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>) {
|
||||
if let Some(w) = app.get_webview_window(policy::MAIN) {
|
||||
let _ = w.unminimize();
|
||||
let _ = w.show();
|
||||
let _ = w.set_focus();
|
||||
// the last notification's target (the plugin has no click callback on desktop): the window goes there now
|
||||
if let Some(route) = tray::take_pending() {
|
||||
let _ = app.emit_to(policy::MAIN, "tray-route", route);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -301,34 +126,13 @@ fn dev_seed(data_dir: &std::path::Path) {
|
|||
}
|
||||
}
|
||||
|
||||
/// One line before Tauri starts: a start at logon that dies early (before the host log exists) still leaves a trace
|
||||
/// with its arguments and working folder (a logon start once left no line at all). Best effort, never fails.
|
||||
fn early_trace() {
|
||||
use std::io::Write;
|
||||
let base = std::env::var_os("APPDATA").or_else(|| std::env::var_os("XDG_DATA_HOME")).map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".local/share")));
|
||||
let Some(base) = base else { return };
|
||||
let dir = base.join("dev.storebound.desktop").join("logs");
|
||||
if std::fs::create_dir_all(&dir).is_err() { return }
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let cwd = std::env::current_dir().map(|d| d.display().to_string()).unwrap_or_default();
|
||||
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("start.log")) {
|
||||
let _ = writeln!(f, "{secs} start {} args={args:?} cwd={cwd} pid={}", env!("CARGO_PKG_VERSION"), std::process::id());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() {
|
||||
early_trace();
|
||||
linux_webkit_env();
|
||||
let app = tauri::Builder::default()
|
||||
// single-instance first: a second start (or a storebound:// link) focuses the running app instead; a second
|
||||
// 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) }))
|
||||
// single-instance first: a second start (or a storebound:// link) focuses the running app instead
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| show_main(app)))
|
||||
.plugin(tauri_plugin_deep_link::init())
|
||||
// never restore "visible": a --hidden start would otherwise pop the window up
|
||||
.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_window_state::Builder::new().build())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
|
|
@ -336,10 +140,6 @@ pub fn run() {
|
|||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.setup(|app| {
|
||||
#[cfg(all(windows, not(debug_assertions)))]
|
||||
if let Some(w) = app.get_webview_window(policy::MAIN) {
|
||||
harden_webview(&w);
|
||||
}
|
||||
let data_dir = app.path().app_data_dir()?;
|
||||
logs::init(&data_dir, app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()));
|
||||
logs::panic_hook();
|
||||
|
|
@ -347,7 +147,6 @@ pub fn run() {
|
|||
dev_seed(&data_dir);
|
||||
let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?;
|
||||
let (saved, report) = store::load_report(&data_dir);
|
||||
let home = app.path().home_dir().ok();
|
||||
logs::host("info", &format!("saved state: {} app folders ({} not found), {} accounts, {} studios, format {}", saved.projects.len(), saved.projects.iter().filter(|p| !std::path::Path::new(&p.path).is_dir()).count(), saved.accounts.len(), saved.studios.len(), saved.version));
|
||||
if let Some(from) = report.migrated_from {
|
||||
logs::host("info", &format!("saved state migrated from format {from} to {}", store::VERSION));
|
||||
|
|
@ -363,41 +162,13 @@ pub fn run() {
|
|||
sidecar: sidecar::Sidecar::default(),
|
||||
saved: Mutex::new(saved),
|
||||
data_dir,
|
||||
profiles: profiles::ProfileStore::new(profiles::default_dir(home.as_deref()), home.clone()),
|
||||
legacy: Box::new(accounts::Keychain),
|
||||
registry: registry::default_file(home.as_deref()),
|
||||
secrets: Box::new(accounts::Keychain),
|
||||
cache,
|
||||
downloads: downloads::Jobs::default(),
|
||||
};
|
||||
// Settings > Offline cache: drop saved reads older than the chosen number of days
|
||||
commands::prune_cache(&state, keep_days);
|
||||
// the machine's shared accounts and app folders (CLI and app); old keychain accounts move into profiles once
|
||||
if let Err(e) = commands::sync_machine(&state) {
|
||||
logs::host("warn", &format!("accounts / app folders not synced at start: {}", e.message));
|
||||
}
|
||||
// start at logon, in the tray: rewritten on every start (Windows: the HKCU Run entry then points at the
|
||||
// running exe, so a moved or updated install fixes itself)
|
||||
// ...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() {
|
||||
Ok(()) => logs::host("info", "autostart at logon set (--hidden, tray)"),
|
||||
Err(e) => logs::host("warn", &format!("autostart not set: {e}")),
|
||||
}
|
||||
}
|
||||
app.manage(state);
|
||||
app.manage(menu_panel::MenuPanels::default());
|
||||
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() {
|
||||
show_main(app.handle());
|
||||
}
|
||||
auto_update(app.handle().clone());
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_menu(menu(app.handle())?)?;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
|
|
@ -407,12 +178,8 @@ pub fn run() {
|
|||
show_main(app);
|
||||
}
|
||||
});
|
||||
// Linux: registering runs update-desktop-database and xdg-mime, which a minimal system may not have; a
|
||||
// missing tool must not stop the app (it then only misses storebound:// links)
|
||||
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
|
||||
if let Err(e) = app.deep_link().register_all() {
|
||||
logs::host("warn", &format!("storebound:// links not registered: {e}"));
|
||||
}
|
||||
app.deep_link().register_all()?;
|
||||
let handle = app.handle().clone();
|
||||
app.deep_link().on_open_url(move |e| handle_deep_link(&handle, &e.urls()));
|
||||
if let Ok(Some(urls)) = app.deep_link().get_current() {
|
||||
|
|
@ -421,16 +188,9 @@ pub fn run() {
|
|||
Ok(())
|
||||
})
|
||||
.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
|
||||
// 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 {
|
||||
// macOS: the close button hides the window (the app stays in the Dock and the Window menu);
|
||||
// Cmd+Q and the app menu's Quit still quit. Elsewhere closing the window quits.
|
||||
if cfg!(target_os = "macos") && w.label() == policy::MAIN {
|
||||
if let WindowEvent::CloseRequested { api, .. } = e {
|
||||
api.prevent_close();
|
||||
let _ = w.hide();
|
||||
|
|
@ -464,7 +224,6 @@ pub fn run() {
|
|||
commands::studio_remove,
|
||||
commands::studio_logo,
|
||||
commands::account_update,
|
||||
commands::account_set_play_developer,
|
||||
commands::account_check,
|
||||
commands::store_apps_refresh,
|
||||
commands::store_apps_cached,
|
||||
|
|
@ -473,33 +232,16 @@ pub fn run() {
|
|||
commands::cache_info,
|
||||
commands::data_reveal,
|
||||
commands::notify,
|
||||
commands::tray_update,
|
||||
commands::card_snapshot,
|
||||
commands::app_reset,
|
||||
commands::update_check,
|
||||
commands::update_install,
|
||||
commands::project_import_fastlane,
|
||||
commands::export_save,
|
||||
commands::price_sheet_pick,
|
||||
commands::image_pick,
|
||||
commands::project_reveal,
|
||||
commands::project_locate,
|
||||
commands::state_reset,
|
||||
commands::log_webview,
|
||||
commands::ai_fix_info,
|
||||
commands::ai_fix_run,
|
||||
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!())
|
||||
.expect("storebound desktop failed to start");
|
||||
|
|
@ -507,33 +249,11 @@ pub fn run() {
|
|||
app.run(|app, e| match e {
|
||||
#[cfg(target_os = "macos")]
|
||||
RunEvent::Reopen { .. } => show_main(app),
|
||||
// no window left is not a reason to quit (tray app); an explicit exit or the updater's restart carries a code
|
||||
RunEvent::ExitRequested { code: None, api, .. } => api.prevent_exit(),
|
||||
RunEvent::Exit => {
|
||||
if let Some(s) = app.try_state::<commands::AppState>() {
|
||||
s.sidecar.shutdown_now();
|
||||
}
|
||||
ai_fix::kill_all();
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Release builds on Windows: no WebView2 browser context menu (Back, Refresh, Save as, Print, More tools) and no
|
||||
/// browser accelerator keys (Ctrl+R, Ctrl+P, F5, Ctrl+Shift+I...). The page draws its own menus; dev keeps devtools.
|
||||
#[cfg(all(windows, not(debug_assertions)))]
|
||||
fn harden_webview(w: &tauri::WebviewWindow) {
|
||||
use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;
|
||||
use windows_core::Interface;
|
||||
let r = w.with_webview(|wv| unsafe {
|
||||
let Ok(core) = wv.controller().CoreWebView2() else { return };
|
||||
let Ok(s) = core.Settings() else { return };
|
||||
let _ = s.SetAreDefaultContextMenusEnabled(false);
|
||||
if let Ok(s3) = s.cast::<ICoreWebView2Settings3>() {
|
||||
let _ = s3.SetAreBrowserAcceleratorKeysEnabled(false);
|
||||
}
|
||||
});
|
||||
if let Err(e) = r {
|
||||
logs::host("warn", &format!("webview menus not turned off: {e}"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,6 @@
|
|||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
// `storebound desktop` reads the installed version this way (Windows, Linux; macOS reads Info.plist)
|
||||
if std::env::args().nth(1).as_deref() == Some("--version") {
|
||||
println!("storebound-desktop {}", env!("CARGO_PKG_VERSION"));
|
||||
return;
|
||||
}
|
||||
// Release smoke test of the exact artifact (tools/desktop-release.ts, the Forgejo workflow): sidecar handshake,
|
||||
// one JSON line, exit. Runs before Tauri starts, so no window opens.
|
||||
if std::env::args().skip(1).any(|a| a == storebound_desktop::selftest::FLAG) {
|
||||
|
|
|
|||
|
|
@ -1,749 +0,0 @@
|
|||
//! 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::*;
|
||||
|
|
@ -43,30 +43,6 @@ pub fn require_main(label: &str, url: &Url, dev: bool) -> Result<(), String> {
|
|||
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.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
|
|
@ -77,8 +53,7 @@ pub enum Kind {
|
|||
Session,
|
||||
/// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key.
|
||||
Account,
|
||||
/// Owner actions (rollout share, phased release, sending one approved reply, submit for review, the Play production
|
||||
/// release, price changes): like writes, a dry run from the
|
||||
/// Owner actions (rollout share, phased release, sending one approved reply): like writes, a dry run from the
|
||||
/// window; the real run only through `write_with_confirm`, whose dialog says that users see it at once.
|
||||
Owner,
|
||||
}
|
||||
|
|
@ -131,11 +106,6 @@ pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Res
|
|||
Ok(Value::Object(out))
|
||||
}
|
||||
|
||||
/// Owner actions that send the app to review or to production (cli/serve.ts OWNER_SUBMIT): App Store submit, resubmit
|
||||
/// after a rejection, in-app purchases to App Review, the Play production release. Like every owner action they run
|
||||
/// for real only through `write_with_confirm`; their dialog says that the app goes to review and may go live by itself.
|
||||
pub const SUBMIT_METHODS: &[&str] = &["owner.apple_submit", "owner.apple_resubmit", "owner.apple_iap_submit", "owner.play_production"];
|
||||
|
||||
/// Write methods whose project is a new folder without a config (the host picks it in a native dialog and runs them
|
||||
/// in its own commands: `project_init`, `project_import_fastlane`); `write_with_confirm` never runs them.
|
||||
pub const NEW_FOLDER_METHODS: &[&str] = &["project.init", "import.fastlane"];
|
||||
|
|
@ -144,19 +114,10 @@ pub const NEW_FOLDER_METHODS: &[&str] = &["project.init", "import.fastlane"];
|
|||
/// closes it. `write_with_confirm` shows its answers and this note instead of a dry-run log; a cancel (`job_cancel`)
|
||||
/// stops the command, which closes the browser.
|
||||
pub const CONSOLE_FILL: &str = "console.fill";
|
||||
pub const CONSOLE_FILL_NOTE: &str = "Console pages change. This is AI-assisted: review every field in the browser and press the final button (Publish, Submit, Save or Create) yourself. storebound moves through the pages for you and never submits or publishes; App Privacy answers stay a draft until you press Publish.";
|
||||
pub const CONSOLE_FILL_NOTE: &str = "Console pages change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves, submits or publishes.";
|
||||
|
||||
/// Writes a store-only app (no folder) may run: they send only what the call carries (one language's texts), never
|
||||
/// the sidecar's generated config. Dry run from the window like every write; the real run only through
|
||||
/// `write_with_confirm`, its token bound to the store ids (`virtual`) instead of a folder.
|
||||
pub const STORE_ONLY_WRITES: &[&str] = &["listing.set"];
|
||||
|
||||
pub fn store_only_write(method: &str, kind: Option<Kind>) -> bool {
|
||||
kind == Some(Kind::Write) && STORE_ONLY_WRITES.contains(&method)
|
||||
}
|
||||
|
||||
/// Reads that are never kept in the offline cache (big: one rendered image or one live store thumbnail as a data: URL).
|
||||
pub const NO_CACHE_METHODS: &[&str] = &["project.render", "art.thumb"];
|
||||
/// Reads that are never kept in the offline cache (big: one rendered image as a data: URL).
|
||||
pub const NO_CACHE_METHODS: &[&str] = &["project.render"];
|
||||
|
||||
/// File kinds the window may export through `export_save`, with their extension.
|
||||
pub const EXPORT_KINDS: &[&str] = &["csv", "md", "json", "txt"];
|
||||
|
|
@ -198,14 +159,9 @@ pub fn project_relative(rel: &str) -> Option<std::path::PathBuf> {
|
|||
Some(p.to_path_buf())
|
||||
}
|
||||
|
||||
/// What `project_reveal` may open (not only show in the file manager): a folder, the gallery page storebound writes,
|
||||
/// or a readiness report page of `storebound report` (.storebound/reports/readiness-*.html, no scripts in it).
|
||||
/// What `project_reveal` may open (not only show in the file manager): a folder, or the gallery page storebound writes.
|
||||
pub fn openable(rel: &std::path::Path, is_dir: bool) -> bool {
|
||||
if is_dir || rel.file_name().and_then(|n| n.to_str()) == Some("index.html") {
|
||||
return true;
|
||||
}
|
||||
let parts: Vec<&str> = rel.components().filter_map(|c| c.as_os_str().to_str()).collect();
|
||||
matches!(parts.as_slice(), [".storebound", "reports", name] if name.starts_with("readiness-") && name.ends_with(".html") && name.len() <= 80)
|
||||
is_dir || rel.file_name().and_then(|n| n.to_str()) == Some("index.html")
|
||||
}
|
||||
|
||||
/// Hosts `open_external` may open in the browser: the two store consoles and storebound's own site.
|
||||
|
|
@ -214,8 +170,6 @@ pub const EXTERNAL_HOSTS: &[&str] = &[
|
|||
"appstoreconnect.apple.com",
|
||||
"developer.apple.com",
|
||||
"storebound.dev",
|
||||
// the guides (skills/<name>/SKILL.md) of check findings, in storebound's public repo
|
||||
"git.crt.fyi",
|
||||
// Dependencies screen link-outs
|
||||
"developer.android.com",
|
||||
"ffmpeg.org",
|
||||
|
|
|
|||
|
|
@ -1,398 +0,0 @@
|
|||
//! The store accounts of this machine, shared with the storebound CLI: credential profiles in
|
||||
//! `~/.storebound/credentials` (STOREBOUND_CREDENTIALS_DIR), the same files `storebound accounts` lists and every
|
||||
//! terminal command reads (cli/lib/credentials.ts). A profile `<name>.json` holds one App Store Connect team key and / or
|
||||
//! one Play service account; its key files live next to it in `<name>/` (mode 0600, folders 0700) and the profile names
|
||||
//! them by relative path:
|
||||
//! { "label": "Acme", "ASC_KEY_ID": "...", "ASC_ISSUER_ID": "...", "ASC_P8": "acme/app-store-connect.p8",
|
||||
//! "PLAY_SERVICE_ACCOUNT": "acme/play-service-account.json" }
|
||||
//! One desktop account = one store of one profile (`Account::profile`). Accounts the CLI added show up in the app
|
||||
//! (`sync`), and keys the app adds are there for the CLI. Desktop accounts of earlier versions kept their keys in the
|
||||
//! OS keychain; `sync` moves each one into a profile once (the same key as an existing profile = that profile) and
|
||||
//! then deletes the keychain entry. Secrets still never reach the webview: they are read here right before a sidecar
|
||||
//! call. A removed account's key files are moved to `.removed/` (never deleted outright).
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::accounts::{Account, AccountKind, Secret, SecretStore};
|
||||
|
||||
pub const P8_FILE: &str = "app-store-connect.p8";
|
||||
pub const PLAY_FILE: &str = "play-service-account.json";
|
||||
|
||||
/// The folder: STOREBOUND_CREDENTIALS_DIR, else ~/.storebound/credentials (the CLI's profileDir()).
|
||||
pub fn default_dir(home: Option<&Path>) -> PathBuf {
|
||||
if let Some(d) = std::env::var_os("STOREBOUND_CREDENTIALS_DIR").filter(|d| !d.is_empty()) {
|
||||
return PathBuf::from(d);
|
||||
}
|
||||
home.map(Path::to_path_buf).unwrap_or_default().join(".storebound").join("credentials")
|
||||
}
|
||||
|
||||
/// A profile name: the CLI's PROFILE_RE (letters, digits, . _ -, starting with a letter or digit, max 64).
|
||||
pub fn valid_name(n: &str) -> bool {
|
||||
let mut c = n.chars();
|
||||
matches!(c.next(), Some(f) if f.is_ascii_alphanumeric()) && n.len() <= 64 && n.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
|
||||
}
|
||||
|
||||
/// A profile name from a label: lower case, other characters as `-` (the CLI's slug).
|
||||
pub fn slug(label: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for c in label.to_lowercase().chars() {
|
||||
if c.is_ascii_alphanumeric() || c == '.' || c == '_' {
|
||||
out.push(c);
|
||||
} else if !out.ends_with('-') {
|
||||
out.push('-');
|
||||
}
|
||||
}
|
||||
let s: String = out.trim_matches(|c| c == '-' || c == '.').chars().take(56).collect();
|
||||
if s.is_empty() || !valid_name(&s) {
|
||||
"account".into()
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// The CLI workspace's account id for a profile's store: sha256("<apple|play>:<profile>"), 16 hex (cli/lib/workspace.ts
|
||||
/// accountId), so the same account has the same id in `storebound.workspace.json` and in the app.
|
||||
/// A Play developer account id: 1-25 digits.
|
||||
pub fn valid_developer_id(v: &str) -> bool {
|
||||
!v.is_empty() && v.len() <= 25 && v.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
pub fn account_id(kind: AccountKind, profile: &str) -> String {
|
||||
let store = match kind {
|
||||
AccountKind::Apple => "apple",
|
||||
AccountKind::Play => "play",
|
||||
};
|
||||
let d = Sha256::digest(format!("{store}:{profile}").as_bytes());
|
||||
d.iter().take(8).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn str_of<'a>(m: &'a Map<String, Value>, k: &str) -> Option<&'a str> {
|
||||
m.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
pub struct ProfileStore {
|
||||
pub dir: PathBuf,
|
||||
home: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// What a profile reaches, for matching (never shown).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Identity {
|
||||
pub apple_key_id: Option<String>,
|
||||
pub play_email: Option<String>,
|
||||
}
|
||||
|
||||
impl ProfileStore {
|
||||
pub fn new(dir: PathBuf, home: Option<PathBuf>) -> ProfileStore {
|
||||
ProfileStore { dir, home }
|
||||
}
|
||||
|
||||
/// The profiles (`*.json` with a valid name), sorted.
|
||||
pub fn names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = fs::read_dir(&self.dir)
|
||||
.map(|rd| rd.filter_map(Result::ok).filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".json")).map(str::to_string)).filter(|n| valid_name(n)).collect())
|
||||
.unwrap_or_default();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
pub fn read(&self, name: &str) -> Result<Map<String, Value>, String> {
|
||||
if !valid_name(name) {
|
||||
return Err(format!("profile {name}: not a profile name"));
|
||||
}
|
||||
let text = fs::read_to_string(self.dir.join(format!("{name}.json"))).map_err(|e| format!("profile {name}: {e}"))?;
|
||||
match serde_json::from_str::<Value>(&text) {
|
||||
Ok(Value::Object(m)) => Ok(m),
|
||||
_ => Err(format!("profile {name}: not a JSON object")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A value that is a key file path: relative to the credentials folder, `~/` from home, or absolute.
|
||||
fn path_of(&self, v: &str) -> PathBuf {
|
||||
if let (Some(rest), Some(h)) = (v.strip_prefix("~/"), self.home.as_ref()) {
|
||||
return h.join(rest);
|
||||
}
|
||||
let p = Path::new(v);
|
||||
if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
self.dir.join(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of a value that is inline (PEM / JSON) or a file.
|
||||
fn content(&self, v: &str) -> Result<String, String> {
|
||||
if v.contains("BEGIN PRIVATE KEY") || v.trim_start().starts_with('{') {
|
||||
return Ok(v.to_string());
|
||||
}
|
||||
fs::read_to_string(self.path_of(v)).map_err(|e| format!("key file: {e}"))
|
||||
}
|
||||
|
||||
pub fn kinds(&self, name: &str) -> Vec<AccountKind> {
|
||||
let Ok(m) = self.read(name) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
if str_of(&m, "ASC_KEY_ID").is_some() && str_of(&m, "ASC_ISSUER_ID").is_some() {
|
||||
out.push(AccountKind::Apple);
|
||||
}
|
||||
if str_of(&m, "PLAY_SERVICE_ACCOUNT").is_some() {
|
||||
out.push(AccountKind::Play);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The Play developer account id a profile keeps (PLAY_DEVELOPER_ID, digits), if any.
|
||||
pub fn play_developer_id(&self, name: &str) -> Option<String> {
|
||||
self.read(name).ok().and_then(|m| str_of(&m, "PLAY_DEVELOPER_ID").map(str::trim).filter(|v| valid_developer_id(v)).map(str::to_string))
|
||||
}
|
||||
|
||||
/// Sets or clears (None) PLAY_DEVELOPER_ID in an existing profile; every other field stays.
|
||||
pub fn set_play_developer_id(&self, name: &str, id: Option<&str>) -> Result<(), String> {
|
||||
let mut m = self.read(name)?;
|
||||
match id {
|
||||
Some(v) if valid_developer_id(v) => { m.insert("PLAY_DEVELOPER_ID".into(), Value::String(v.to_string())); }
|
||||
Some(_) => return Err("the Play developer id is the digits in play.google.com/console/u/0/developers/<id>".into()),
|
||||
None => { m.remove("PLAY_DEVELOPER_ID"); }
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&Value::Object(m)).map_err(|e| e.to_string())? + "
|
||||
";
|
||||
write_private(&self.dir.join(format!("{name}.json")), text.as_bytes())
|
||||
}
|
||||
|
||||
/// The label the profile carries, if any (written by the app; the CLI ignores it).
|
||||
pub fn label(&self, name: &str) -> Option<String> {
|
||||
self.read(name).ok().and_then(|m| str_of(&m, "label").map(str::to_string))
|
||||
}
|
||||
|
||||
/// One store's keys of a profile, read from its files right now.
|
||||
pub fn secret(&self, name: &str, kind: AccountKind) -> Result<Secret, String> {
|
||||
let m = self.read(name)?;
|
||||
match kind {
|
||||
AccountKind::Apple => {
|
||||
let key_id = str_of(&m, "ASC_KEY_ID").ok_or_else(|| format!("profile {name}: no ASC_KEY_ID"))?.to_string();
|
||||
let issuer_id = str_of(&m, "ASC_ISSUER_ID").ok_or_else(|| format!("profile {name}: no ASC_ISSUER_ID"))?.to_string();
|
||||
// no ASC_P8: the CLI looks in ~/.appstoreconnect/private_keys itself
|
||||
let p8 = match str_of(&m, "ASC_P8") {
|
||||
Some(v) => self.content(v)?,
|
||||
None => String::new(),
|
||||
};
|
||||
Ok(Secret::Apple { key_id, issuer_id, p8 })
|
||||
}
|
||||
AccountKind::Play => {
|
||||
let v = str_of(&m, "PLAY_SERVICE_ACCOUNT").ok_or_else(|| format!("profile {name}: no PLAY_SERVICE_ACCOUNT"))?;
|
||||
Ok(Secret::Play { service_account: self.content(v)? })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn identity(&self, name: &str) -> Identity {
|
||||
let apple_key_id = self.read(name).ok().and_then(|m| str_of(&m, "ASC_KEY_ID").map(str::to_string));
|
||||
let play_email = match self.secret(name, AccountKind::Play) {
|
||||
Ok(Secret::Play { service_account }) => email_of(&service_account),
|
||||
_ => None,
|
||||
};
|
||||
Identity { apple_key_id, play_email }
|
||||
}
|
||||
|
||||
/// Where a new key goes: the profile that already has this key (same key id / service account e-mail), else the
|
||||
/// profile named after the label when it has no key of this store yet, else a free name.
|
||||
pub fn place(&self, label: &str, secret: &Secret) -> String {
|
||||
let names = self.names();
|
||||
for n in &names {
|
||||
let id = self.identity(n);
|
||||
let same = match secret {
|
||||
Secret::Apple { key_id, .. } => id.apple_key_id.as_deref() == Some(key_id.as_str()),
|
||||
Secret::Play { service_account } => id.play_email.is_some() && id.play_email == email_of(service_account),
|
||||
};
|
||||
if same {
|
||||
return n.clone();
|
||||
}
|
||||
}
|
||||
let base = slug(label);
|
||||
if !names.contains(&base) || !self.kinds(&base).contains(&secret.kind()) {
|
||||
return base;
|
||||
}
|
||||
let kind = match secret.kind() {
|
||||
AccountKind::Apple => "apple",
|
||||
AccountKind::Play => "play",
|
||||
};
|
||||
let mut i = 1;
|
||||
loop {
|
||||
let n = if i == 1 { format!("{base}-{kind}") } else { format!("{base}-{kind}-{i}") };
|
||||
if !names.contains(&n) || !self.kinds(&n).contains(&secret.kind()) {
|
||||
return n;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_dir(&self, d: &Path) -> Result<(), String> {
|
||||
fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
private_dir(d);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes one store's keys into profile `name` (created when missing): the key file in `<name>/` (0600), then the
|
||||
/// profile JSON (0600, atomic), keeping the profile's other store and fields. The written profile is read back.
|
||||
pub fn save(&self, name: &str, label: &str, secret: &Secret) -> Result<(), String> {
|
||||
if !valid_name(name) {
|
||||
return Err(format!("profile {name}: not a profile name"));
|
||||
}
|
||||
self.ensure_dir(&self.dir)?;
|
||||
let mut m = if self.dir.join(format!("{name}.json")).exists() { self.read(name)? } else { Map::new() };
|
||||
let keys = self.dir.join(name);
|
||||
self.ensure_dir(&keys)?;
|
||||
match secret {
|
||||
Secret::Apple { key_id, issuer_id, p8 } => {
|
||||
if !p8.is_empty() {
|
||||
write_private(&keys.join(P8_FILE), p8.as_bytes())?;
|
||||
m.insert("ASC_P8".into(), Value::String(format!("{name}/{P8_FILE}")));
|
||||
}
|
||||
m.insert("ASC_KEY_ID".into(), Value::String(key_id.clone()));
|
||||
m.insert("ASC_ISSUER_ID".into(), Value::String(issuer_id.clone()));
|
||||
}
|
||||
Secret::Play { service_account } => {
|
||||
write_private(&keys.join(PLAY_FILE), service_account.as_bytes())?;
|
||||
m.insert("PLAY_SERVICE_ACCOUNT".into(), Value::String(format!("{name}/{PLAY_FILE}")));
|
||||
}
|
||||
}
|
||||
if !m.contains_key("label") && !label.trim().is_empty() {
|
||||
m.insert("label".into(), Value::String(label.trim().to_string()));
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&Value::Object(m)).map_err(|e| e.to_string())? + "\n";
|
||||
write_private(&self.dir.join(format!("{name}.json")), text.as_bytes())?;
|
||||
match self.secret(name, secret.kind()) {
|
||||
Ok(back) if back == *secret || matches!((&back, secret), (Secret::Apple { key_id: a, .. }, Secret::Apple { key_id: b, p8, .. }) if a == b && p8.is_empty()) => Ok(()),
|
||||
Ok(_) => Err(format!("profile {name}: the key did not read back the same")),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes one store from a profile: its key file goes to `.removed/<name>-<time>/`, its fields leave the profile,
|
||||
/// and a profile with no store left moves there too. Nothing is deleted outright.
|
||||
pub fn remove(&self, name: &str, kind: AccountKind, stamp: &str) -> Result<(), String> {
|
||||
let mut m = self.read(name)?;
|
||||
let archive = self.dir.join(".removed").join(format!("{name}-{stamp}"));
|
||||
self.ensure_dir(&archive)?;
|
||||
let (fields, file): (&[&str], &str) = match kind {
|
||||
AccountKind::Apple => (&["ASC_KEY_ID", "ASC_ISSUER_ID", "ASC_P8", "ASC_VENDOR_NUMBER"], "ASC_P8"),
|
||||
AccountKind::Play => (&["PLAY_SERVICE_ACCOUNT"], "PLAY_SERVICE_ACCOUNT"),
|
||||
};
|
||||
// only key files inside the credentials folder are moved; a file the owner keeps elsewhere stays where it is
|
||||
if let Some(v) = str_of(&m, file) {
|
||||
let p = self.path_of(v);
|
||||
if p.starts_with(&self.dir) && p.is_file() {
|
||||
let to = archive.join(p.file_name().unwrap_or_default());
|
||||
fs::rename(&p, &to).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
}
|
||||
}
|
||||
for f in fields {
|
||||
m.remove(*f);
|
||||
}
|
||||
let left = ["ASC_KEY_ID", "PLAY_SERVICE_ACCOUNT"].iter().any(|k| m.contains_key(*k));
|
||||
let json = self.dir.join(format!("{name}.json"));
|
||||
if left {
|
||||
let text = serde_json::to_string_pretty(&Value::Object(m)).map_err(|e| e.to_string())? + "\n";
|
||||
write_private(&json, text.as_bytes())
|
||||
} else {
|
||||
fs::rename(&json, archive.join(format!("{name}.json"))).map_err(|e| e.to_string())?;
|
||||
let _ = fs::remove_dir(self.dir.join(name));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The client_email of a service account JSON.
|
||||
pub fn email_of(sa: &str) -> Option<String> {
|
||||
serde_json::from_str::<Value>(sa).ok()?.get("client_email")?.as_str().map(str::to_string)
|
||||
}
|
||||
|
||||
fn private_dir(d: &Path) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = fs::set_permissions(d, fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = d;
|
||||
}
|
||||
|
||||
/// Writes a file only its owner can read (0600 on unix), atomically (temp file, then rename).
|
||||
pub fn write_private(path: &Path, data: &[u8]) -> Result<(), String> {
|
||||
let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
|
||||
{
|
||||
let mut o = fs::OpenOptions::new();
|
||||
o.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
o.mode(0o600);
|
||||
}
|
||||
let mut f = o.open(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
f.write_all(data).map_err(|e| e.to_string())?;
|
||||
f.sync_all().map_err(|e| e.to_string())?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&tmp, fs::Permissions::from_mode(0o600)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// What `sync` did, for host.log (no values).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct SyncReport {
|
||||
pub migrated: Vec<String>,
|
||||
pub added: Vec<String>,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl SyncReport {
|
||||
pub fn changed(&self) -> bool {
|
||||
!self.migrated.is_empty() || !self.added.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings the app's account list in line with the shared profiles: (1) an account of an earlier version still in the
|
||||
/// keychain moves into a profile (its id, label, studio and app mappings stay) and its keychain entry is deleted once
|
||||
/// the profile reads back; (2) every profile store without an account gets one (id: `account_id`, label: the
|
||||
/// profile's label or name). Accounts whose profile disappeared stay (the app says the key is missing).
|
||||
pub fn sync(accounts: &mut Vec<Account>, store: &ProfileStore, legacy: &dyn SecretStore, now: &str) -> SyncReport {
|
||||
let mut r = SyncReport::default();
|
||||
for a in accounts.iter_mut().filter(|a| a.profile.is_none()) {
|
||||
match legacy.get(&a.id) {
|
||||
Ok(secret) => {
|
||||
let name = store.place(&a.label, &secret);
|
||||
match store.save(&name, &a.label, &secret) {
|
||||
Ok(()) => {
|
||||
a.profile = Some(name.clone());
|
||||
if let Err(e) = legacy.delete(&a.id) {
|
||||
r.notes.push(format!("account {}: moved to profile {name}, the keychain entry stays ({e})", a.id));
|
||||
}
|
||||
r.migrated.push(format!("{} -> {name}", a.id));
|
||||
}
|
||||
Err(e) => r.notes.push(format!("account {}: not moved to a profile yet ({e}); the keychain keeps it", a.id)),
|
||||
}
|
||||
}
|
||||
Err(e) => r.notes.push(format!("account {}: no key in the keychain ({e})", a.id)),
|
||||
}
|
||||
}
|
||||
for name in store.names() {
|
||||
for kind in store.kinds(&name) {
|
||||
if accounts.iter().any(|a| a.kind == kind && a.profile.as_deref() == Some(name.as_str())) {
|
||||
continue;
|
||||
}
|
||||
let id = account_id(kind, &name);
|
||||
if accounts.iter().any(|a| a.id == id) {
|
||||
continue;
|
||||
}
|
||||
accounts.push(Account { id: id.clone(), label: store.label(&name).unwrap_or_else(|| name.clone()), kind, created: now.to_string(), studio: None, profile: Some(name.clone()), developer_id: None });
|
||||
r.added.push(format!("{id} ({name})"));
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
|
@ -1,365 +0,0 @@
|
|||
//! The app folders of this machine, shared with the storebound CLI: `~/.storebound/projects.json`
|
||||
//! (STOREBOUND_REGISTRY), the same file as `storebound apps folders` / `apps add` / `storebound desktop` / `ws`
|
||||
//! (cli/lib/registry.ts). The list of folders is the registry's; the app keeps its per-folder extras (mapped accounts)
|
||||
//! in state.json under the same id. `sync` runs at start, when the list is shown and before a deep link is handled;
|
||||
//! adding, removing and locating a folder in the app write the registry too. The first start with a registry missing
|
||||
//! writes the app's own list into it.
|
||||
//! { "version": 1, "projects": [{ "id": "<16 hex>", "path": "/abs/folder", "name": "Star Dash", "added": "<iso>" }],
|
||||
//! "storeApps": [{ "id": "<16 hex>", "store": "apple", "appId": "6400000000", "account": "<profile>", "name": "…" }] }
|
||||
//! `storeApps` (written by `storebound apps add --store … --app-id …`) are apps live on a store with no project on this
|
||||
//! machine: they join the app list of the account with that credential profile (`store_apps_cached`), so the
|
||||
//! portfolio shows them read-only ("store only"). Writing the folder list keeps them.
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::store::{Project, State};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub id: String,
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub added: String,
|
||||
}
|
||||
|
||||
pub fn default_file(home: Option<&Path>) -> PathBuf {
|
||||
if let Some(f) = std::env::var_os("STOREBOUND_REGISTRY").filter(|f| !f.is_empty()) {
|
||||
return PathBuf::from(f);
|
||||
}
|
||||
home.map(Path::to_path_buf).unwrap_or_default().join(".storebound").join("projects.json")
|
||||
}
|
||||
|
||||
/// The CLI's id for a folder it adds: sha256("project:<path>"), 16 hex (cli/lib/registry.ts folderId).
|
||||
pub fn folder_id(path: &str) -> String {
|
||||
Sha256::digest(format!("project:{path}").as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn hex16(s: &str) -> bool {
|
||||
s.len() == 16 && s.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
|
||||
}
|
||||
|
||||
/// Parses the file (pure): entries without an absolute path or with a repeated path are dropped.
|
||||
pub fn parse(text: &str) -> Vec<Entry> {
|
||||
let Ok(v) = serde_json::from_str::<Value>(text) else { return vec![] };
|
||||
let mut out: Vec<Entry> = vec![];
|
||||
for p in v.get("projects").and_then(Value::as_array).into_iter().flatten() {
|
||||
let Some(path) = p.get("path").and_then(Value::as_str) else { continue };
|
||||
if !Path::new(path).is_absolute() || out.iter().any(|e| e.path == path) {
|
||||
continue;
|
||||
}
|
||||
let id = p.get("id").and_then(Value::as_str).filter(|i| hex16(i) && !out.iter().any(|e| e.id == *i)).map(str::to_string).unwrap_or_else(|| folder_id(path));
|
||||
let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).map(str::to_string)
|
||||
.unwrap_or_else(|| Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "App".into()));
|
||||
out.push(Entry { id, path: path.to_string(), name, added: p.get("added").and_then(Value::as_str).unwrap_or_default().to_string() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// None = the file does not exist (first start); Some(list) otherwise (an unreadable file reads as empty).
|
||||
pub fn read(file: &Path) -> Option<Vec<Entry>> {
|
||||
match fs::read_to_string(file) {
|
||||
Ok(t) => Some(parse(&t)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(_) => Some(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(file: &Path, entries: &[Entry]) -> Result<(), String> {
|
||||
if let Some(d) = file.parent() {
|
||||
fs::create_dir_all(d).map_err(|e| e.to_string())?;
|
||||
}
|
||||
// the store-only entries the CLI wrote stay as they are
|
||||
let keep = fs::read_to_string(file).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v.get("storeApps").cloned()).filter(|s| s.as_array().is_some_and(|a| !a.is_empty()));
|
||||
let mut doc = serde_json::json!({ "version": 1, "projects": entries });
|
||||
// the folders' `ignored` flags (written by the CLI or by push_ignored) stay with their folder
|
||||
let old = fs::read_to_string(file).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
if let (Some(old), Some(list)) = (old.as_ref().and_then(|o| o.get("projects")).and_then(Value::as_array), doc.get_mut("projects").and_then(Value::as_array_mut)) {
|
||||
for e in list {
|
||||
let ig = e.get("path").and_then(Value::as_str).and_then(|path| old.iter().find(|o| o.get("path").and_then(Value::as_str) == Some(path))).and_then(|o| o.get("ignored")).cloned();
|
||||
if let (Some(ig), Some(o)) = (ig, e.as_object_mut()) {
|
||||
o.insert("ignored".into(), ig);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(s) = keep {
|
||||
doc["storeApps"] = s;
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())? + "\n";
|
||||
let tmp = file.with_extension(format!("tmp-{}", std::process::id()));
|
||||
fs::write(&tmp, text).map_err(|e| e.to_string())?;
|
||||
fs::rename(&tmp, file).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// An app that is live on a store with no project on this machine (cli/lib/registry.ts StoreOnlyApp).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StoreOnly {
|
||||
pub id: String,
|
||||
/// "apple" | "play"
|
||||
pub store: String,
|
||||
/// Apple: the numeric app id; Play: the package name.
|
||||
pub app_id: String,
|
||||
/// The credential profile that reads it; None = the account of that store when there is only one.
|
||||
pub account: Option<String>,
|
||||
pub name: String,
|
||||
pub bundle_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The store-only entries of the file's text (pure): malformed ones are dropped.
|
||||
pub fn parse_store_apps(text: &str) -> Vec<StoreOnly> {
|
||||
let Ok(v) = serde_json::from_str::<Value>(text) else { return vec![] };
|
||||
let mut out: Vec<StoreOnly> = vec![];
|
||||
for x in v.get("storeApps").and_then(Value::as_array).into_iter().flatten() {
|
||||
let s = |k: &str| x.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
|
||||
let (Some(store), Some(app_id)) = (s("store"), s("appId")) else { continue };
|
||||
let ok = match store.as_str() {
|
||||
"apple" => app_id.len() >= 6 && app_id.len() <= 12 && app_id.chars().all(|c| c.is_ascii_digit()),
|
||||
"play" => app_id.contains('.') && app_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_'),
|
||||
_ => false,
|
||||
};
|
||||
if !ok || out.iter().any(|o| o.store == store && o.app_id == app_id) {
|
||||
continue;
|
||||
}
|
||||
let id: String = Sha256::digest(format!("store:{store}:{app_id}").as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect();
|
||||
let bundle_id = s("bundleId").or_else(|| (store == "play").then(|| app_id.clone()));
|
||||
out.push(StoreOnly { id, name: s("name").unwrap_or_else(|| app_id.clone()), account: s("account"), bundle_id, store, app_id });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn read_store_apps(file: &Path) -> Vec<StoreOnly> {
|
||||
fs::read_to_string(file).map(|t| parse_store_apps(&t)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One account's app list (`apps.list` JSON, or None when never read) with the store-only entries of its profile
|
||||
/// added (pure). `store` is "apple" | "play"; `only` = this is the only account of that store (entries that name no
|
||||
/// profile go to it). The entries already in the list (same id) are left as the store reported them.
|
||||
pub fn with_store_only(list: Option<Value>, store: &str, profile: Option<&str>, only: bool, apps: &[StoreOnly], at: &str) -> Option<Value> {
|
||||
let mine: Vec<&StoreOnly> = apps.iter().filter(|a| a.store == store && (a.account.as_deref().is_some_and(|p| Some(p) == profile) || (a.account.is_none() && only))).collect();
|
||||
if mine.is_empty() {
|
||||
return list;
|
||||
}
|
||||
let ios = store == "apple";
|
||||
let mut v = list.unwrap_or_else(|| serde_json::json!({ "store": if ios { "ios" } else { "android" }, "apps": [], "warnings": [], "at": at }));
|
||||
if !v.get("apps").is_some_and(Value::is_array) {
|
||||
v["apps"] = serde_json::json!([]);
|
||||
}
|
||||
let have: Vec<String> = v["apps"].as_array().map(|a| a.iter().filter_map(|x| x.get("id").and_then(Value::as_str).map(str::to_string)).collect()).unwrap_or_default();
|
||||
for a in mine {
|
||||
if have.contains(&a.app_id) {
|
||||
continue;
|
||||
}
|
||||
let app = serde_json::json!({
|
||||
"store": if ios { "ios" } else { "android" }, "id": a.app_id, "bundleId": a.bundle_id.clone().unwrap_or_default(), "name": a.name,
|
||||
"platforms": [if ios { "IOS" } else { "ANDROID" }], "sku": null, "primaryLocale": null, "latest": null, "icon": null, "registered": true,
|
||||
});
|
||||
if let Some(list) = v["apps"].as_array_mut() {
|
||||
list.push(app);
|
||||
}
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
fn entry_of(p: &Project) -> Entry {
|
||||
Entry { id: p.id.clone(), path: p.path.clone(), name: p.name.clone(), added: p.added.clone() }
|
||||
}
|
||||
|
||||
/// Makes the app's folder list the registry's (pure on the values). A registry folder the app has (by path) keeps the
|
||||
/// app's id, name and accounts; a new one comes in with the registry's id; a folder that left the registry leaves the
|
||||
/// app (with its links, ignore entries and studio moves). Returns (changed state, the registry to write back if it
|
||||
/// needs the app's ids or names).
|
||||
pub fn merge(state: &mut State, reg: Option<Vec<Entry>>) -> (bool, Option<Vec<Entry>>) {
|
||||
let Some(reg) = reg else {
|
||||
// first start with a shared list: the app's folders become it
|
||||
return (false, Some(state.projects.iter().map(entry_of).collect()));
|
||||
};
|
||||
let mut projects = Vec::with_capacity(reg.len());
|
||||
let mut write_back = false;
|
||||
for e in ® {
|
||||
match state.projects.iter().find(|p| p.path == e.path) {
|
||||
Some(p) => {
|
||||
if p.id != e.id || p.name != e.name {
|
||||
write_back = true;
|
||||
}
|
||||
projects.push(p.clone());
|
||||
}
|
||||
None => {
|
||||
// an id the app already uses for another folder gets the CLI's id instead
|
||||
let id = if state.projects.iter().any(|p| p.id == e.id) { folder_id(&e.path) } else { e.id.clone() };
|
||||
write_back |= id != e.id;
|
||||
projects.push(Project { id, path: e.path.clone(), name: e.name.clone(), play_account: None, apple_account: None, added: e.added.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let gone: Vec<String> = state.projects.iter().filter(|p| !projects.iter().any(|x| x.id == p.id)).map(|p| p.id.clone()).collect();
|
||||
let changed = projects != state.projects;
|
||||
for id in &gone {
|
||||
let key = format!("project:{id}");
|
||||
state.overrides.links.retain(|l| &l.project != id);
|
||||
state.overrides.ignored.retain(|i| i != &key);
|
||||
state.overrides.app_studio.retain(|a| a.key != key);
|
||||
}
|
||||
state.projects = projects;
|
||||
(changed, if write_back { Some(state.projects.iter().map(entry_of).collect()) } else { None })
|
||||
}
|
||||
|
||||
/// Reads the registry, merges, writes it back when needed. Returns whether the state changed.
|
||||
pub fn sync(state: &mut State, file: &Path) -> Result<bool, String> {
|
||||
let (changed, back) = merge(state, read(file));
|
||||
if let Some(list) = back {
|
||||
write(file, &list)?;
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// After the app changed its list (add, remove, locate): the registry gets the app's list, keeping folders another
|
||||
/// tool added since the last sync.
|
||||
pub fn publish(state: &State, file: &Path, removed: &[String]) -> Result<(), String> {
|
||||
let mut list: Vec<Entry> = state.projects.iter().map(entry_of).collect();
|
||||
for e in read(file).unwrap_or_default() {
|
||||
if !list.iter().any(|x| x.path == e.path || x.id == e.id) && !removed.contains(&e.path) {
|
||||
list.push(e);
|
||||
}
|
||||
}
|
||||
write(file, &list)
|
||||
}
|
||||
|
||||
// ---- ignored apps: the registry's `ignored` flags (cli/lib/registry.ts) <-> the app's ignore keys ----
|
||||
// projects: "ignored": ["apple", "play"] (both = the whole app) <-> "project:<id>" (both) / "project:<id>:ios" / "project:<id>:android"
|
||||
// storeApps: "ignored": ["apple"] <-> "app:ios:<account id>:<app id>" (android for play)
|
||||
// The registry is the truth for the apps it lists: `pull_ignored` (start, list shown) replaces the app's keys for those
|
||||
// apps with the registry's flags, `push_ignored` (the owner ignores or restores in the app) writes them back. Apps
|
||||
// that are not in the registry (listed by a store account only) keep their keys in the app's state alone.
|
||||
const SIDES: [&str; 2] = ["apple", "play"];
|
||||
|
||||
fn word_of(side: &str) -> &'static str {
|
||||
if side == "apple" { "ios" } else { "android" }
|
||||
}
|
||||
|
||||
fn sides_in(v: &Value) -> Vec<String> {
|
||||
let have: Vec<&str> = v.get("ignored").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
SIDES.iter().filter(|s| have.contains(s)).map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
fn is_project_key_of(k: &str, id: &str) -> bool {
|
||||
k == format!("project:{id}") || k.starts_with(&format!("project:{id}:"))
|
||||
}
|
||||
|
||||
/// The ignore keys of one folder for its ignored store sides (pure).
|
||||
pub fn project_keys(id: &str, sides: &[String]) -> Vec<String> {
|
||||
if SIDES.iter().all(|s| sides.iter().any(|x| x == s)) {
|
||||
return vec![format!("project:{id}")];
|
||||
}
|
||||
sides.iter().filter(|s| SIDES.contains(&s.as_str())).map(|s| format!("project:{id}:{}", word_of(s))).collect()
|
||||
}
|
||||
|
||||
/// The ignored store sides of a folder, from the app's ignore keys (pure).
|
||||
pub fn project_sides(keys: &[String], id: &str) -> Vec<String> {
|
||||
let mut on = [false, false];
|
||||
for k in keys {
|
||||
if *k == format!("project:{id}") {
|
||||
on = [true, true];
|
||||
} else if *k == format!("project:{id}:ios") {
|
||||
on[0] = true;
|
||||
} else if *k == format!("project:{id}:android") {
|
||||
on[1] = true;
|
||||
}
|
||||
}
|
||||
SIDES.iter().enumerate().filter(|(i, _)| on[*i]).map(|(_, s)| s.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Whether an ignore key "app:<ios|android>:<account>:<app id>" is this store app (pure).
|
||||
pub fn app_key_matches(k: &str, store: &str, app_id: &str) -> bool {
|
||||
let Some(rest) = k.strip_prefix("app:") else { return false };
|
||||
rest.split(':').next() == Some(word_of(store)) && rest.rsplit(':').next() == Some(app_id)
|
||||
}
|
||||
|
||||
/// The account (id) that reads a store-only entry: the one with its credential profile, else the only account of that store.
|
||||
pub fn account_for(accounts: &[crate::accounts::Account], store: &str, profile: Option<&str>) -> Option<String> {
|
||||
use crate::accounts::AccountKind;
|
||||
let kind = if store == "apple" { AccountKind::Apple } else { AccountKind::Play };
|
||||
let of_kind: Vec<_> = accounts.iter().filter(|a| a.kind == kind).collect();
|
||||
match profile {
|
||||
Some(p) => of_kind.iter().find(|a| a.profile.as_deref() == Some(p)).map(|a| a.id.clone()),
|
||||
None => (of_kind.len() == 1).then(|| of_kind[0].id.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_doc(file: &Path) -> Option<Value> {
|
||||
serde_json::from_str::<Value>(&fs::read_to_string(file).ok()?).ok()
|
||||
}
|
||||
|
||||
/// Registry flags -> the app's ignore keys. True when the keys changed.
|
||||
pub fn pull_ignored(state: &mut State, file: &Path) -> bool {
|
||||
let Some(doc) = parse_doc(file) else { return false };
|
||||
let before = state.overrides.ignored.clone();
|
||||
let mut keys = before.clone();
|
||||
for p in doc.get("projects").and_then(Value::as_array).into_iter().flatten() {
|
||||
let Some(path) = p.get("path").and_then(Value::as_str) else { continue };
|
||||
let Some(id) = state.projects.iter().find(|x| x.path == path).map(|x| x.id.clone()) else { continue };
|
||||
keys.retain(|k| !is_project_key_of(k, &id));
|
||||
keys.extend(project_keys(&id, &sides_in(p)));
|
||||
}
|
||||
for a in doc.get("storeApps").and_then(Value::as_array).into_iter().flatten() {
|
||||
let (Some(store), Some(app_id)) = (a.get("store").and_then(Value::as_str), a.get("appId").and_then(Value::as_str)) else { continue };
|
||||
let Some(acct) = account_for(&state.accounts, store, a.get("account").and_then(Value::as_str)) else { continue };
|
||||
keys.retain(|k| !app_key_matches(k, store, app_id));
|
||||
if sides_in(a).iter().any(|s| s == store) {
|
||||
keys.push(format!("app:{}:{acct}:{app_id}", word_of(store)));
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
keys.retain(|k| seen.insert(k.clone()));
|
||||
if keys == before {
|
||||
return false;
|
||||
}
|
||||
state.overrides.ignored = keys;
|
||||
true
|
||||
}
|
||||
|
||||
/// The app's ignore keys -> registry flags (only the apps the registry lists). Writes when something changed.
|
||||
pub fn push_ignored(state: &State, file: &Path) -> Result<bool, String> {
|
||||
let Some(mut doc) = parse_doc(file) else { return Ok(false) };
|
||||
let keys = &state.overrides.ignored;
|
||||
let mut changed = false;
|
||||
let mut set = |entry: &mut Value, sides: Vec<String>| {
|
||||
if sides_in(entry) == sides {
|
||||
return;
|
||||
}
|
||||
changed = true;
|
||||
if let Some(o) = entry.as_object_mut() {
|
||||
if sides.is_empty() {
|
||||
o.remove("ignored");
|
||||
} else {
|
||||
o.insert("ignored".into(), serde_json::json!(sides));
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(list) = doc.get_mut("projects").and_then(Value::as_array_mut) {
|
||||
for p in list {
|
||||
let Some(id) = p.get("path").and_then(Value::as_str).and_then(|path| state.projects.iter().find(|x| x.path == path)).map(|x| x.id.clone()) else { continue };
|
||||
set(p, project_sides(keys, &id));
|
||||
}
|
||||
}
|
||||
if let Some(list) = doc.get_mut("storeApps").and_then(Value::as_array_mut) {
|
||||
for a in list {
|
||||
let (Some(store), Some(app_id)) = (a.get("store").and_then(Value::as_str).map(str::to_string), a.get("appId").and_then(Value::as_str).map(str::to_string)) else { continue };
|
||||
if account_for(&state.accounts, &store, a.get("account").and_then(Value::as_str)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let on = keys.iter().any(|k| app_key_matches(k, &store, &app_id));
|
||||
set(a, if on { vec![store] } else { vec![] });
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())? + "\n";
|
||||
let tmp = file.with_extension(format!("tmp-{}", std::process::id()));
|
||||
fs::write(&tmp, text).map_err(|e| e.to_string())?;
|
||||
fs::rename(&tmp, file).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
|
@ -45,14 +45,11 @@ pub struct State {
|
|||
pub overrides: Overrides,
|
||||
#[serde(default)]
|
||||
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 {
|
||||
fn default() -> State {
|
||||
State { version: VERSION, projects: vec![], accounts: vec![], studios: vec![], overrides: Overrides::default(), settings: Settings::default(), menu_pins: vec![] }
|
||||
State { version: VERSION, projects: vec![], accounts: vec![], studios: vec![], overrides: Overrides::default(), settings: Settings::default() }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -124,7 +121,6 @@ pub fn migrate(mut v: Value) -> (State, u32, Vec<String>) {
|
|||
studios: list(&o, "studios", &mut notes),
|
||||
overrides: one(&o, "overrides", &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
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
|
|
|
|||
|
|
@ -1,286 +0,0 @@
|
|||
//! 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
|
||||
//! (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
|
||||
//! `tray-action` (`read`, `mute-toggle`).
|
||||
//!
|
||||
//! Clicking a desktop notification: the notification plugin has no click callback on Windows, macOS or Linux (its
|
||||
//! actions are mobile only). So `notify` remembers where the notification points (`set_pending`) and `show_main`
|
||||
//! hands it to the window as a `tray-route` the next time the window is shown from the tray or the Dock.
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tauri::image::Image;
|
||||
use tauri::menu::{IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
|
||||
|
||||
use crate::menu_panel::{from_entries, Node};
|
||||
use tauri::{AppHandle, Runtime};
|
||||
|
||||
pub const ID_OPEN: &str = "tray-open";
|
||||
pub const ID_READ: &str = "tray-read";
|
||||
pub const ID_MUTE: &str = "tray-mute";
|
||||
pub const ID_UPDATE: &str = "tray-update";
|
||||
pub const ID_SETTINGS: &str = "tray-settings";
|
||||
pub const ID_QUIT: &str = "tray-quit";
|
||||
pub const ID_APP_PREFIX: &str = "tray-app:";
|
||||
|
||||
/// Apps listed in the submenu (more would not fit a menu anyway).
|
||||
pub const MAX_APPS: usize = 30;
|
||||
/// Windows cuts a tooltip at 127 UTF-16 units; stay under it everywhere.
|
||||
pub const MAX_TIP: usize = 120;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct TrayApp {
|
||||
/// The app's key in the window (opens it).
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
/// Plain words: "App Store: In review · Play: Live".
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
/// The menu words in the window's language.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct TrayLabels {
|
||||
pub open: String,
|
||||
pub read_now: String,
|
||||
pub apps: String,
|
||||
pub no_apps: String,
|
||||
pub mute: String,
|
||||
pub unmute: String,
|
||||
pub update: String,
|
||||
pub settings: String,
|
||||
pub quit: String,
|
||||
}
|
||||
|
||||
impl Default for TrayLabels {
|
||||
fn default() -> TrayLabels {
|
||||
TrayLabels {
|
||||
open: "Open storebound".into(),
|
||||
read_now: "Read the stores now".into(),
|
||||
apps: "Apps".into(),
|
||||
no_apps: "No apps yet".into(),
|
||||
mute: "Mute notifications for 1 hour".into(),
|
||||
unmute: "Unmute notifications".into(),
|
||||
update: "Check for updates".into(),
|
||||
settings: "Settings".into(),
|
||||
quit: "Quit storebound".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct TraySummary {
|
||||
pub tooltip: String,
|
||||
/// Apps that need the owner (rejected, halted): above 0 the icon gets a red dot.
|
||||
pub attention: u32,
|
||||
/// Notifications are muted right now.
|
||||
pub muted: bool,
|
||||
pub apps: Vec<TrayApp>,
|
||||
pub labels: TrayLabels,
|
||||
}
|
||||
|
||||
/// One menu entry, before it is drawn.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
Item { id: String, label: String, enabled: bool },
|
||||
Separator,
|
||||
/// `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 {
|
||||
let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
let one = one.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if one.chars().count() <= max {
|
||||
return one;
|
||||
}
|
||||
let mut cut: String = one.chars().take(max.saturating_sub(1)).collect();
|
||||
cut.push('…');
|
||||
cut
|
||||
}
|
||||
|
||||
/// The tooltip: the window's text, one line, short; "storebound" when it sent none.
|
||||
pub fn tooltip_text(s: &TraySummary) -> String {
|
||||
let t = clean(&s.tooltip, MAX_TIP);
|
||||
if t.is_empty() { "storebound".into() } else { t }
|
||||
}
|
||||
|
||||
/// The context menu: Open, Read now, Apps (one entry per app with its state), Mute / Unmute, Check for updates,
|
||||
/// Settings, Quit.
|
||||
pub fn menu_model(s: &TraySummary) -> Vec<Entry> {
|
||||
let item = |id: &str, label: &str| Entry::Item { id: id.into(), label: clean(label, 90), enabled: true };
|
||||
let l = &s.labels;
|
||||
let apps: Vec<Entry> = if s.apps.is_empty() {
|
||||
vec![Entry::Item { id: "tray-none".into(), label: clean(&l.no_apps, 90), enabled: false }]
|
||||
} else {
|
||||
s.apps
|
||||
.iter()
|
||||
.filter(|a| !a.key.is_empty() && !a.key.chars().any(char::is_control))
|
||||
.take(MAX_APPS)
|
||||
.map(|a| {
|
||||
let name = clean(&a.name, 40);
|
||||
let state = clean(&a.state, 60);
|
||||
let label = if state.is_empty() { name } else { format!("{name} · {state}") };
|
||||
Entry::Item { id: format!("{ID_APP_PREFIX}{}", a.key.chars().take(200).collect::<String>()), label, enabled: true }
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
vec![
|
||||
item(ID_OPEN, &l.open),
|
||||
item(ID_READ, &l.read_now),
|
||||
Entry::Separator,
|
||||
Entry::Sub { key: "apps".into(), label: clean(&l.apps, 40), items: apps },
|
||||
Entry::Separator,
|
||||
item(ID_MUTE, if s.muted { &l.unmute } else { &l.mute }),
|
||||
item(ID_UPDATE, &l.update),
|
||||
item(ID_SETTINGS, &l.settings),
|
||||
Entry::Separator,
|
||||
item(ID_QUIT, &l.quit),
|
||||
]
|
||||
}
|
||||
|
||||
/// What a menu click does.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Action {
|
||||
/// Show the window.
|
||||
Open,
|
||||
Quit,
|
||||
/// Tell the window (no window needed): `tray-action` with this word.
|
||||
Event(&'static str),
|
||||
/// Show the window on this route (JSON for `tray-route`).
|
||||
Route(String),
|
||||
}
|
||||
|
||||
pub fn action_of(id: &str) -> Option<Action> {
|
||||
match id {
|
||||
ID_OPEN => Some(Action::Open),
|
||||
ID_READ => Some(Action::Event("read")),
|
||||
ID_MUTE => Some(Action::Event("mute-toggle")),
|
||||
ID_UPDATE => Some(Action::Route(serde_json::json!({ "screen": "settings", "section": "updates" }).to_string())),
|
||||
ID_SETTINGS => Some(Action::Route(serde_json::json!({ "screen": "settings" }).to_string())),
|
||||
ID_QUIT => Some(Action::Quit),
|
||||
_ => id.strip_prefix(ID_APP_PREFIX).filter(|k| !k.is_empty()).map(|k| Action::Route(serde_json::json!({ "screen": "app", "appId": k, "tab": "releases" }).to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A notification target the window may be sent to later: a small JSON object of strings with a known `screen`.
|
||||
pub fn valid_route(json: &str) -> bool {
|
||||
if json.len() > 400 {
|
||||
return false;
|
||||
}
|
||||
let Ok(Value::Object(o)) = serde_json::from_str::<Value>(json) else { return false };
|
||||
let screens = ["portfolio", "app", "apps", "accounts", "ignored", "dependencies", "settings"];
|
||||
o.len() <= 4 && o.values().all(|v| v.as_str().is_some_and(|s| s.len() <= 300 && !s.chars().any(char::is_control))) && o.get("screen").and_then(Value::as_str).is_some_and(|s| screens.contains(&s))
|
||||
}
|
||||
|
||||
/// The default icon with a red dot (white ring) in the top right corner, for "something needs you". RGBA in, RGBA out.
|
||||
pub fn with_attention_dot(rgba: &[u8], w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = rgba.to_vec();
|
||||
if w == 0 || h == 0 || out.len() != (w as usize) * (h as usize) * 4 {
|
||||
return out;
|
||||
}
|
||||
let side = w.min(h) as f32;
|
||||
let r = side * 0.27;
|
||||
let (cx, cy) = (w as f32 - r - side * 0.02, r + side * 0.02);
|
||||
let blend = |px: &mut [u8], color: [f32; 3], c: f32| {
|
||||
if c <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let a = px[3] as f32 / 255.0;
|
||||
let oa = a + (1.0 - a) * c;
|
||||
for i in 0..3 {
|
||||
// the dot covers what is under it by `c`; the alpha of the icon only grows
|
||||
px[i] = (px[i] as f32 * (1.0 - c) + color[i] * c).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
px[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8;
|
||||
};
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
let px = &mut out[i..i + 4];
|
||||
blend(px, [255.0, 255.0, 255.0], (r + 0.5 - d).clamp(0.0, 1.0));
|
||||
blend(px, [229.0, 57.0, 53.0], (r * 0.78 + 0.5 - d).clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---- where the last notification pointed ----
|
||||
|
||||
static PENDING: Mutex<Option<(String, Instant)>> = Mutex::new(None);
|
||||
const PENDING_FOR: Duration = Duration::from_secs(2 * 3600);
|
||||
|
||||
/// Remembers the route (JSON) of the notification just shown. Ignores anything `valid_route` refuses.
|
||||
pub fn set_pending(route: &str) {
|
||||
if valid_route(route) {
|
||||
if let Ok(mut p) = PENDING.lock() {
|
||||
*p = Some((route.to_string(), Instant::now()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The remembered route, once (it is forgotten after it is handed out, and after two hours).
|
||||
pub fn take_pending() -> Option<String> {
|
||||
let (route, at) = PENDING.lock().ok()?.take()?;
|
||||
(at.elapsed() < PENDING_FOR).then_some(route)
|
||||
}
|
||||
|
||||
// ---- drawing ----
|
||||
|
||||
static LAST: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// The native menu items for a panel tree (the fallback, and Linux), nested to any depth.
|
||||
fn native_items<R: Runtime>(app: &AppHandle<R>, nodes: &[Node]) -> tauri::Result<Vec<Box<dyn IsMenuItem<R>>>> {
|
||||
let mut out: Vec<Box<dyn IsMenuItem<R>>> = Vec::new();
|
||||
for n in nodes {
|
||||
match n {
|
||||
Node::Item { id, label, enabled } => out.push(Box::new(MenuItem::with_id(app, id, label, *enabled, None::<&str>)?)),
|
||||
Node::Sep => out.push(Box::new(PredefinedMenuItem::separator(app)?)),
|
||||
Node::Sub { label, items, .. } => {
|
||||
let children = native_items(app, items)?;
|
||||
let refs: Vec<&dyn IsMenuItem<R>> = children.iter().map(|b| b.as_ref()).collect();
|
||||
out.push(Box::new(Submenu::with_items(app, label, true, &refs)?));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The native tray menu, rendered from the same tree as the panels.
|
||||
pub fn native_menu<R: Runtime>(app: &AppHandle<R>, nodes: &[Node]) -> tauri::Result<Menu<R>> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// The tree before the window has sent anything (English words).
|
||||
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 key = format!("{s:?}");
|
||||
if LAST.lock().ok().is_some_and(|l| l.as_deref() == Some(key.as_str())) {
|
||||
return Ok(());
|
||||
}
|
||||
tray.set_tooltip(Some(tooltip_text(s)))?;
|
||||
crate::menu_panel::set_nodes(app, from_entries(&menu_model(s)));
|
||||
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() };
|
||||
tray.set_icon(Some(img))?;
|
||||
}
|
||||
if let Ok(mut l) = LAST.lock() {
|
||||
*l = Some(key);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,111 +1,22 @@
|
|||
//! 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
|
||||
//! private key never leaves the release machine, ~/.storebound-keys). Nothing installs without the owner's click in
|
||||
//! 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};
|
||||
|
||||
//! a native dialog (commands::update_install). Pure parts here so tests can pin them.
|
||||
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).
|
||||
pub const STABLE: &str = "https://storebound.dev/desktop/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.
|
||||
pub fn endpoint(channel: &str) -> &'static str {
|
||||
match channel {
|
||||
"beta" => BETA,
|
||||
"dev" => DEV,
|
||||
_ => STABLE,
|
||||
if channel == "beta" {
|
||||
BETA
|
||||
} else {
|
||||
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.
|
||||
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/")
|
||||
|
|
|
|||
|
|
@ -251,12 +251,6 @@ pub struct RefreshSettings {
|
|||
pub parallel: u8,
|
||||
/// Read app icons from the stores when importing (an extra request per app).
|
||||
pub icons: bool,
|
||||
/// Background reading of every app (status, releases, catalog, prices, listings, TestFlight, health, reviews,
|
||||
/// analytics, checks): on start, when the window shows again and every `every_minutes` while it is open.
|
||||
pub auto_read: bool,
|
||||
/// Minutes between background passes while the window is visible (only reads past their TTL run); 0 = only on
|
||||
/// start and when the window shows again.
|
||||
pub every_minutes: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -269,39 +263,9 @@ pub struct CacheSettings {
|
|||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct NotifySettings {
|
||||
/// Other release state changes (submitted, in review).
|
||||
pub review_state: bool,
|
||||
/// A version the store rejected.
|
||||
pub rejected: bool,
|
||||
/// A version that passed review (ready for release).
|
||||
pub approved: bool,
|
||||
/// A version that went live or started rolling out.
|
||||
pub live: bool,
|
||||
pub low_reviews: bool,
|
||||
/// A Play crash / ANR rate over the threshold, or a halted rollout.
|
||||
pub crash: bool,
|
||||
pub quiet_hours: QuietHours,
|
||||
}
|
||||
|
||||
/// No notification between `from` and `to` (HH:MM, local time; the window may cross midnight).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct QuietHours {
|
||||
pub enabled: bool,
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
impl Default for QuietHours {
|
||||
fn default() -> QuietHours {
|
||||
QuietHours { enabled: false, from: "23:00".into(), to: "08:00".into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// "HH:MM" with a valid hour and minute.
|
||||
pub fn valid_hhmm(s: &str) -> bool {
|
||||
let b = s.as_bytes();
|
||||
b.len() == 5 && b[2] == b':' && b.iter().enumerate().all(|(i, c)| i == 2 || c.is_ascii_digit()) && s[..2].parse::<u8>().is_ok_and(|h| h < 24) && s[3..].parse::<u8>().is_ok_and(|m| m < 60)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -310,7 +274,7 @@ pub struct Settings {
|
|||
pub refresh: RefreshSettings,
|
||||
pub cache: CacheSettings,
|
||||
pub notify: NotifySettings,
|
||||
/// Update channel (Settings > Updates): stable | dev (beta kept for saved states). crate::updates::endpoint.
|
||||
/// Update channel (placeholder until the updater ships): stable | beta.
|
||||
pub channel: String,
|
||||
}
|
||||
|
||||
|
|
@ -318,7 +282,7 @@ pub struct Settings {
|
|||
// build that lacks a newer setting keeps the rest.
|
||||
impl Default for RefreshSettings {
|
||||
fn default() -> RefreshSettings {
|
||||
RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true, auto_read: true, every_minutes: 15 }
|
||||
RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -330,7 +294,7 @@ impl Default for CacheSettings {
|
|||
|
||||
impl Default for NotifySettings {
|
||||
fn default() -> NotifySettings {
|
||||
NotifySettings { review_state: true, rejected: true, approved: true, live: true, low_reviews: true, crash: true, quiet_hours: QuietHours::default() }
|
||||
NotifySettings { review_state: true, low_reviews: true, crash: true }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -342,41 +306,19 @@ impl Default for Settings {
|
|||
|
||||
pub const AUTO_MINUTES: &[u32] = &[0, 15, 30, 60, 180, 720];
|
||||
pub const KEEP_DAYS: &[u32] = &[0, 7, 30, 90, 365];
|
||||
pub const EVERY_MINUTES: &[u32] = &[0, 5, 15, 30, 60];
|
||||
|
||||
pub fn check_settings(s: &Settings) -> Result<(), String> {
|
||||
if !AUTO_MINUTES.contains(&s.refresh.auto_minutes) {
|
||||
return Err("refresh: 0 (off), 15, 30, 60, 180 or 720 minutes".into());
|
||||
}
|
||||
if !EVERY_MINUTES.contains(&s.refresh.every_minutes) {
|
||||
return Err("background reading: 0 (only on start), 5, 15, 30 or 60 minutes".into());
|
||||
}
|
||||
if !(1..=8).contains(&s.refresh.parallel) {
|
||||
return Err("parallel reads: 1 to 8".into());
|
||||
}
|
||||
if !KEEP_DAYS.contains(&s.cache.keep_days) {
|
||||
return Err("keep saved reads: 0 (always), 7, 30, 90 or 365 days".into());
|
||||
}
|
||||
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());
|
||||
}
|
||||
if !crate::updates::CHANNELS.contains(&s.channel.as_str()) {
|
||||
return Err("channel: stable or dev".into());
|
||||
if !["stable", "beta"].contains(&s.channel.as_str()) {
|
||||
return Err("channel: stable or beta".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The storebound version an app folder pins: `storebound` in its package.json devDependencies or dependencies.
|
||||
pub fn pinned_storebound(dir: &std::path::Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(dir.join("package.json")).ok()?;
|
||||
let v: Value = serde_json::from_str(&text).ok()?;
|
||||
["devDependencies", "dependencies"].iter().find_map(|k| v.get(*k)?.get("storebound")?.as_str().map(str::to_string))
|
||||
}
|
||||
|
||||
/// Whether a pinned spec names another version than the app's (its bundled CLI). `^0.8.0`, `~0.8.0`, `=0.8.0` and
|
||||
/// `0.8.0` name 0.8.0; tags, ranges like `*`, `latest`, `file:` / `link:` / `workspace:` specs name none (no notice).
|
||||
pub fn pin_differs(spec: &str, app: &str) -> bool {
|
||||
let s = spec.trim().trim_start_matches(['^', '~', '=', 'v']);
|
||||
let looks = s.split('.').count() == 3 && s.split(['.', '-']).take(3).all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
|
||||
looks && s != app
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "storebound",
|
||||
"mainBinaryName": "storebound-desktop",
|
||||
"version": "0.8.78",
|
||||
"version": "0.1.0",
|
||||
"identifier": "dev.storebound.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
|
@ -20,8 +20,7 @@
|
|||
"minWidth": 880,
|
||||
"minHeight": 560,
|
||||
"resizable": true,
|
||||
"center": true,
|
||||
"visible": false
|
||||
"center": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
|
|
@ -50,7 +49,7 @@
|
|||
"form-action": "'none'"
|
||||
},
|
||||
"freezePrototype": true,
|
||||
"capabilities": ["main-window", "card-window", "menu-window"]
|
||||
"capabilities": ["main-window"]
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
|
@ -58,7 +57,6 @@
|
|||
"targets": "all",
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "Every game's releases on both stores in one window",
|
||||
"longDescription": "storebound desktop: store listings, builds, in-app purchases, reviews and releases of mobile apps and games on Google Play and the App Store, in one window. Every write shows a dry run first, and public steps wait for your confirmation.",
|
||||
"copyright": "MIT license, storebound contributors",
|
||||
"externalBin": ["binaries/storebound"],
|
||||
"createUpdaterArtifacts": false,
|
||||
|
|
@ -88,7 +86,6 @@
|
|||
},
|
||||
"updater": {
|
||||
"endpoints": ["https://storebound.dev/desktop/latest.json"],
|
||||
"windows": { "installMode": "quiet" },
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ0Rjc4QTc4RDlFRjM4MkEKUldRcU9PL1plSXIzUkJtb2x0L2Z4MTA4bTg5UU5FVW5kUlRGcnVjangwQ0JNb2VGYjcveGhydlcK"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@ const FAKE_PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PR
|
|||
|
||||
#[test]
|
||||
fn shown_metadata_carries_no_secret() {
|
||||
let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into(), studio: Some("s1".into()), profile: Some("studio".into()), developer_id: None };
|
||||
let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into(), studio: Some("s1".into()) };
|
||||
let v = serde_json::to_value(&a).unwrap();
|
||||
assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label", "profile", "studio"]);
|
||||
assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label", "studio"]);
|
||||
assert_eq!(v["kind"], "play");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,178 +0,0 @@
|
|||
//! Fix with AI (src/ai_fix.rs): the prompt, the dirty-tree refusal, Undo restricted to the run's own files, the
|
||||
//! timeout and kill by PID, and that claude only ever gets the file tools.
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
#[cfg(unix)]
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use storebound_desktop::ai_fix::*;
|
||||
|
||||
fn finding() -> AiFinding {
|
||||
AiFinding {
|
||||
rule: "ats".into(),
|
||||
guideline: "Apple: App Transport Security".into(),
|
||||
store: "apple".into(),
|
||||
title: "NSAllowsArbitraryLoads is true".into(),
|
||||
evidence: vec![
|
||||
Evidence { file: "ios/App/Info.plist".into(), line: 42, text: Some("NSAllowsArbitraryLoads\ttrue".into()) },
|
||||
Evidence { file: "../outside.txt".into(), line: 1, text: None },
|
||||
],
|
||||
fix: "Remove NSAllowsArbitraryLoads; add exception domains only where needed.".into(),
|
||||
skill: "review-rejections".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("sb-aifix-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let ok = Command::new("git").current_dir(dir).args(args).env("GIT_AUTHOR_NAME", "T").env("GIT_AUTHOR_EMAIL", "t@example.com").env("GIT_COMMITTER_NAME", "T").env("GIT_COMMITTER_EMAIL", "t@example.com").output().unwrap();
|
||||
assert!(ok.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&ok.stderr));
|
||||
}
|
||||
|
||||
fn repo(name: &str) -> PathBuf {
|
||||
let d = tmp(name);
|
||||
git(&d, &["init", "-q"]);
|
||||
fs::create_dir_all(d.join("app")).unwrap();
|
||||
fs::write(d.join("app/Info.plist"), "a\n").unwrap();
|
||||
fs::write(d.join("app/Other.swift"), "b\n").unwrap();
|
||||
git(&d, &["add", "."]);
|
||||
git(&d, &["commit", "-q", "-m", "init"]);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_names_the_finding_and_the_limits() {
|
||||
let p = build_prompt(&finding()).unwrap();
|
||||
for s in ["ats", "NSAllowsArbitraryLoads is true", "ios/App/Info.plist:42", "review-rejections", "Change only what this finding needs", "Do not run commands", "commit or push", "Never invent an answer"] {
|
||||
assert!(p.contains(s), "missing {s}");
|
||||
}
|
||||
// evidence outside the folder is left out; control characters are flattened
|
||||
assert!(!p.contains("outside.txt"));
|
||||
assert!(!p.contains('\t'));
|
||||
let mut bad = finding();
|
||||
bad.rule = "ats; rm -rf".into();
|
||||
assert!(build_prompt(&bad).is_err());
|
||||
bad = finding();
|
||||
bad.store = "web".into();
|
||||
assert!(build_prompt(&bad).is_err());
|
||||
bad = finding();
|
||||
bad.title = "x".repeat(5000);
|
||||
assert!(build_prompt(&bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_gets_only_the_file_tools() {
|
||||
let a = claude_args("hi");
|
||||
assert_eq!(a[0], "-p");
|
||||
let allowed = &a[a.iter().position(|x| x == "--allowedTools").unwrap() + 1];
|
||||
assert_eq!(allowed, "Read,Edit,Write,Grep,Glob");
|
||||
let denied = &a[a.iter().position(|x| x == "--disallowedTools").unwrap() + 1];
|
||||
for t in ["Bash", "WebFetch", "WebSearch", "Task"] {
|
||||
assert!(denied.split(',').any(|x| x == t), "{t} not denied");
|
||||
}
|
||||
assert!(!a.iter().any(|x| x.contains("dangerously") || x == "bypassPermissions"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_claude_in_the_usual_folders() {
|
||||
let d = tmp("which");
|
||||
let home = d.join("home");
|
||||
fs::create_dir_all(home.join(".local/bin")).unwrap();
|
||||
let dirs = search_path(Some(""), Some(&home));
|
||||
assert!(find_claude_in(&dirs).is_none() || !find_claude_in(&dirs).unwrap().starts_with(&home));
|
||||
let name = if cfg!(windows) { "claude.exe" } else { "claude" };
|
||||
fs::write(home.join(".local/bin").join(name), "").unwrap();
|
||||
assert_eq!(find_claude_in(&dirs).unwrap(), home.join(".local/bin").join(name));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirty_tree_is_reported_and_clean_tree_is_empty() {
|
||||
let d = repo("dirty");
|
||||
let (_, clean) = status(&d.join("app")).unwrap();
|
||||
assert!(clean.is_empty());
|
||||
fs::write(d.join("app/Other.swift"), "changed\n").unwrap();
|
||||
fs::write(d.join("app/new.txt"), "n\n").unwrap();
|
||||
let (_, dirty) = status(&d.join("app")).unwrap();
|
||||
let mut paths: Vec<(String, String)> = dirty.iter().map(|c| (c.path.clone(), c.status.clone())).collect();
|
||||
paths.sort();
|
||||
assert_eq!(paths, vec![("app/Other.swift".into(), "M".into()), ("app/new.txt".into(), "??".into())]);
|
||||
// not a repository: refused with a reason
|
||||
assert!(status(&tmp("nogit")).unwrap_err().contains("git"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_restores_only_the_runs_files() {
|
||||
let d = repo("undo");
|
||||
// the run changed Info.plist and created new.txt; Other.swift was changed later by the owner, not by the run
|
||||
fs::write(d.join("app/Info.plist"), "fixed\n").unwrap();
|
||||
fs::write(d.join("app/new.txt"), "n\n").unwrap();
|
||||
let (_, run) = status(&d.join("app")).unwrap();
|
||||
fs::write(d.join("app/Other.swift"), "owner edit\n").unwrap();
|
||||
let diff_text = diff(&d, &run);
|
||||
assert!(diff_text.contains("+fixed") && diff_text.contains("+++ b/app/new.txt"));
|
||||
let done = undo(&d, &run).unwrap();
|
||||
assert_eq!(done.len(), 2);
|
||||
assert_eq!(fs::read_to_string(d.join("app/Info.plist")).unwrap(), "a\n");
|
||||
assert!(!d.join("app/new.txt").exists());
|
||||
assert_eq!(fs::read_to_string(d.join("app/Other.swift")).unwrap(), "owner edit\n");
|
||||
// paths outside the repository never reach git or the file system
|
||||
let evil = vec![Change { path: "../x".into(), status: "M".into() }, Change { path: "/etc/hosts".into(), status: "??".into() }, Change { path: "-f".into(), status: "M".into() }];
|
||||
assert_eq!(undo_plan(&evil), (vec![], vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_parser_handles_renames_and_new_files() {
|
||||
let z = "R new.txt\0old.txt\0 M a b.txt\0?? n/x.txt\0";
|
||||
assert_eq!(parse_status(z), vec![
|
||||
Change { path: "new.txt".into(), status: "R".into() },
|
||||
Change { path: "a b.txt".into(), status: "M".into() },
|
||||
Change { path: "n/x.txt".into(), status: "??".into() },
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_json_lines_become_progress() {
|
||||
assert_eq!(progress_line(r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Edit","input":{"file_path":"ios/App/Info.plist"}}]}}"#).unwrap(), "Edit ios/App/Info.plist");
|
||||
assert_eq!(progress_line(r#"{"type":"result","result":"Removed NSAllowsArbitraryLoads."}"#).unwrap(), "Removed NSAllowsArbitraryLoads.");
|
||||
assert!(progress_line(r#"{"type":"system","subtype":"init"}"#).is_none());
|
||||
assert!(progress_line("not json").is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn timeout_kills_the_process_group_with_heartbeats() {
|
||||
let mut c = Command::new("sh");
|
||||
c.args(["-c", "sleep 30 & sleep 30; echo never"]);
|
||||
let t = Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let o = run(c, "t-timeout", Duration::from_millis(800), Duration::from_millis(300), |l| lines.push(l.to_string())).unwrap();
|
||||
assert!(t.elapsed() < Duration::from_secs(10));
|
||||
assert!(o.timed_out);
|
||||
assert!(lines.iter().any(|l| l.starts_with("still working")));
|
||||
assert!(lines.iter().any(|l| l.starts_with("timed out")));
|
||||
assert!(!lines.iter().any(|l| l.contains("never")));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancel_kills_by_pid() {
|
||||
let h = std::thread::spawn(|| {
|
||||
let mut c = Command::new("sh");
|
||||
c.args(["-c", "sleep 30"]);
|
||||
run(c, "t-cancel", Duration::from_secs(60), Duration::from_secs(60), |_| {}).unwrap()
|
||||
});
|
||||
let end = Instant::now() + Duration::from_secs(5);
|
||||
while !cancel("t-cancel") {
|
||||
assert!(Instant::now() < end, "never started");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let o = h.join().unwrap();
|
||||
assert!(o.cancelled && !o.timed_out);
|
||||
assert!(!cancel("t-cancel"));
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
//! 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);
|
||||
}
|
||||
|
|
@ -32,18 +32,14 @@ fn app_folder_paths() {
|
|||
assert!(openable(Path::new("store/renders/index.html"), false));
|
||||
assert!(openable(Path::new("store/renders"), true));
|
||||
assert!(!openable(Path::new("store/renders/run.sh"), false));
|
||||
assert!(openable(Path::new(".storebound/reports/readiness-2026-10-18.html"), false));
|
||||
assert!(!openable(Path::new(".storebound/reports/readiness-2026-10-18.sh"), false));
|
||||
assert!(!openable(Path::new(".storebound/credentials.json"), false));
|
||||
assert!(!openable(Path::new("other/reports/readiness-2026-10-18.html"), false));
|
||||
assert!(!openable(Path::new("store/prices.csv"), false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_folder_methods_and_big_reads() {
|
||||
assert_eq!(NEW_FOLDER_METHODS, &["project.init", "import.fastlane"]);
|
||||
assert_eq!(NO_CACHE_METHODS, &["project.render", "art.thumb"]);
|
||||
for c in ["project_import_fastlane", "export_save", "price_sheet_pick", "image_pick", "project_reveal"] {
|
||||
assert_eq!(NO_CACHE_METHODS, &["project.render"]);
|
||||
for c in ["project_import_fastlane", "export_save", "price_sheet_pick", "project_reveal"] {
|
||||
assert!(COMMANDS.contains(&c), "{c}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@
|
|||
//! after a dialog that names the action on its button and says users see it at once. Tokens are bound to exactly the
|
||||
//! method and the { project, args } sent (the same vector as the TypeScript side checks).
|
||||
use serde_json::json;
|
||||
use storebound_desktop::commands::{console_fill_dialog, dialog_labels, dialog_summary, owner_summary, summary_for};
|
||||
use storebound_desktop::commands::{console_fill_dialog, dialog_labels, dialog_summary, owner_summary};
|
||||
use storebound_desktop::confirm::{canonical, mac, mint};
|
||||
use storebound_desktop::policy::{sanitize_js_call, Kind, CONSOLE_FILL, CONSOLE_FILL_NOTE, SUBMIT_METHODS};
|
||||
use storebound_desktop::policy::{sanitize_js_call, Kind, CONSOLE_FILL, CONSOLE_FILL_NOTE};
|
||||
|
||||
#[test]
|
||||
fn owner_actions_are_dry_runs_from_the_window() {
|
||||
|
|
@ -18,27 +18,6 @@ fn owner_actions_are_dry_runs_from_the_window() {
|
|||
assert_eq!(w["dryRun"], json!(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_only_apps_take_only_the_listing_text_write() {
|
||||
use storebound_desktop::policy::{store_only_write, STORE_ONLY_WRITES};
|
||||
assert_eq!(STORE_ONLY_WRITES, &["listing.set"]);
|
||||
assert!(store_only_write("listing.set", Some(Kind::Write)));
|
||||
// the folder writes, owner actions and reads are not store-only writes
|
||||
for m in ["play.listing", "apple.listing", "project.edit", "play.images"] {
|
||||
assert!(!store_only_write(m, Some(Kind::Write)), "{m}");
|
||||
}
|
||||
assert!(!store_only_write("listing.set", Some(Kind::Owner)));
|
||||
assert!(!store_only_write("listing.set", Some(Kind::Read)));
|
||||
// a dry run from the window, like every write
|
||||
let p = sanitize_js_call("listing.set", Some(Kind::Write), &json!({ "args": { "store": "play", "lang": "en-US", "fields": "{\"short\":\"x\"}" } })).unwrap();
|
||||
assert_eq!(p["dryRun"], json!(true));
|
||||
// the token binds the store ids instead of a folder: another app's ids give another token
|
||||
let secret = [9u8; 32];
|
||||
let a = json!({ "virtual": { "name": "com.example.a", "play": { "packageName": "com.example.a" } }, "args": { "lang": "en-US" } });
|
||||
let b = json!({ "virtual": { "name": "com.example.b", "play": { "packageName": "com.example.b" } }, "args": { "lang": "en-US" } });
|
||||
assert_ne!(mint(&secret, "listing.set", &a, 1_000, "n1").unwrap(), mint(&secret, "listing.set", &b, 1_000, "n1").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_dialogs_name_the_action() {
|
||||
let (title, ok) = dialog_labels(Kind::Owner, "Change the Play staged rollout");
|
||||
|
|
@ -50,25 +29,6 @@ fn owner_dialogs_name_the_action() {
|
|||
assert!(dialog_summary("Push", "d", "A", true, false).contains("not public until you submit"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submit_for_review_is_an_owner_action_with_its_own_dialog() {
|
||||
assert_eq!(SUBMIT_METHODS, &["owner.apple_submit", "owner.apple_resubmit", "owner.apple_iap_submit", "owner.play_production"]);
|
||||
for m in SUBMIT_METHODS {
|
||||
// a dry run from the window, whatever it sends; the real run only through write_with_confirm
|
||||
let p = sanitize_js_call(m, Some(Kind::Owner), &json!({ "args": { "build": "52" } })).unwrap();
|
||||
assert_eq!(p["dryRun"], json!(true));
|
||||
for bad in [json!({ "dryRun": false }), json!({ "confirmToken": "sbt1.x" }), json!({ "args": {}, "project": "/x" })] {
|
||||
assert!(sanitize_js_call(m, Some(Kind::Owner), &bad).is_err(), "{m} {bad}");
|
||||
}
|
||||
let s = summary_for(m, Kind::Owner, "Submit for App Review", "Sends the version.", "Prism Puddle", true, false);
|
||||
assert!(s.contains("Prism Puddle") && s.contains("store's review") && s.contains("go live without another click") && s.contains("press the button"), "{s}");
|
||||
}
|
||||
// other owner actions keep their summary, writes theirs
|
||||
assert!(summary_for("owner.play_rollout", Kind::Owner, "T", "d", "A", true, false).contains("right away"));
|
||||
assert!(summary_for("play.listing", Kind::Write, "T", "d", "A", true, false).contains("not public until you submit"));
|
||||
assert_eq!(dialog_labels(Kind::Owner, "Submit for App Review").1, "Yes: Submit for App Review");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_bind_method_project_and_args_of_each_write() {
|
||||
let secret = [9u8; 32];
|
||||
|
|
@ -81,9 +41,6 @@ fn tokens_bind_method_project_and_args_of_each_write() {
|
|||
("owner.play_rollout", json!({ "action": "percent", "percent": 50 })),
|
||||
("owner.ios_phased", json!({ "action": "resume", "version": "2.3.0" })),
|
||||
("owner.reply_send", json!({ "file": "play-r-p1.md" })),
|
||||
("owner.apple_submit", json!({ "build": "52", "version": "2.4.0" })),
|
||||
("owner.apple_resubmit", json!({ "build": "53", "resolve_iaps": true })),
|
||||
("owner.play_production", json!({ "version_code": "24", "status": "inProgress", "percent": 10 })),
|
||||
];
|
||||
for (method, args) in writes {
|
||||
let bound = json!({ "project": "/apps/prism", "args": args });
|
||||
|
|
@ -115,7 +72,6 @@ fn console_fill_is_a_dry_run_from_the_window_and_its_dialog_lists_the_answers()
|
|||
assert_eq!(title, "Fill in console: Age rating");
|
||||
assert_eq!(ok, "Open the browser");
|
||||
assert!(text.contains("Prism Puddle") && text.contains(CONSOLE_FILL_NOTE));
|
||||
assert!(text.contains("uses storebound's own browser profile") && text.contains("cookies are never copied"));
|
||||
assert!(text.contains("- Cartoon violence: None") && text.contains("- Simulated gambling: you answer this"));
|
||||
let (_, empty, _) = console_fill_dialog("A", &json!(null));
|
||||
assert!(empty.contains("every field is yours"));
|
||||
|
|
|
|||
|
|
@ -18,10 +18,9 @@ fn conf() -> Value {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn one_version_with_the_cli() {
|
||||
fn one_version_from_the_root_package_json() {
|
||||
let pkg: Value = serde_json::from_str(&fs::read_to_string(root().join("../../../package.json")).unwrap()).unwrap();
|
||||
// one product, one number: the desktop app has the npm CLI's version (its bundled sidecar is that CLI)
|
||||
let want = pkg["version"].as_str().expect("package.json version");
|
||||
let want = pkg["desktopVersion"].as_str().expect("package.json desktopVersion");
|
||||
assert_eq!(env!("CARGO_PKG_VERSION"), want, "Cargo.toml (bun tools/desktop-version.ts --set {want})");
|
||||
assert_eq!(conf()["version"], want, "tauri.conf.json");
|
||||
let app: Value = serde_json::from_str(&fs::read_to_string(root().join("../package.json")).unwrap()).unwrap();
|
||||
|
|
@ -41,13 +40,10 @@ fn updater_has_a_real_minisign_key_and_only_storebound_dev() {
|
|||
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
|
||||
assert_eq!(c["bundle"]["createUpdaterArtifacts"], false);
|
||||
assert_eq!(c["plugins"]["updater"]["windows"]["installMode"], "quiet");
|
||||
for ch in ["stable", "beta", "dev", "nightly", ""] {
|
||||
for ch in ["stable", "beta", "nightly", ""] {
|
||||
assert!(updates::endpoint_allowed(&Url::parse(updates::endpoint(ch)).unwrap()), "{ch}");
|
||||
}
|
||||
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);
|
||||
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}");
|
||||
|
|
@ -58,12 +54,12 @@ fn updater_has_a_real_minisign_key_and_only_storebound_dev() {
|
|||
#[test]
|
||||
fn open_deep_link_takes_one_plain_absolute_path() {
|
||||
let p = |s: &str| deep_link_open_path(&Url::parse(s).unwrap());
|
||||
let abs = if cfg!(windows) { "C:%5Cgames%5Cdemo-app" } else { "%2FUsers%2Fyou%2Fgames%2Fdemo-app" };
|
||||
let want = if cfg!(windows) { "C:\\games\\demo-app" } else { "/Users/you/games/demo-app" };
|
||||
let abs = if cfg!(windows) { "C:%5Cgames%5CDemo App" } else { "%2FUsers%2Fyou%2Fgames%2FDemo App" };
|
||||
let want = if cfg!(windows) { "C:\\games\\Demo App" } else { "/Users/you/games/Demo App" };
|
||||
assert_eq!(p(&format!("storebound://open?path={abs}")), Some(PathBuf::from(want)));
|
||||
assert_eq!(p(&format!("storebound://open/?path={abs}")), Some(PathBuf::from(want)));
|
||||
for bad in [
|
||||
"storebound://open?path=games%2Fdemo-app".to_string(),
|
||||
"storebound://open?path=games%2FDemo App".to_string(),
|
||||
"storebound://open?path=".to_string(),
|
||||
"storebound://open".to_string(),
|
||||
format!("storebound://open?path={abs}&path={abs}"),
|
||||
|
|
@ -106,49 +102,3 @@ fn deep_links_to_folders_ask_before_adding() {
|
|||
let body = &cmds[at..];
|
||||
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(&[]));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,262 +0,0 @@
|
|||
//! One product per machine: the app's accounts are the CLI's credential profiles (~/.storebound/credentials), keychain
|
||||
//! accounts of earlier versions move there once, the app folder list is the CLI's (~/.storebound/projects.json), and
|
||||
//! a folder that pins another storebound version says so. No real keys anywhere.
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde_json::json;
|
||||
use storebound_desktop::accounts::{Account, AccountKind, Secret, SecretStore};
|
||||
use storebound_desktop::profiles::{self, ProfileStore};
|
||||
use storebound_desktop::registry::{self, Entry};
|
||||
use storebound_desktop::store::{Project, State};
|
||||
use storebound_desktop::workspace::{pin_differs, pinned_storebound};
|
||||
|
||||
const PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PRIVATE KEY-----\n";
|
||||
|
||||
fn sa(email: &str) -> String {
|
||||
json!({ "type": "service_account", "client_email": email, "private_key": PEM }).to_string()
|
||||
}
|
||||
|
||||
fn apple(key: &str) -> Secret {
|
||||
Secret::Apple { key_id: key.into(), issuer_id: "00000000-0000-0000-0000-000000000000".into(), p8: PEM.into() }
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MapStore(Mutex<HashMap<String, Secret>>);
|
||||
impl SecretStore for MapStore {
|
||||
fn set(&self, id: &str, s: &Secret) -> Result<(), String> {
|
||||
self.0.lock().unwrap().insert(id.into(), s.clone());
|
||||
Ok(())
|
||||
}
|
||||
fn get(&self, id: &str) -> Result<Secret, String> {
|
||||
self.0.lock().unwrap().get(id).cloned().ok_or_else(|| "no entry".into())
|
||||
}
|
||||
fn delete(&self, id: &str) -> Result<(), String> {
|
||||
self.0.lock().unwrap().remove(id);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn account(id: &str, label: &str, kind: AccountKind, profile: Option<&str>) -> Account {
|
||||
Account { id: id.into(), label: label.into(), kind, created: "2026-10-01T00:00:00Z".into(), studio: Some("s1".into()), profile: profile.map(str::to_string), developer_id: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_match_the_cli() {
|
||||
// cli/lib/workspace.ts accountId and cli/lib/registry.ts folderId give the same values
|
||||
assert_eq!(profiles::account_id(AccountKind::Apple, "acme"), "747351dbf2569d17");
|
||||
assert_eq!(profiles::account_id(AccountKind::Play, "default"), "82a8c2561d950999");
|
||||
assert_eq!(registry::folder_id("/w/star-dash"), "c27311c5023dc3ba");
|
||||
assert!(profiles::valid_name("default") && profiles::valid_name("acme-games.2") && !profiles::valid_name("../x") && !profiles::valid_name("-a"));
|
||||
assert_eq!(profiles::slug("Acme Games: Play!"), "acme-games-play");
|
||||
assert_eq!(profiles::slug("???"), "account");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_round_trips_in_the_cli_format_with_private_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = ProfileStore::new(dir.path().join("credentials"), None);
|
||||
store.save("acme", "Acme", &apple("ABCDE12345")).unwrap();
|
||||
store.save("acme", "Acme", &Secret::Play { service_account: sa("bot@example.com") }).unwrap();
|
||||
let m = store.read("acme").unwrap();
|
||||
assert_eq!(m["ASC_P8"], "acme/app-store-connect.p8");
|
||||
assert_eq!(m["PLAY_SERVICE_ACCOUNT"], "acme/play-service-account.json");
|
||||
assert_eq!(m["label"], "Acme");
|
||||
assert!(!serde_json::to_string(&m).unwrap().contains("not-a-real-key"), "keys stay in their own files");
|
||||
assert_eq!(store.secret("acme", AccountKind::Apple).unwrap(), apple("ABCDE12345"));
|
||||
assert_eq!(store.kinds("acme"), vec![AccountKind::Apple, AccountKind::Play]);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode(&store.dir.join("acme.json")), 0o600);
|
||||
assert_eq!(mode(&store.dir.join("acme").join(profiles::P8_FILE)), 0o600);
|
||||
assert_eq!(mode(&store.dir.join("acme")), 0o700);
|
||||
assert_eq!(mode(&store.dir), 0o700);
|
||||
}
|
||||
// the same key again lands in the same profile; another key in a profile of its own
|
||||
assert_eq!(store.place("Anything", &apple("ABCDE12345")), "acme");
|
||||
assert_eq!(store.place("Acme", &apple("ZZZZZ99999")), "acme-apple");
|
||||
assert_eq!(store.place("Acme", &Secret::Play { service_account: sa("bot@example.com") }), "acme");
|
||||
// a profile the CLI wrote by hand, with an absolute key path and no ASC_P8
|
||||
std::fs::write(store.dir.join("cli.json"), json!({ "ASC_KEY_ID": "CLI0000000", "ASC_ISSUER_ID": "i" }).to_string()).unwrap();
|
||||
let mut creds = serde_json::Map::new();
|
||||
store.secret("cli", AccountKind::Apple).unwrap().to_credentials(&mut creds);
|
||||
assert_eq!(creds.keys().cloned().collect::<Vec<_>>(), vec!["ASC_ISSUER_ID", "ASC_KEY_ID"], "no ASC_P8: the CLI looks in ~/.appstoreconnect itself");
|
||||
// removing one store archives its key file; the last store archives the profile
|
||||
store.remove("acme", AccountKind::Play, "20261013T000000Z").unwrap();
|
||||
assert_eq!(store.kinds("acme"), vec![AccountKind::Apple]);
|
||||
assert!(store.dir.join(".removed/acme-20261013T000000Z").join(profiles::PLAY_FILE).is_file());
|
||||
store.remove("acme", AccountKind::Apple, "20261013T000001Z").unwrap();
|
||||
assert!(!store.names().contains(&"acme".to_string()));
|
||||
assert!(store.dir.join(".removed/acme-20261013T000001Z/acme.json").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keychain_accounts_move_into_profiles_once_and_cli_profiles_show_up() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = ProfileStore::new(dir.path().join("credentials"), None);
|
||||
// the CLI already imported the shared account ("accounts import" -> profile default)
|
||||
store.save("default", "", &apple("ABCDE12345")).unwrap();
|
||||
store.save("default", "", &Secret::Play { service_account: sa("bot@example.com") }).unwrap();
|
||||
let legacy = MapStore::default();
|
||||
legacy.set("0123456789abcdef", &Secret::Play { service_account: sa("bot@example.com") }).unwrap();
|
||||
legacy.set("fedcba9876543210", &apple("SIDE000000")).unwrap();
|
||||
let mut accs = vec![
|
||||
account("0123456789abcdef", "Example Games Play", AccountKind::Play, None),
|
||||
account("fedcba9876543210", "Side project", AccountKind::Apple, None),
|
||||
account("00112233445566ff", "Lost key", AccountKind::Apple, None),
|
||||
];
|
||||
let r = profiles::sync(&mut accs, &store, &legacy, "2026-10-13T00:00:00Z");
|
||||
// the same service account as the CLI's profile: that profile; the other key: a profile named after its label
|
||||
assert_eq!(accs[0].profile.as_deref(), Some("default"));
|
||||
assert_eq!(accs[1].profile.as_deref(), Some("side-project"));
|
||||
assert_eq!(accs[2].profile, None, "no keychain entry: stays, said in the log");
|
||||
assert_eq!(accs[0].studio.as_deref(), Some("s1"), "id, label, studio stay");
|
||||
assert!(legacy.get("0123456789abcdef").is_err() && legacy.get("fedcba9876543210").is_err(), "moved entries leave the keychain");
|
||||
assert_eq!(r.migrated.len(), 2);
|
||||
assert_eq!(r.notes.len(), 1);
|
||||
// the CLI profile's Apple key had no app account yet: it comes in with the CLI workspace's id
|
||||
let added: Vec<_> = accs.iter().skip(3).map(|a| (a.id.clone(), a.kind, a.profile.clone())).collect();
|
||||
assert_eq!(added, vec![(profiles::account_id(AccountKind::Apple, "default"), AccountKind::Apple, Some("default".into()))]);
|
||||
// a second start changes nothing
|
||||
let again = profiles::sync(&mut accs, &store, &legacy, "2026-10-14T00:00:00Z");
|
||||
assert!(!again.changed());
|
||||
assert_eq!(accs.len(), 4);
|
||||
}
|
||||
|
||||
fn project(id: &str, path: &str, play: Option<&str>) -> Project {
|
||||
Project { id: id.into(), path: path.into(), name: id.into(), play_account: play.map(str::to_string), apple_account: None, added: String::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_folder_list_is_the_machines() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("projects.json");
|
||||
let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", "/w/star-dash", Some("acc"))], ..State::default() };
|
||||
// first start: the app's list becomes the shared one
|
||||
assert!(!registry::sync(&mut st, &file).unwrap());
|
||||
assert_eq!(registry::read(&file).unwrap()[0].id, "aaaaaaaaaaaaaaaa");
|
||||
// the CLI adds a folder (storebound desktop / apps add): the app shows it, the first keeps its accounts
|
||||
let mut list = registry::read(&file).unwrap();
|
||||
list.push(Entry { id: registry::folder_id("/w/demo-game"), path: "/w/demo-game".into(), name: "demo-game".into(), added: "t".into() });
|
||||
registry::write(&file, &list).unwrap();
|
||||
assert!(registry::sync(&mut st, &file).unwrap());
|
||||
assert_eq!(st.projects.iter().map(|p| p.path.as_str()).collect::<Vec<_>>(), vec!["/w/star-dash", "/w/demo-game"]);
|
||||
assert_eq!(st.projects[0].play_account.as_deref(), Some("acc"));
|
||||
// the CLI removes one (apps remove): it leaves the app with its overrides
|
||||
st.overrides.ignored.push(format!("project:{}", registry::folder_id("/w/demo-game")));
|
||||
registry::write(&file, &list[..1]).unwrap();
|
||||
assert!(registry::sync(&mut st, &file).unwrap());
|
||||
assert_eq!(st.projects.len(), 1);
|
||||
assert!(st.overrides.ignored.is_empty());
|
||||
// the app adds one; a folder another tool added meanwhile is kept
|
||||
st.projects.push(project("bbbbbbbbbbbbbbbb", "/w/third", None));
|
||||
registry::write(&file, &[list[0].clone(), Entry { id: registry::folder_id("/w/cli"), path: "/w/cli".into(), name: "cli".into(), added: String::new() }]).unwrap();
|
||||
registry::publish(&st, &file, &[]).unwrap();
|
||||
let paths: Vec<String> = registry::read(&file).unwrap().into_iter().map(|e| e.path).collect();
|
||||
assert_eq!(paths, vec!["/w/star-dash", "/w/third", "/w/cli"]);
|
||||
// bad entries are dropped, not the whole file
|
||||
assert_eq!(registry::parse(r#"{"projects":[{"path":"rel"},{"path":"/a","id":"XYZ"},{"path":"/a"}]}"#).iter().map(|e| e.id.clone()).collect::<Vec<_>>(), vec![registry::folder_id("/a")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_only_apps_join_their_profiles_account_and_survive_folder_writes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("projects.json");
|
||||
// as `storebound apps add --store apple --app-id 6400000999 --account teamA` and a Play one without a profile wrote it
|
||||
std::fs::write(&file, r#"{"version":1,"projects":[],"storeApps":[
|
||||
{"id":"x","store":"apple","appId":"6400000999","account":"teamA","name":"Example Aquarium","bundleId":"com.example.aquarium","added":"t"},
|
||||
{"store":"play","appId":"com.example.legacy","name":"Legacy"},
|
||||
{"store":"apple","appId":"not-a-number"}]}"#).unwrap();
|
||||
let apps = registry::read_store_apps(&file);
|
||||
assert_eq!(apps.iter().map(|a| a.app_id.as_str()).collect::<Vec<_>>(), vec!["6400000999", "com.example.legacy"]);
|
||||
assert_eq!(apps[1].bundle_id.as_deref(), Some("com.example.legacy"));
|
||||
// the app writes its folder list: the store-only entries stay
|
||||
let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", "/w/star-dash", None)], ..State::default() };
|
||||
registry::publish(&st, &file, &[]).unwrap();
|
||||
assert_eq!(registry::read_store_apps(&file).len(), 2);
|
||||
assert!(registry::sync(&mut st, &file).is_ok());
|
||||
assert_eq!(registry::read_store_apps(&file).len(), 2);
|
||||
// an account of profile teamA that never listed its apps: the entry shows as its app, read-only, no folder
|
||||
let v = registry::with_store_only(None, "apple", Some("teamA"), false, &apps, "t").unwrap();
|
||||
assert_eq!(v["store"], "ios");
|
||||
assert_eq!(v["apps"][0]["id"], "6400000999");
|
||||
assert_eq!(v["apps"][0]["bundleId"], "com.example.aquarium");
|
||||
assert_eq!(v["apps"][0]["registered"], true);
|
||||
// an account of another profile gets nothing; the list the store returned is kept, the entry not doubled
|
||||
assert_eq!(registry::with_store_only(None, "apple", Some("teamB"), false, &apps, "t"), None);
|
||||
let listed = serde_json::json!({ "store": "ios", "apps": [{ "id": "6400000999", "name": "From the store" }], "warnings": [], "at": "t" });
|
||||
assert_eq!(registry::with_store_only(Some(listed.clone()), "apple", Some("teamA"), false, &apps, "t"), Some(listed));
|
||||
// no profile named: the only Play account takes it
|
||||
let p = registry::with_store_only(None, "play", Some("any"), true, &apps, "t").unwrap();
|
||||
assert_eq!(p["apps"][0]["name"], "Legacy");
|
||||
assert_eq!(registry::with_store_only(None, "play", Some("any"), false, &apps, "t"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_pins_another_storebound_says_so() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(pinned_storebound(dir.path()), None);
|
||||
std::fs::write(dir.path().join("package.json"), r#"{"devDependencies":{"storebound":"^0.7.1"}}"#).unwrap();
|
||||
assert_eq!(pinned_storebound(dir.path()).as_deref(), Some("^0.7.1"));
|
||||
assert!(pin_differs("^0.7.1", "0.8.0"));
|
||||
assert!(!pin_differs("0.8.0", "0.8.0"));
|
||||
assert!(!pin_differs("~0.8.0", "0.8.0"));
|
||||
for spec in ["latest", "*", "file:../storebound", "workspace:*", ">=0.7"] {
|
||||
assert!(!pin_differs(spec, "0.8.0"), "{spec}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_flags_travel_between_the_registry_and_the_apps_ignore_keys() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("projects.json");
|
||||
// as `storebound apps ignore` wrote it: one folder fully, one store side of another, one store-only app
|
||||
let (one, two) = (dir.path().join("one").to_string_lossy().to_string(), dir.path().join("two").to_string_lossy().to_string());
|
||||
let doc = json!({ "version": 1, "projects": [
|
||||
{ "id": "aaaaaaaaaaaaaaaa", "path": one, "name": "One", "added": "t", "ignored": ["apple", "play"] },
|
||||
{ "id": "bbbbbbbbbbbbbbbb", "path": two, "name": "Two", "added": "t", "ignored": ["play"] }],
|
||||
"storeApps": [{ "store": "apple", "appId": "6400000999", "account": "teamA", "name": "Demo", "ignored": ["apple"] }] });
|
||||
std::fs::write(&file, doc.to_string()).unwrap();
|
||||
let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", &one, None), project("bbbbbbbbbbbbbbbb", &two, None)], ..State::default() };
|
||||
st.accounts = vec![account("acct1", "Team A", AccountKind::Apple, Some("teamA"))];
|
||||
st.overrides.ignored = vec!["account:zzz".into(), "app:ios:other:6400000999".into()];
|
||||
assert!(registry::pull_ignored(&mut st, &file));
|
||||
assert!(st.overrides.ignored.contains(&"account:zzz".to_string()));
|
||||
assert!(st.overrides.ignored.contains(&"project:aaaaaaaaaaaaaaaa".to_string()));
|
||||
assert!(st.overrides.ignored.contains(&"project:bbbbbbbbbbbbbbbb:android".to_string()));
|
||||
assert!(st.overrides.ignored.contains(&"app:ios:acct1:6400000999".to_string()));
|
||||
assert!(!st.overrides.ignored.contains(&"app:ios:other:6400000999".to_string()));
|
||||
assert!(!registry::pull_ignored(&mut st, &file), "second pull changes nothing");
|
||||
// the owner restores one folder's play side and ignores the other's apple side in the app
|
||||
st.overrides.ignored.retain(|k| k != "project:bbbbbbbbbbbbbbbb:android" && k != "app:ios:acct1:6400000999");
|
||||
st.overrides.ignored.push("project:bbbbbbbbbbbbbbbb:ios".into());
|
||||
assert!(registry::push_ignored(&st, &file).unwrap());
|
||||
let doc: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
|
||||
assert_eq!(doc["projects"][0]["ignored"], json!(["apple", "play"]));
|
||||
assert_eq!(doc["projects"][1]["ignored"], json!(["apple"]));
|
||||
assert!(doc["storeApps"][0].get("ignored").is_none());
|
||||
assert!(!registry::push_ignored(&st, &file).unwrap());
|
||||
// writing the folder list keeps the flags of the folders that stay
|
||||
let list = registry::read(&file).unwrap();
|
||||
registry::write(&file, &list).unwrap();
|
||||
let doc: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
|
||||
assert_eq!(doc["projects"][1]["ignored"], json!(["apple"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_play_developer_id_is_kept_in_the_profile_for_the_cli() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = ProfileStore::new(dir.path().join("credentials"), None);
|
||||
store.save("studio", "Studio", &Secret::Play { service_account: sa("bot@example.com") }).unwrap();
|
||||
assert_eq!(store.play_developer_id("studio"), None);
|
||||
store.set_play_developer_id("studio", Some("5550000000000000001")).unwrap();
|
||||
assert_eq!(store.play_developer_id("studio").as_deref(), Some("5550000000000000001"));
|
||||
let m = store.read("studio").unwrap();
|
||||
assert_eq!(m.get("PLAY_DEVELOPER_ID").and_then(|v| v.as_str()), Some("5550000000000000001"));
|
||||
assert!(m.contains_key("PLAY_SERVICE_ACCOUNT"));
|
||||
assert!(store.set_play_developer_id("studio", Some("abc")).is_err());
|
||||
store.set_play_developer_id("studio", None).unwrap();
|
||||
assert_eq!(store.play_developer_id("studio"), None);
|
||||
}
|
||||
|
|
@ -1,214 +0,0 @@
|
|||
//! 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}");
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
|||
|
||||
use serde_json::{json, Value};
|
||||
use storebound_desktop::policy::*;
|
||||
use storebound_desktop::{CARD_COMMANDS, COMMANDS, MENU_COMMANDS};
|
||||
use storebound_desktop::COMMANDS;
|
||||
use url::Url;
|
||||
|
||||
fn root() -> PathBuf {
|
||||
|
|
@ -24,10 +24,9 @@ fn u(s: &str) -> Url {
|
|||
#[test]
|
||||
fn one_capability_for_the_main_window_with_exactly_the_app_commands() {
|
||||
let dir = root().join("capabilities");
|
||||
let mut files: Vec<PathBuf> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).collect();
|
||||
files.sort();
|
||||
assert_eq!(files.len(), 3, "main, card and menu capability files expected, found {files:?}");
|
||||
let cap = read_json(&dir.join("main.json"));
|
||||
let 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:?}");
|
||||
let cap = read_json(&files[0]);
|
||||
assert_eq!(cap["identifier"], "main-window");
|
||||
assert_eq!(cap["windows"], json!(["main"]));
|
||||
assert!(cap.get("webviews").is_none(), "no webview-scoped grants");
|
||||
|
|
@ -47,69 +46,6 @@ 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]
|
||||
fn every_registered_command_is_in_the_list_and_nothing_else() {
|
||||
let lib = fs::read_to_string(root().join("src/lib.rs")).unwrap();
|
||||
|
|
@ -120,7 +56,7 @@ fn every_registered_command_is_in_the_list_and_nothing_else() {
|
|||
.map(|s| s.trim().trim_start_matches("commands::").to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
assert_eq!(registered, COMMANDS.iter().chain(CARD_COMMANDS).chain(MENU_COMMANDS).map(|s| s.to_string()).collect::<Vec<_>>());
|
||||
assert_eq!(registered, COMMANDS.iter().map(|s| s.to_string()).collect::<Vec<_>>());
|
||||
// every command checks the caller first
|
||||
let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap();
|
||||
for c in COMMANDS {
|
||||
|
|
@ -148,7 +84,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("https:") && !v.contains("http://") || v == "ipc: http://ipc.localhost", "{k}: no remote sources: {v}");
|
||||
}
|
||||
assert_eq!(conf["app"]["security"]["capabilities"], json!(["main-window", "card-window", "menu-window"]));
|
||||
assert_eq!(conf["app"]["security"]["capabilities"], json!(["main-window"]));
|
||||
assert_eq!(conf["app"]["security"]["freezePrototype"], json!(true));
|
||||
assert!(conf["app"].get("withGlobalTauri").is_none() || conf["app"]["withGlobalTauri"] == json!(false));
|
||||
let windows = conf["app"]["windows"].as_array().unwrap();
|
||||
|
|
@ -243,16 +179,6 @@ fn sidecar_starts_with_fixed_arguments_from_one_place() {
|
|||
assert!(src.contains("Command::new(&bin)\n .args(policy::SIDECAR_ARGS)"));
|
||||
continue;
|
||||
}
|
||||
// Fix with AI: only the claude binary (claude_command checks its name), git, and kill / taskkill by PID
|
||||
if p.ends_with("ai_fix.rs") {
|
||||
for (i, _) in src.match_indices("Command::new(") {
|
||||
let arg = &src[i + "Command::new(".len()..];
|
||||
let ok = ["claude)", "\"git\")", "\"kill\")", "\"taskkill\")"];
|
||||
assert!(ok.iter().any(|o| arg.starts_with(o)), "unexpected program: {}", &arg[..arg.find(')').unwrap_or(20).min(40)]);
|
||||
}
|
||||
assert!(src.contains("if !matches!(name, \"claude\" | \"claude.exe\" | \"claude.cmd\")"));
|
||||
continue;
|
||||
}
|
||||
// other programs: only the download checks (unpack, signature, version banner), with fixed program names
|
||||
if src.contains("Command::new(") {
|
||||
assert!(p.ends_with("downloads.rs"), "{} starts a program", p.display());
|
||||
|
|
|
|||
|
|
@ -4,39 +4,11 @@ use serde_json::{json, Value};
|
|||
use storebound_desktop::commands::project_view;
|
||||
use storebound_desktop::logs;
|
||||
use storebound_desktop::store::{self, State, VERSION};
|
||||
use storebound_desktop::accounts::{AccountKind, Secret, SecretStore};
|
||||
use storebound_desktop::profiles::{self, ProfileStore};
|
||||
use storebound_desktop::registry;
|
||||
use storebound_desktop::workspace::{Overrides, Settings};
|
||||
|
||||
const D1: &str = include_str!("../../tests/fixtures/state/d1-missing-folders.json");
|
||||
const D3: &str = include_str!("../../tests/fixtures/state/d3-full.json");
|
||||
const EMPTY: &str = include_str!("../../tests/fixtures/state/empty.json");
|
||||
const SHARED: &str = include_str!("../../tests/fixtures/state/shared-profiles.json");
|
||||
|
||||
/// Keychain entries of versions before 0.8, for the migration into credential profiles.
|
||||
#[derive(Default)]
|
||||
struct Keychain(std::sync::Mutex<std::collections::HashMap<String, Secret>>);
|
||||
impl SecretStore for Keychain {
|
||||
fn set(&self, id: &str, s: &Secret) -> Result<(), String> {
|
||||
self.0.lock().unwrap().insert(id.into(), s.clone());
|
||||
Ok(())
|
||||
}
|
||||
fn get(&self, id: &str) -> Result<Secret, String> {
|
||||
self.0.lock().unwrap().get(id).cloned().ok_or_else(|| "no entry".into())
|
||||
}
|
||||
fn delete(&self, id: &str) -> Result<(), String> {
|
||||
self.0.lock().unwrap().remove(id);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
const FAKE_PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PRIVATE KEY-----\n";
|
||||
fn fake_secret(kind: AccountKind, n: usize) -> Secret {
|
||||
match kind {
|
||||
AccountKind::Apple => Secret::Apple { key_id: format!("FAKEKEY{n:03}"), issuer_id: "00000000-0000-0000-0000-000000000000".into(), p8: FAKE_PEM.into() },
|
||||
AccountKind::Play => Secret::Play { service_account: json!({ "client_email": format!("bot{n}@example.iam.gserviceaccount.com"), "private_key": FAKE_PEM }).to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
fn write(dir: &std::path::Path, text: &str) {
|
||||
std::fs::write(dir.join(store::FILE), text).unwrap();
|
||||
|
|
@ -205,59 +177,17 @@ fn log_entries_are_one_block_and_rotate() {
|
|||
}
|
||||
|
||||
/// What the host answers for each fixture (projects_list without `missing`, accounts_list, workspace_get), written
|
||||
/// next to it as `<name>.host.json`, after the start-up sync with the machine's shared stores: D1 keeps its accounts in a
|
||||
/// keychain that has no entries (the keys were never added: the accounts stay without a profile), D3's keychain has
|
||||
/// them (they move into credential profiles), and shared-profiles is the 0.8 format whose apple account comes from a
|
||||
/// profile the CLI wrote, with a folder that pins storebound 0.6.0 and a store-only app of that profile (`storebound
|
||||
/// apps add --store apple --app-id … --account default`: store_apps_cached lists it under the apple account).
|
||||
/// tools/desktop-boot-check.ts boots the built window on exactly these answers.
|
||||
/// next to it as `<name>.host.json`. tools/desktop-boot-check.ts boots the built window on exactly these answers.
|
||||
/// After a change to the state format: STOREBOUND_UPDATE_FIXTURES=1 cargo test --test state
|
||||
#[test]
|
||||
fn host_answers_for_the_fixtures_are_current() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/fixtures/state");
|
||||
for (name, text, keychain) in [("empty", EMPTY, false), ("d1-missing-folders", D1, false), ("d3-full", D3, true), ("shared-profiles", SHARED, false)] {
|
||||
let (mut st, _, notes) = store::migrate(serde_json::from_str(text).unwrap());
|
||||
for (name, text) in [("empty", EMPTY), ("d1-missing-folders", D1), ("d3-full", D3)] {
|
||||
let (st, _, notes) = store::migrate(serde_json::from_str(text).unwrap());
|
||||
assert!(notes.is_empty(), "{name}: {notes:?}");
|
||||
let machine = tempfile::tempdir().unwrap();
|
||||
let profiles = ProfileStore::new(machine.path().join("credentials"), None);
|
||||
let legacy = Keychain::default();
|
||||
if keychain {
|
||||
for (i, a) in st.accounts.iter().enumerate() {
|
||||
legacy.set(&a.id, &fake_secret(a.kind, i)).unwrap();
|
||||
}
|
||||
}
|
||||
if name == "shared-profiles" {
|
||||
profiles.save("default", "Acme Games", &fake_secret(AccountKind::Play, 0)).unwrap();
|
||||
profiles.save("default", "Acme Games", &fake_secret(AccountKind::Apple, 0)).unwrap();
|
||||
}
|
||||
profiles::sync(&mut st.accounts, &profiles, &legacy, "2026-10-13T00:00:00Z");
|
||||
registry::sync(&mut st, &machine.path().join("projects.json")).unwrap();
|
||||
let mut projects = serde_json::to_value(&st.projects).unwrap();
|
||||
if name == "shared-profiles" {
|
||||
// what project_view says for a folder whose package.json pins storebound 0.6.0
|
||||
let pinned = tempfile::tempdir().unwrap();
|
||||
std::fs::write(pinned.path().join("package.json"), r#"{"devDependencies":{"storebound":"0.6.0"}}"#).unwrap();
|
||||
let mut p = st.projects[0].clone();
|
||||
p.path = pinned.path().to_string_lossy().to_string();
|
||||
let pin = project_view(&p).storebound_pin.expect("0.6.0 is not this app");
|
||||
projects[0]["storeboundPin"] = json!(pin);
|
||||
}
|
||||
// store_apps_cached before any store read: only the machine's store-only entries (registry.rs)
|
||||
let store_only = if name == "shared-profiles" {
|
||||
registry::parse_store_apps(r#"{"storeApps":[{"store":"apple","appId":"6400000999","account":"default","name":"Example Aquarium","bundleId":"com.example.aquarium"}]}"#)
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let cached: Vec<serde_json::Value> = st.accounts.iter().map(|a| {
|
||||
let store = match a.kind { AccountKind::Apple => "apple", AccountKind::Play => "play" };
|
||||
let only = st.accounts.iter().filter(|x| x.kind == a.kind).count() == 1;
|
||||
let entry = registry::with_store_only(None, store, a.profile.as_deref(), only, &store_only, "2026-10-13T00:00:00Z").map(|value| json!({ "value": value, "at": "2026-10-13T00:00:00Z" }));
|
||||
json!({ "account": a.id, "entry": entry })
|
||||
}).collect();
|
||||
let host = json!({
|
||||
"projects_list": projects,
|
||||
"projects_list": st.projects,
|
||||
"accounts_list": st.accounts,
|
||||
"store_apps_cached": cached,
|
||||
"workspace_get": { "studios": st.studios, "overrides": st.overrides, "settings": st.settings },
|
||||
});
|
||||
let want = format!("{}\n", serde_json::to_string_pretty(&host).unwrap());
|
||||
|
|
|
|||
|
|
@ -1,122 +0,0 @@
|
|||
//! The tray's pure parts: menu model, tooltip, click actions, notification targets, the attention dot, settings.
|
||||
use storebound_desktop::tray::*;
|
||||
use storebound_desktop::workspace::{check_settings, valid_hhmm, Settings};
|
||||
|
||||
fn summary() -> TraySummary {
|
||||
TraySummary {
|
||||
tooltip: "storebound · 2 in review · 1 needs you".into(),
|
||||
attention: 1,
|
||||
muted: false,
|
||||
apps: vec![
|
||||
TrayApp { key: "k1".into(), name: "First".into(), state: "App Store: In review · Play: Live".into() },
|
||||
TrayApp { key: "k2".into(), name: "Second".into(), state: String::new() },
|
||||
],
|
||||
labels: TrayLabels::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(m: &[Entry]) -> Vec<String> {
|
||||
m.iter().filter_map(|e| if let Entry::Item { id, .. } = e { Some(id.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_has_every_entry_in_order() {
|
||||
let m = menu_model(&summary());
|
||||
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") };
|
||||
assert_eq!(label, "Apps");
|
||||
assert_eq!(items.len(), 2);
|
||||
let Entry::Item { id, label, enabled } = &items[0] else { panic!() };
|
||||
assert_eq!((id.as_str(), *enabled), ("tray-app:k1", true));
|
||||
assert!(label.contains("First") && label.contains("In review"), "{label}");
|
||||
let Entry::Item { label, .. } = &items[1] else { panic!() };
|
||||
assert_eq!(label, "Second", "an app without a state shows its name only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mute_entry_follows_the_state_and_empty_apps_say_so() {
|
||||
let mut s = summary();
|
||||
s.muted = true;
|
||||
s.apps.clear();
|
||||
let m = menu_model(&s);
|
||||
let Entry::Item { label, .. } = m.iter().find(|e| matches!(e, Entry::Item { id, .. } if id == ID_MUTE)).unwrap() else { panic!() };
|
||||
assert_eq!(label, "Unmute notifications");
|
||||
let Entry::Sub { items, .. } = &m[3] else { panic!() };
|
||||
assert!(matches!(&items[0], Entry::Item { enabled: false, label, .. } if label == "No apps yet"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tooltip_is_one_short_line() {
|
||||
assert_eq!(tooltip_text(&summary()), "storebound · 2 in review · 1 needs you");
|
||||
let mut s = summary();
|
||||
s.tooltip = "a\nb\t c".into();
|
||||
assert_eq!(tooltip_text(&s), "a b c");
|
||||
s.tooltip = "x".repeat(500);
|
||||
assert_eq!(tooltip_text(&s).chars().count(), MAX_TIP);
|
||||
s.tooltip = " ".into();
|
||||
assert_eq!(tooltip_text(&s), "storebound");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_map_to_actions() {
|
||||
assert_eq!(action_of(ID_OPEN), Some(Action::Open));
|
||||
assert_eq!(action_of(ID_QUIT), Some(Action::Quit));
|
||||
assert_eq!(action_of(ID_READ), Some(Action::Event("read")));
|
||||
assert_eq!(action_of(ID_MUTE), Some(Action::Event("mute-toggle")));
|
||||
assert_eq!(action_of("tray-app:k1"), Some(Action::Route(r#"{"appId":"k1","screen":"app","tab":"releases"}"#.into())));
|
||||
assert_eq!(action_of("tray-app:"), None);
|
||||
assert_eq!(action_of("other"), None);
|
||||
let Some(Action::Route(r)) = action_of(ID_UPDATE) else { panic!() };
|
||||
assert!(valid_route(&r) && r.contains("updates"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_known_small_routes_are_remembered() {
|
||||
assert!(valid_route(r#"{"screen":"app","appId":"k1","tab":"releases"}"#));
|
||||
assert!(valid_route(r#"{"screen":"portfolio"}"#));
|
||||
assert!(!valid_route(r#"{"screen":"evil"}"#));
|
||||
assert!(!valid_route(r#"{"screen":"app","appId":5}"#));
|
||||
assert!(!valid_route("[]"));
|
||||
assert!(!valid_route("not json"));
|
||||
assert!(!valid_route(&format!(r#"{{"screen":"app","appId":"{}"}}"#, "a".repeat(500))));
|
||||
// handed out once
|
||||
set_pending(r#"{"screen":"portfolio"}"#);
|
||||
assert_eq!(take_pending().as_deref(), Some(r#"{"screen":"portfolio"}"#));
|
||||
assert_eq!(take_pending(), None);
|
||||
set_pending(r#"{"screen":"evil"}"#);
|
||||
assert_eq!(take_pending(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attention_dot_changes_only_the_corner() {
|
||||
let (w, h) = (32u32, 32u32);
|
||||
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);
|
||||
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]] };
|
||||
assert_eq!(at(&out, 2, 30), [10, 20, 30, 255], "the bottom left stays");
|
||||
let dot = at(&out, 25, 6);
|
||||
assert!(dot[0] > 200 && dot[1] < 90 && dot[2] < 90, "red in the middle of the dot: {dot:?}");
|
||||
// transparent icon: the dot is opaque, the rest stays clear
|
||||
let clear = vec![0u8; (w * h * 4) as usize];
|
||||
let out = with_attention_dot(&clear, w, h);
|
||||
assert_eq!(at(&out, 2, 30)[3], 0);
|
||||
assert_eq!(at(&out, 25, 6)[3], 255);
|
||||
// a wrong buffer size is returned unchanged
|
||||
assert_eq!(with_attention_dot(&[1, 2, 3], w, h), vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_hours_settings_are_checked_and_default_off() {
|
||||
let d = Settings::default();
|
||||
assert!(!d.notify.quiet_hours.enabled);
|
||||
assert_eq!((d.notify.quiet_hours.from.as_str(), d.notify.quiet_hours.to.as_str()), ("23:00", "08:00"));
|
||||
assert!(d.notify.rejected && d.notify.approved && d.notify.live);
|
||||
assert!(valid_hhmm("00:00") && valid_hhmm("23:59"));
|
||||
assert!(!valid_hhmm("24:00") && !valid_hhmm("7:00") && !valid_hhmm("12:60") && !valid_hhmm("ab:cd"));
|
||||
let mut s = d.clone();
|
||||
s.notify.quiet_hours.from = "25:00".into();
|
||||
assert!(check_settings(&s).is_err());
|
||||
let old: Settings = serde_json::from_value(serde_json::json!({ "notify": { "crash": false } })).unwrap();
|
||||
assert!(!old.notify.crash && old.notify.rejected && !old.notify.quiet_hours.enabled, "an older file gets the new defaults");
|
||||
}
|
||||
|
|
@ -106,15 +106,6 @@ fn settings_have_safe_defaults_and_bounds() {
|
|||
s = d.clone();
|
||||
s.refresh.auto_minutes = 1;
|
||||
assert!(check_settings(&s).is_err(), "no tight polling of the store APIs");
|
||||
assert_eq!((d.refresh.auto_read, d.refresh.every_minutes), (true, 15), "background reading is on by default, every 15 minutes");
|
||||
s = d.clone();
|
||||
s.refresh.every_minutes = 1;
|
||||
assert!(check_settings(&s).is_err(), "no background pass more often than every 5 minutes");
|
||||
s = d.clone();
|
||||
s.refresh.every_minutes = 0;
|
||||
assert!(check_settings(&s).is_ok());
|
||||
let old: Settings = serde_json::from_value(serde_json::json!({ "refresh": { "autoMinutes": 15 } })).unwrap();
|
||||
assert_eq!((old.refresh.auto_read, old.refresh.every_minutes, old.refresh.auto_minutes), (true, 15, 15), "an older settings file gets the new defaults");
|
||||
s = d.clone();
|
||||
s.cache.keep_days = 3;
|
||||
assert!(check_settings(&s).is_err());
|
||||
|
|
|
|||
|
|
@ -1,46 +1,36 @@
|
|||
// 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),
|
||||
// Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh),
|
||||
// the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide.
|
||||
import { DryRunPreview } from './ui/DryRunPreview';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { FIXTURES, onDeepLink, onDeepLinkFolder, onTrayRoute } from './api';
|
||||
import { FIXTURES, onDeepLink, onDeepLinkFolder } from './api';
|
||||
import { devSwitch } from './dev/switches';
|
||||
import { type Key, t } from './i18n';
|
||||
import { ago, num } from './lib/format';
|
||||
import type { UnifiedApp } from './lib/identity';
|
||||
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 { ago } from './lib/format';
|
||||
import { groupByStudio, type UnifiedApp } from './lib/identity';
|
||||
import { NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav';
|
||||
import { usePrefs } from './prefs-ctx';
|
||||
import { Accounts } from './screens/Accounts';
|
||||
import { AppFolders } from './screens/AppFolders';
|
||||
import { AppView } from './screens/AppView';
|
||||
import { Dependencies } from './screens/Dependencies';
|
||||
import { Ignored } from './screens/Ignored';
|
||||
import { useShowIgnored } from './lib/show-ignored';
|
||||
import { Onboarding } from './screens/Onboarding';
|
||||
import { Portfolio } from './screens/Portfolio';
|
||||
import { Settings } from './screens/Settings';
|
||||
import { useData, useReadState } from './store';
|
||||
import { useData } from './store';
|
||||
import { Icon, type IconName, Mark } from './ui/icons';
|
||||
import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit';
|
||||
import { type Command, Palette } from './ui/Palette';
|
||||
import { ExportMenu, useExportItems, useRunExport } from './ui/Exports';
|
||||
import { ErrorBoundary } from './ui/ErrorBoundary';
|
||||
import { Toasts } from './ui/Toasts';
|
||||
import { useContextMenu } from './ui/ContextMenu';
|
||||
import { appMenu } from './ui/app-menu';
|
||||
import { isEditable, isItem, type MenuInput } from './ui/menu-logic';
|
||||
import { attention, isGameSummary, SIDE_GROUPS, type SideGroup, sideStatus } from './lib/model';
|
||||
|
||||
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' };
|
||||
|
||||
const SIDE_KEY = 'storebound.side.v1';
|
||||
const STUDIO_KEY = 'storebound.side.studio.v1';
|
||||
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 []; }
|
||||
}
|
||||
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 }) {
|
||||
const d = useData();
|
||||
|
|
@ -50,38 +40,11 @@ export function App({ onTheme }: { onTheme: () => void }) {
|
|||
const [welcome, setWelcome] = useState(false);
|
||||
const [started, setStarted] = useState(false);
|
||||
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 runExport = useRunExport();
|
||||
|
||||
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]);
|
||||
// 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 ignoredApps = useMemo(() => d.apps.filter(a => a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]);
|
||||
const gameOf = useCallback((a: UnifiedApp) => isGameSummary(d.statusFor(a)?.summary), [d]);
|
||||
const tabsOf = useCallback((a: UnifiedApp) => tabsFor(!!a.project, gameOf(a)), [gameOf]);
|
||||
// the sidebar: apps by what they need (attention, in progress, live, not on a store yet), one status line each
|
||||
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) => {
|
||||
if (!sideOrder.length) return;
|
||||
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]!;
|
||||
go({ screen: 'app', appId: next.key, tab: route.screen === 'app' && tabsOf(next).includes(route.tab) ? route.tab : 'releases' });
|
||||
}, [sideOrder, route, go, tabsOf]);
|
||||
const toggleGroup = (id: string) => setCollapsed(c => {
|
||||
const next = c.includes(id) ? c.filter(x => x !== id) : [...c, id];
|
||||
try { localStorage.setItem(SIDE_KEY, JSON.stringify(next)); } catch { /* private mode */ }
|
||||
|
|
@ -104,44 +67,33 @@ export function App({ onTheme }: { onTheme: () => void }) {
|
|||
const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); });
|
||||
// `storebound desktop` in an app folder: the host added (after its native dialog) or found that folder
|
||||
const unFolder = onDeepLinkFolder(id => { d.reload().catch(() => {}).finally(() => go({ screen: 'app', appId: id, tab: 'releases' })); });
|
||||
// the tray menu (an app, Settings, Check for updates) and the first show after a notification
|
||||
const unTray = onTrayRoute(s => { const r = parseRouteJson(s); if (r) go(r); });
|
||||
return () => { un.then(f => f()); unFolder.then(f => f()); unTray.then(f => f()); };
|
||||
return () => { un.then(f => f()); unFolder.then(f => f()); };
|
||||
}, [go, d.reload]);
|
||||
|
||||
const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined;
|
||||
const game = app ? gameOf(app) : false;
|
||||
const tabs = app ? tabsOf(app) : [];
|
||||
const sections = app ? sectionsFor(!!app.project, game) : [];
|
||||
const tabs = app ? tabsFor(!!app.project) : [];
|
||||
|
||||
// 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
|
||||
// keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-6 workspace, Cmd/Ctrl+Shift+[ ] app tabs
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette(p => !p); return; }
|
||||
if (palette || welcome) return;
|
||||
if (e.altKey && !mod && !e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown') && !isEditable(e.target as HTMLInputElement)) { e.preventDefault(); stepApp(e.key === 'ArrowDown' ? 1 : -1); return; }
|
||||
if (mod && !e.shiftKey && !e.altKey && /^[1-6]$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
const n = Number(e.key);
|
||||
go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! });
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app' && tabs.length) {
|
||||
e.preventDefault();
|
||||
const i = sections.indexOf(sectionOf(route.tab)) + (e.key === ']' || e.key === '}' ? 1 : -1);
|
||||
go({ ...route, tab: subsOf(sections[(i + sections.length) % sections.length]!, !!app.project, game)[0]! });
|
||||
const i = tabs.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1);
|
||||
go({ ...route, tab: tabs[(i + tabs.length) % tabs.length]! });
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [palette, welcome, route, go, app, sections, game, stepApp]);
|
||||
}, [palette, welcome, route, go, tabs]);
|
||||
|
||||
const closeWelcome = useCallback(() => {
|
||||
setWelcome(false);
|
||||
|
|
@ -155,30 +107,11 @@ 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 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) },
|
||||
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-prev-app', group: G.go, title: t('palette.prevApp'), icon: 'arrowLeft', hint: 'Alt ↑', keywords: 'previous app up k', run: () => stepApp(-1) });
|
||||
run: () => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' }) });
|
||||
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 }) }));
|
||||
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 }) });
|
||||
// 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
|
||||
// also one Ctrl+K away; opening a tab is already above
|
||||
if (app) {
|
||||
const skip = new Set([t('cm.open'), t('cm.openTab')]);
|
||||
const add = (items: MenuInput, prefix: string) => items.forEach((e, i) => {
|
||||
if (!e || !isItem(e) || skip.has(e.label) || e.disabled) return;
|
||||
const title = prefix ? `${prefix} · ${e.label}` : e.label;
|
||||
if (e.submenu) { add(e.submenu, title); return; }
|
||||
if (e.onSelect) c.push({ id: `appcmd-${prefix}-${i}-${e.label}`, group: t('palette.gApp', { name: app.name }), title, icon: e.icon, hint: e.shortcut, keywords: app.name, run: e.onSelect });
|
||||
});
|
||||
add(appMenu(app, d, { route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }, { showIgnored }), '');
|
||||
}
|
||||
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 }) });
|
||||
for (const x of exports) c.push({ id: `export-${x.id}`, group: G.exp, title: t('palette.export', { what: x.label }), icon: x.icon ?? 'download', keywords: `export save download ${x.kind}`, hint: x.disabled || `.${x.kind}`, run: () => { runExport(x); } });
|
||||
if (app?.project) {
|
||||
const p = app.project.id;
|
||||
|
|
@ -191,37 +124,37 @@ export function App({ onTheme }: { onTheme: () => void }) {
|
|||
c.push({ id: 'act-check', group: G.act, title: t('action.checkConfigs'), icon: 'shield', run: () => { d.refreshPortfolio(false); } });
|
||||
c.push({ id: 'act-add', group: G.act, title: t('action.addFolder'), icon: 'folderPlus', run: () => go({ screen: 'apps' }) });
|
||||
c.push({ id: 'act-account', group: G.act, title: t('action.addAccount'), icon: 'key', run: () => go({ screen: 'accounts' }) });
|
||||
c.push({ id: 'act-density', group: G.act, title: t('action.toggleDensity'), icon: 'grid', keywords: 'dense compact table density rows', run: () => update({ ...prefs, density: prefs.density === 'compact' ? 'comfortable' : 'compact' }) });
|
||||
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) });
|
||||
return c;
|
||||
}, [d, visible, app, sections, game, route, go, onTheme, exports, runExport, showIgnored, stepApp, prefs, update, tabsOf]);
|
||||
}, [d, visible, app, tabs, route, go, onTheme, exports, runExport]);
|
||||
|
||||
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(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]) }] : [])]
|
||||
: route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }]
|
||||
: [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }];
|
||||
const lastRead = d.live?.at ?? null;
|
||||
// the app on screen is read first by the background reader
|
||||
const { setFocus } = d;
|
||||
useEffect(() => { setFocus(app?.key ?? null); }, [app?.key, setFocus]);
|
||||
const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]);
|
||||
const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) || (r.screen !== 'app' && r.screen !== 'portfolio' && r.screen === route.screen) ? 'page' : undefined);
|
||||
const groups = d.studios.length ? groupByStudio(visible.map(a => ({ app: a })), d.studios) : [{ studio: null as string | null, rows: visible.map(a => ({ app: a })) }];
|
||||
const ignoredCount = d.apps.filter(a => a.ignored).length + d.overrides.ignored.filter(i => i.startsWith('account:')).length;
|
||||
|
||||
const menu = useContextMenu();
|
||||
const appItem = (a: UnifiedApp, st: { text: string; tone: string }) => (
|
||||
const appItem = (a: UnifiedApp) => {
|
||||
const e = d.statusFor(a);
|
||||
const missing = !!a.project?.missing;
|
||||
const bad = missing ? 1 : (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
|
||||
return (
|
||||
<div role="listitem" key={a.key}>
|
||||
<button {...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' && tabsOf(a).includes(route.tab) ? route.tab : 'releases' })}
|
||||
title={`${a.name} · ${st.text}`}>
|
||||
<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>
|
||||
<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>}
|
||||
<button className="nav nav-app" 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' })}>
|
||||
<AppIcon name={a.name} src={d.iconFor(a)} />
|
||||
<span className="grow">{a.name}</span>
|
||||
{!a.project && <span className="so-dot" title={t('apps.storeOnlyHint')}><Icon name="cloud" /></span>}
|
||||
{missing ? <span className="tag-count bad" title={t('folder.missingShort')} aria-label={t('folder.missingShort')}>!</span>
|
||||
: bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
const WS_ROW: (WorkspaceScreen | 'portfolio')[] = ['portfolio', ...WORKSPACE];
|
||||
};
|
||||
|
||||
return (
|
||||
<NavCtx.Provider value={nav}>
|
||||
|
|
@ -235,47 +168,40 @@ export function App({ onTheme }: { onTheme: () => void }) {
|
|||
</button>
|
||||
</div>
|
||||
<div className="side-scroll">
|
||||
<div className="side-label" id="apps-label"><span>{t('nav.appsLabel')} <span className="count">{visible.length}</span></span>
|
||||
<button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => go({ screen: 'portfolio' })}>
|
||||
<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>
|
||||
</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 => {
|
||||
const gid = `g:${g.id}`;
|
||||
const s = d.studios.find(x => x.id === g.studio) ?? null;
|
||||
const gid = g.studio ?? 'none';
|
||||
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 (
|
||||
<div className="side-group" key={gid} data-group={g.id}>
|
||||
<button className="side-group-head" aria-expanded={open} aria-controls={`sg-${g.id}`} onClick={() => toggleGroup(gid)}>
|
||||
<Icon name="chevronRight" className="chev" /><span className="grow">{t(GROUP_KEY[g.id])}</span><span className="count">{g.rows.length}</span>
|
||||
<div className="side-group" key={gid}>
|
||||
<button className="side-group-head" aria-expanded={open} aria-controls={`sg-${gid}`} 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>
|
||||
</button>
|
||||
{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>}
|
||||
{open && <div role="list" id={`sg-${gid}`} aria-label={s?.name ?? t('studio.none')}>{g.rows.map(r => appItem(r.app))}</div>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{!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>}
|
||||
</div>
|
||||
<div className="side-ws" role="group" aria-label={t('nav.workspace')}>
|
||||
{WS_ROW.map((s, i) => {
|
||||
const label = s === 'portfolio' ? t('nav.portfolio') : t(WS_KEY[s]);
|
||||
const n = s === 'accounts' ? d.accounts.length : s === 'ignored' ? ignoredCount : 0;
|
||||
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>}
|
||||
{!visible.length && <p className="side-empty">{t('nav.noApps')}</p>}
|
||||
<div className="side-label"><span>{t('nav.workspace')}</span></div>
|
||||
{WORKSPACE.map((s, i) => (
|
||||
<button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${t(WS_KEY[s])} (${MOD} ${i + 2})`}>
|
||||
<Icon name={WS_ICON[s]} weight={current({ screen: s }) ? 'fill' : 'regular'} /><span className="grow">{t(WS_KEY[s])}</span>
|
||||
{s === 'accounts' && <span className="count">{d.accounts.length}</span>}
|
||||
{s === 'ignored' && ignoredCount > 0 && <span className="count">{ignoredCount}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
))}
|
||||
</div>
|
||||
<div className="side-foot" aria-live="polite">
|
||||
<div className="row"><i className={`dot ${d.sidecar?.running ? 'ok' : d.sidecarError ? 'bad' : ''}`} />
|
||||
<span>{d.sidecar?.running ? t('foot.cli', { version: d.sidecar.version }) : d.sidecarError ? t('foot.cliDown') : t('foot.cliStarting')}</span></div>
|
||||
<div className="row"><Icon name="clock" className="sr-icon" /><span>{lastRead ? t('foot.lastRead', { when: ago(lastRead) }) : t('foot.neverRead')}</span></div>
|
||||
<ReaderLine />
|
||||
</div>
|
||||
</nav>
|
||||
<div className="main">
|
||||
|
|
@ -291,8 +217,8 @@ export function App({ onTheme }: { onTheme: () => void }) {
|
|||
<span className="spacer" />
|
||||
{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>
|
||||
<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={allReads.busy ? 'spin' : undefined} />{t('action.refreshAll')}
|
||||
<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy || !visible.length} title={t('action.readStoresHint')}>
|
||||
<Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')}
|
||||
</button>
|
||||
<ExportMenu />
|
||||
</header>
|
||||
|
|
@ -313,27 +239,6 @@ export function App({ onTheme }: { onTheme: () => void }) {
|
|||
{palette && <ErrorBoundary where="palette"><Palette commands={commands} onClose={() => setPalette(false)} /></ErrorBoundary>}
|
||||
{welcome && <ErrorBoundary where="welcome"><Onboarding onClose={closeWelcome} /></ErrorBoundary>}
|
||||
<ErrorBoundary where="toasts"><Toasts /></ErrorBoundary>
|
||||
<ErrorBoundary where="preview"><DryRunPreview /></ErrorBoundary>
|
||||
</NavCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/** The background reader in the sidebar foot: progress (count + thin bar) and the App Store hourly limit on their own
|
||||
* short rows, so nothing is cut off; the long wording stays in the tooltip. */
|
||||
function ReaderLine() {
|
||||
const d = useData();
|
||||
const r = d.reader;
|
||||
const q = Object.values(r.quota).sort((a, b) => a.remaining - b.remaining)[0];
|
||||
const busy = r.total > 0 && (r.running || r.queued);
|
||||
const head = busy ? t('reader.progress', { done: r.done, total: r.total }) : !d.reader.autoRead ? t('reader.off') : d.ready && d.apps.length ? t('reader.upToDate') : '';
|
||||
const paused = Object.keys(r.paused).length > 0;
|
||||
if (!head && !q && !paused) return null;
|
||||
return (
|
||||
<div className="reader-line" data-testid="reader-line" aria-live="polite">
|
||||
{head && <div className="row" title={head}><Icon name="refresh" className={`sr-icon${r.running ? ' spin' : ''}`} /><span>{head}</span></div>}
|
||||
{busy && <div className="reader-bar" role="progressbar" aria-valuemin={0} aria-valuemax={r.total} aria-valuenow={r.done} aria-label={head}><i style={{ width: `${Math.round((r.done / Math.max(1, r.total)) * 100)}%` }} /></div>}
|
||||
{paused && <div className="row" title={t('reader.backoff')}><Icon name="pause" className="sr-icon" /><span>{t('reader.backoffShort')}</span></div>}
|
||||
{q && <div className="row" title={t('reader.appleQuota', { left: num(q.remaining), limit: num(q.limit) })}><Icon name="gauge" className="sr-icon" /><span>{t('reader.appleQuotaShort', { left: num(q.remaining), limit: num(q.limit) })}</span></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,40 +6,32 @@ import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event';
|
|||
import type { AccountCheck, AppsListResult, DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol';
|
||||
import type { DeclarationsResult, ListingText, RendersResult } from '../../../cli/lib/desktop-protocol';
|
||||
import type { Overrides } from './lib/identity';
|
||||
import type { TraySummary } from './lib/tray';
|
||||
|
||||
export type {
|
||||
AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult,
|
||||
ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult,
|
||||
EditableListing, EditableResult, EditResult,
|
||||
AnalyticsCompare, AsoAuditView, AsoTrendRow, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult,
|
||||
ArtThumb, LiveArtResult, LiveArtSet, LiveArtTile,
|
||||
AnalyticsCompare, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult,
|
||||
} from '../../../cli/lib/desktop-protocol';
|
||||
|
||||
export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null }
|
||||
export type { ToolStatus } from '../../../cli/lib/tools';
|
||||
export type { AndroidSdkLookup } from '../../../cli/lib/tools';
|
||||
/** system.tools: the local tools and (newer sidecars) the Android SDK as `play build` finds it. */
|
||||
export interface LocalTools { tools: import('../../../cli/lib/tools').ToolStatus[]; androidSdk?: import('../../../cli/lib/tools').AndroidSdkLookup }
|
||||
export interface LocalTools { tools: import('../../../cli/lib/tools').ToolStatus[] }
|
||||
export interface SidecarStatus { running: boolean; version: string; protocol: string; methods: Pick<MethodDescriptor, 'method' | 'title' | 'description' | 'kind' | 'network' | 'destructive' | 'json'>[]; tools: LocalTools | null }
|
||||
/** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */
|
||||
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string; /** The folder is gone (moved, renamed, deleted): shown as "Folder not found". */ missing?: boolean; /** The storebound version the folder's package.json pins, when it is not this app's. */ storeboundPin?: string | null }
|
||||
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string; /** The folder is gone (moved, renamed, deleted): shown as "Folder not found". */ missing?: boolean }
|
||||
export type AccountKind = 'play' | 'apple';
|
||||
export interface Account { id: string; label: string; kind: AccountKind; created: string; studio?: string | null; /** The machine profile that holds the key (~/.storebound, shared with the CLI); null while an old keychain key has not moved. */ profile?: string | null; /** Play: the developer account id (PLAY_DEVELOPER_ID in the profile) for Play Console deep links. */ developerId?: string | null }
|
||||
export interface Account { id: string; label: string; kind: AccountKind; created: string; studio?: string | null }
|
||||
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
|
||||
export type StudioColor = (typeof STUDIO_COLORS)[number];
|
||||
/** A user-named group of store accounts (and so of apps). */
|
||||
export interface Studio { id: string; name: string; color: StudioColor; logo: string | null; created: string }
|
||||
export interface Settings {
|
||||
/** autoRead / everyMinutes: the background reader (store.tsx); autoMinutes / onLaunch: older builds' settings, kept for them. */
|
||||
refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean; autoRead: boolean; everyMinutes: 0 | 5 | 15 | 30 | 60 };
|
||||
refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean };
|
||||
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). */
|
||||
notify: { reviewState: boolean; rejected: boolean; approved: boolean; live: boolean; lowReviews: boolean; crash: boolean; quietHours: { enabled: boolean; from: string; to: string } };
|
||||
/** Update channel: stable (npm releases) or dev (every push to main); beta is kept for saved states. */
|
||||
channel: 'stable' | 'dev' | 'beta';
|
||||
notify: { reviewState: boolean; lowReviews: boolean; crash: boolean };
|
||||
channel: 'stable' | '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 }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' };
|
||||
export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings }
|
||||
export interface AccountApps { account: string; entry: CacheEntry<AppsListResult> | null }
|
||||
export interface CacheInfo { rows: number; bytes: number; oldest: string | null; file_bytes: number }
|
||||
|
|
@ -48,7 +40,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 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 interface UpdateInfo { current: string; channel: 'stable' | 'dev' | 'beta'; available: string | null; notes: string | null; date: string | null }
|
||||
export interface UpdateInfo { current: string; channel: 'stable' | 'beta'; available: string | null; notes: string | null; date: string | null }
|
||||
|
||||
/** What a failed command rejects with (sidecar.rs `Fail`). */
|
||||
export interface Fail { code: number; message: string; data?: unknown }
|
||||
|
|
@ -72,13 +64,6 @@ async function listen<T>(event: string, cb: (payload: T) => void): Promise<Unlis
|
|||
return tauriListen<T>(event, e => cb(e.payload));
|
||||
}
|
||||
|
||||
/** The finding fields the host builds the Fix with AI prompt from. */
|
||||
export interface AiFinding { rule: string; guideline: string; store: 'apple' | 'play'; title: string; evidence: { file: string; line: number; text?: string }[]; fix: string; skill: string }
|
||||
export interface AiChange { path: string; status: string }
|
||||
export interface AiFixInfo { claude: boolean; prompt: string; git: boolean; gitError: string | null; dirty: AiChange[] }
|
||||
export type AiFixRun = { refused: 'dirty'; dirty: AiChange[] }
|
||||
| { refused?: undefined; runId: string; outcome: { code: number | null; timed_out: boolean; cancelled: boolean; summary: string }; changes: AiChange[]; diff: string };
|
||||
|
||||
let jobSeq = 0;
|
||||
/** A fresh job id for one background run (progress events and cancel refer to it). */
|
||||
export const newJob = (kind: string): string => `${kind.replace(/[^A-Za-z0-9_.-]/g, '-').slice(0, 40)}-${Date.now().toString(36)}-${++jobSeq}`;
|
||||
|
|
@ -94,10 +79,6 @@ export const api = {
|
|||
invoke<CacheEntry<T> | null>('cache_get', { method, projectId, args }),
|
||||
clearCache: () => invoke<void>('cache_clear'),
|
||||
cancel: (job: string) => invoke<boolean>('job_cancel', { job }),
|
||||
/** Fix with AI (src-tauri/src/ai_fix.rs): claude installed?, the prompt (also for Copy for AI), the dirty files. */
|
||||
aiFixInfo: (projectId: string, finding: AiFinding) => invoke<AiFixInfo>('ai_fix_info', { projectId, finding }),
|
||||
aiFixRun: (projectId: string, finding: AiFinding, job: string) => invoke<AiFixRun>('ai_fix_run', { projectId, finding, job }),
|
||||
aiFixUndo: (runId: string) => invoke<string[]>('ai_fix_undo', { runId }),
|
||||
/** Dry run, native confirm dialog with that dry run, then the real run with a host-minted token. */
|
||||
writeWithConfirm: (method: string, projectId: string, args: Record<string, unknown> = {}, job?: string) =>
|
||||
invoke<WriteOutcome>('write_with_confirm', { method, projectId, args, job: job ?? null }),
|
||||
|
|
@ -111,7 +92,6 @@ export const api = {
|
|||
addAppleAccount: (label: string, keyId: string, issuerId: string, studio: string | null = null) => invoke<Account | null>('account_add_apple', { label, keyId, issuerId, studio }),
|
||||
removeAccount: (id: string) => invoke<void>('account_remove', { id }),
|
||||
updateAccount: (id: string, label: string, studio: string | null) => invoke<Account>('account_update', { id, label, studio }),
|
||||
setPlayDeveloper: (id: string, developerId: string | null) => invoke<Account>('account_set_play_developer', { id, developerId }),
|
||||
/** Does the key work, can it see apps (live, not cached). */
|
||||
checkAccount: (id: string, job?: string) => invoke<AccountCheck>('account_check', { id, job: job ?? null }),
|
||||
/** Reads the apps an account can see from its store and keeps the list. */
|
||||
|
|
@ -125,10 +105,7 @@ export const api = {
|
|||
setSettings: (settings: Settings) => invoke<Settings>('settings_set', { settings }),
|
||||
cacheInfo: () => invoke<CacheInfo>('cache_info'),
|
||||
revealData: () => invoke<void>('data_reveal'),
|
||||
/** target: a route (JSON) the window opens on when it is next shown from the tray (the notification plugin has no click callback on desktop). */
|
||||
notify: (title: string, body: string, target?: string) => invoke<void>('notify', { title, body, target: target ?? null }),
|
||||
/** Pushes the tray's tooltip, attention flag and app list after a read (lib/tray.ts). */
|
||||
trayUpdate: (summary: TraySummary) => invoke<void>('tray_update', { summary }),
|
||||
notify: (title: string, body: string) => invoke<void>('notify', { title, body }),
|
||||
/** Native confirmation first; true when everything was forgotten. */
|
||||
reset: () => invoke<boolean>('app_reset'),
|
||||
/** Offline (folders) or live; live also reads the given store-only apps (store targets). */
|
||||
|
|
@ -147,8 +124,6 @@ export const api = {
|
|||
exportSave: (name: string, kind: ExportKind, content: string, personal = false) => invoke<string | null>('export_save', { name, kind, content, personal }),
|
||||
/** Native open dialog for a price sheet (CSV); its path, or null. */
|
||||
pickPriceSheet: (projectId: string) => invoke<string | null>('price_sheet_pick', { projectId }),
|
||||
/** Native open dialog for an image (PNG / JPEG) to replace one store image with; its path, or null. */
|
||||
pickImage: (projectId: string) => invoke<string | null>('image_pick', { projectId }),
|
||||
/** Shows a path of an app folder in the file manager, or opens a folder / the gallery page. */
|
||||
reveal: (projectId: string, rel = '', open = false) => invoke<void>('project_reveal', { projectId, rel, open }),
|
||||
/** "Locate…" for a folder that is gone: native folder picker; the same app with its new path, or null. */
|
||||
|
|
@ -173,14 +148,8 @@ export const reads = {
|
|||
export interface ProgressEvent extends ProgressParams { job?: string }
|
||||
export const onProgress = (cb: (p: ProgressEvent) => void): Promise<UnlistenFn> =>
|
||||
listen<{ params: ProgressParams; job?: string }>('sidecar-progress', e => cb({ ...e.params, job: e.job }));
|
||||
/** One progress line of a Fix with AI run. */
|
||||
export const onAiFix = (cb: (e: { job: string; line: string }) => void): Promise<UnlistenFn> => listen<{ job: string; line: string }>('ai-fix', cb);
|
||||
export const onDownload = (cb: (e: DownloadEvent) => void): Promise<UnlistenFn> => listen<DownloadEvent>('tool-download', cb);
|
||||
export const onDeepLink = (cb: (screen: string) => void): Promise<UnlistenFn> => listen<string>('deep-link', cb);
|
||||
/** storebound://open?path=... selected or added an app folder (its project id). */
|
||||
export const onDeepLinkFolder = (cb: (projectId: string) => void): Promise<UnlistenFn> => listen<string>('deep-link-folder', cb);
|
||||
/** A tray menu click (or the first window show after a notification) that opens a route (JSON, see parseRouteJson). */
|
||||
export const onTrayRoute = (cb: (route: string) => void): Promise<UnlistenFn> => listen<string>('tray-route', cb);
|
||||
/** A tray menu click that is not navigation: read the stores now, toggle mute. */
|
||||
export const onTrayAction = (cb: (action: 'read' | 'mute-toggle') => void): Promise<UnlistenFn> => listen<'read' | 'mute-toggle'>('tray-action', cb);
|
||||
export const onUpdateProgress = (cb: (p: { received: number; total: number | null }) => void): Promise<UnlistenFn> => listen('update-progress', cb);
|
||||
|
|
|
|||
|
|
@ -1,178 +0,0 @@
|
|||
// 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('') || '?';
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
// 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;
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
// 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(() => {}); },
|
||||
};
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
/* 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; }
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
// 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' },
|
||||
],
|
||||
};
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
// 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');
|
||||
})();
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
// 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,
|
||||
};
|
||||
}
|
||||