diff --git a/.agents/FEATURES.md b/.agents/FEATURES.md index 88e1fd6..e4db2c0 100644 --- a/.agents/FEATURES.md +++ b/.agents/FEATURES.md @@ -5,6 +5,7 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in | Feature | Phase | Status | Analysis | Review | |:--|:--|:--|:--|:--| +| Keep her safe in the apps: true words, Android's own save screen, the page kept between the system bars | Platform track | Merged to `main` 2026-11-17; built on this machine, not distributed. Closes G-T4 and, on Android, G-T5 | [keep-her-safe-apps.md](features/keep-her-safe-apps.md) | [feature-keep-her-safe-apps.md](reviews/feature-keep-her-safe-apps.md) | | Four versions, one garden: the Tauri 2 shell (`apps/rosea-tauri`) for Android, iOS and desktop beside the PWA; a Windows build and an Android debug APK run on the tablet | Platform track | Merged to `main` 2026-11-17; built on this machine, not distributed. iOS needs a Mac (G-T1); *Keep her safe* in the apps is a release blocker (G-T4) | [tauri-platforms.md](features/tauri-platforms.md) | [feature-tauri-platforms.md](reviews/feature-tauri-platforms.md) | | Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) | | Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) | diff --git a/.agents/GAP_ANALYSIS.md b/.agents/GAP_ANALYSIS.md index 4f0aad6..9471bde 100644 --- a/.agents/GAP_ANALYSIS.md +++ b/.agents/GAP_ANALYSIS.md @@ -78,8 +78,8 @@ Svelte codebase, the apps through a Tauri 2 shell. Analysis: | G-T1 | iOS | Open. Needs macOS + Xcode, the iOS Rust targets, an Apple developer account. `pnpm tauri:ios` refuses elsewhere. | | G-T2 | macOS and Linux desktop builds | Open. Each on its own system; macOS signing/notarisation. | | G-T3 | Release signing (Android keystore, Windows certificate); AAB; stores | Open. Phase 6. Keys never in the repository. | -| G-T4 | **Keep her safe inside the apps — release blocker** | Open. Measured: *Save her to a file* does nothing on Android; the words say *this browser*; `persist()` is always `false`. Needs app copy and a working save (first plugin). No app reaches a player before this closes. | -| G-T5 | Bringing her back from a file inside the apps | Open. The Android file picker opens; no round trip seen. | +| ~~G-T4~~ | ~~Keep her safe inside the apps — release blocker~~ | Closed 2026-11-17 on `feature/keep-her-safe-apps`: the apps say *She lives in this app, on this device, until the app is removed…* and ask no browser; Android saves through its own save screen by a narrow Kotlin bridge (no plugin, no IPC, no permission) and says *She is in that file now.*; Windows downloads. Seen on the tablet (2 of 2) and on Windows (3 of 3); 572 unit tests; every drill caught after one test was tightened. | +| ~~G-T5~~ | ~~Bringing her back from a file inside the apps~~ | Closed on Android 2026-11-17: the round trip on the tablet, *Everything in that file is already here.* Windows not driven. | | G-T6 | WebView2's own traffic not measured for Rosea | Open. Flags from Amicitia's measurement are set; measure before a desktop release. | | G-T7 | No CI for the apps | Open. With G0.22. | | G-T8 | Webview storage eviction | Partly measured: `persist()` is `false` in WebView2 and Android WebView. Pressure eviction of app storage not measured. G-T4 is the answer either way. | diff --git a/.agents/features/keep-her-safe-apps.md b/.agents/features/keep-her-safe-apps.md new file mode 100644 index 0000000..60c3297 --- /dev/null +++ b/.agents/features/keep-her-safe-apps.md @@ -0,0 +1,81 @@ +# Keep her safe, inside the apps (G-T4) + +Status: built on `feature/keep-her-safe-apps`, 2026-11-17. Closes the release blocker found in +[`tauri-platforms.md`](tauri-platforms.md) G-T4 and, if a round trip is seen, G-T5. Builds on +[`keep-her-safe.md`](keep-her-safe.md). Review: +[`feature-keep-her-safe-apps.md`](../reviews/feature-keep-her-safe-apps.md). + +## 1. Why and what, in the player's terms + +*Keep her safe* is how a player makes sure their rose cannot be lost, and how she moves to another +device. In the browser it tells the truth about the browser. In the Android and desktop apps it +said the same words, and they were wrong there: *This browser may clear her if the garden is not +opened for a long time* — there is no browser, and an app's own storage is not cleared for being +left alone. It offered *Ask the browser to keep her*, which always answers no in an app. And on +Android, *Save her to a file* did nothing at all (measured on the tablet). A player was told she +might be lost, and the one remedy failed without a word. + +Now, in the apps: + +- She says where she lives, truly and calmly: *She lives in this app, on this device, until the app + is removed. A saved file keeps her anywhere.* No button that cannot work. +- *Save her to a file* opens Android's own *save* screen; the player chooses where (the phone, a + memory card, a cloud folder they already use). When the file is written, the garden says + *She is in that file now.* If they step back, nothing is said. +- *Bring her back from a file* opens Android's own file picker, as before. + +The PWA is unchanged. + +## 2. Technical architecture + +```mermaid +flowchart LR + ks["packages/ui
KeepSafe.svelte"] -->|"wiring.saveFile(name, text)
wiring.keeping.where"| app["apps/rosea
App.svelte"] + app -->|"PWA / Windows: <a download>"| browser["browser / WebView2 download"] + app -->|"Android: window.roseaFile.save(name, text)"| bridge["apps/rosea-tauri/android/java
MainActivity.kt (copied into gen/)"] + bridge -->|"ACTION_CREATE_DOCUMENT"| saf["Android's save screen
(Storage Access Framework)"] + saf -->|"uri"| bridge + bridge -->|"write, then event 'rosea-file-saved' (true|false)"| app +``` + +| # | Decision | Why | +|:--|:--|:--| +| A1 | **The words follow where she lives**: `RoseWiring.keeping.where` is `'browser'` or `'app'`, set in `App.svelte` from `__ROSEA_SHELL__`. In an app, `KeepSafe` shows `safe.app` and never asks `persist()`. | The words state facts about the platform; the platform decides which facts are true (lessons/design.md). The package chooses among its own words; the app only says where it is. | +| A2 | **Android saves through a small Kotlin bridge**, not a Tauri plugin: `MainActivity` adds one JavaScript interface, `roseaFile.save(name, text)`, which opens `ACTION_CREATE_DOCUMENT` through Tauri's own `launchActivityForResult` and writes the text to the chosen place. | No new dependency, no download, no IPC and no capability: the shell still grants the page nothing through Tauri. The Storage Access Framework needs **no permission** on any Android version (the APK check still demands none). A plugin (dialog + fs) would bring IPC, a capability, a CSP change and two packages for one file. iOS will need its own answer (G-T1). | +| A3 | **The bridge takes only what a rose file is**: a name like `rose-2026-11-17.json` and text up to 8 MB; anything else is refused before the picker opens. One save at a time. | The interface is reachable by any script in the page; the page is our own and has no network, but the bridge stays as narrow as the job. | +| A4 | **The answer comes back as a window event** (`rosea-file-saved`, `true` or `false`), dispatched by `evaluateJavascript`; `saveFile` returns a promise of it. The garden says *She is in that file now.* only on `true`. | The player sees the system screen close; without a word they cannot know whether it worked. A cancelled save is the player's choice and is not commented on. | +| A5 | `MainActivity.kt` lives in `apps/rosea-tauri/android/java/` and is copied over the generated one by `scripts/android.ts apply`; `check` refuses an APK build without it. The bridge class carries `@Keep` so a minified release build cannot strip it. | `gen/` is never committed (D6 in tauri-platforms.md). | +| A7 | **The page is kept between Android's system bars**, which show the garden's paper (light or dark with the system). Added after the tablet's screenshot showed the clock over the title and the navigation bar over *Bring her back from a file*. | Tauri's stock activity draws edge to edge, and the WebView does not reliably report the bars as `env(safe-area-inset-*)` (Culina measured the same). The colours are `--paper` from `tokens.css`, held equal by a test. | +| A6 | Windows keeps ``: WebView2 saves to *Downloads* and shows its own download flyout (measured in the platform review). | It works; the browser's own feedback is the confirmation there, as in the PWA. | + +## 3. Risk analysis + +| Risk | Answer | +|:--|:--| +| **Fear**: words that say she may be lost. | Removed in the apps (A1). The new sentence says the one true condition (removing the app) and the remedy. | +| **A broken promise**: a save that does nothing. | Fixed on Android (A2) and confirmed to the player (A4). | +| **Location in the file.** | Unchanged: the file never holds the town (keep-her-safe.md K4). | +| **Bytes leaving the device.** | Only where the player chooses in Android's save screen. If they choose a cloud folder, that app uploads it — their choice, made in the system's own screen. The game still has no `INTERNET`. | +| **A script calling the bridge.** | Only the game's own page runs in the WebView (no network, `'self'` CSP). The bridge refuses any other name or a huge text, and it can only open a screen the player must confirm. | +| **Reachability, guilt, counting.** | None: nothing new reaches anyone or counts anything. | + +## 4. Gap analysis + +Closes G-T4 for Android and Windows, and G-T5 on Android: the round trip (save through Android's +screen, bring her back from that file) passed on the tablet twice, 2026-11-17. Bringing her back on +Windows was not driven. iOS stays G-T1: WKWebView will need its own save (a share sheet or a document picker). + +## 5. Verification matrix + +| Case | Kind | Where | +|:--|:--|:--| +| In an app: the app sentence, no *Ask*, no install hint, `persisted()` and `persist()` never called | unit | `packages/ui/test/rose.test.ts` | +| The app words never speak of a browser | unit | same | +| In a browser: the browser sentences as before | unit | same (existing cases) and the e2e suite | +| `saveFile` answering `true` → *She is in that file now.*; `false` → the word goes; a browser download → nothing said | unit | same | +| The bridge's contract with the game: package = identifier, interface name `roseaFile`, event `rosea-file-saved` with `.detail === true`, the file-name rule accepts `rose-.json` and refuses five wrong names, `@Keep` on the class and method, no permission asked | unit (reads both sources) | `apps/rosea-tauri/test/android-bridge.test.ts` | +| The size limit (8 MB) and one-save-at-a-time | — | Kotlin only, not tested off the device | +| `android.ts check` refuses a project with Tauri's own `MainActivity` | script | seen: exit 1, then 0 after `apply` (review) | +| The APK still asks for no permission | artefact | `pnpm tauri:android` → aapt2 | +| Windows: the app words; *Save her to a file* starts a download | device | `e2e/apps/check-garden.ts desktop` | +| Android: the app words; save through Android's screen, *She is in that file now.*; bring her back from that file, *Everything in that file is already here.*; the file removed afterwards | device | `e2e/apps/check-garden.ts android` (uiautomator presses the system screens) | diff --git a/.agents/lessons/README.md b/.agents/lessons/README.md index 9754858..7acc84f 100644 --- a/.agents/lessons/README.md +++ b/.agents/lessons/README.md @@ -11,10 +11,10 @@ and **how to apply it**. | [`design.md`](design.md) | 1 | Wording, silence, empty states. | | [`art.md`](art.md) | 3 | The image pipeline. | | [`code.md`](code.md) | 4 | TypeScript, Svelte, async ordering, Rust. | -| [`technical.md`](technical.md) | 9 | The browser and the build as platforms. | -| [`testing.md`](testing.md) | 15 | What makes a test worth having, and how a passing test lies. | +| [`technical.md`](technical.md) | 10 | The browser and the build as platforms. | +| [`testing.md`](testing.md) | 16 | What makes a test worth having, and how a passing test lies. | | `privacy.md` | none yet | What could leave the device or make a person findable. (The geocell finding is in the review, not here: it was caught before it cost anything.) | -| [`process.md`](process.md) | 4 | Workflow, commits, credentials, honesty about what shipped. | +| [`process.md`](process.md) | 5 | Workflow, commits, credentials, honesty about what shipped. | A file is created with its first real entry. An empty lessons file only looks like knowledge. diff --git a/.agents/lessons/process.md b/.agents/lessons/process.md index 6962089..c127cf5 100644 --- a/.agents/lessons/process.md +++ b/.agents/lessons/process.md @@ -59,3 +59,14 @@ On Windows the interpreter also chooses line endings. **How to apply it.** Edit source files with the edit tool. When a script is needed, write it to a file first (the scratchpad), then run the file. + +## Git Bash rewrites Android paths + +**What happened.** On 2026-11-17 `adb shell ls -l /sdcard/Download/…` typed in Git Bash answered +`ls: C:/Program: No such file or directory`: MSYS turned `/sdcard/…` into +`C:/Program Files/Git/sdcard/…` before adb saw it. + +**Why it bit.** The rewrite is silent and the error looks like the device's. + +**How to apply it.** Prefix hand-typed adb commands with `MSYS_NO_PATHCONV=1`, or pass arguments from +Node (`spawnSync`), which the shell does not touch. diff --git a/.agents/lessons/technical.md b/.agents/lessons/technical.md index 9e804bd..8cd3bd4 100644 --- a/.agents/lessons/technical.md +++ b/.agents/lessons/technical.md @@ -124,3 +124,17 @@ a permission a library adds. **How to apply it.** Check permissions, backup flags and WebView switches on the APK and on the installed package, and name each allowed exception precisely (this package's own receiver guard, not any app's). + +## Tauri's Android activity draws under the system bars + +**What happened.** The first screenshot of the Android app on the tablet (2026-11-17) showed the clock +over the title and the navigation bar over *Bring her back from a file*. Tauri's generated +`MainActivity` calls `enableEdgeToEdge()`, and Android WebView does not reliably report the bars to +the page as `env(safe-area-inset-*)` (Culina found the same on an emulator). + +**Why it bit.** Every test before it read the page, not the screen: the button was there, enabled and +clickable by script, and hidden from a finger. + +**How to apply it.** Look at a screenshot of every new platform before calling it done. Keep the page +between the bars in the activity (padding from `WindowInsetsCompat`), paint the bars with the page's +own background, and carry the activity in `apps/rosea-tauri/android/java/` because `gen/` is regenerated. diff --git a/.agents/lessons/testing.md b/.agents/lessons/testing.md index 9777a65..db9d23e 100644 --- a/.agents/lessons/testing.md +++ b/.agents/lessons/testing.md @@ -212,3 +212,18 @@ happens first (the setup fails). On a shared device, a leftover is somebody else clean-up tolerate half-done setup (`page?.close()`, `browser?.close()`); retry connections that race a cold start (the script tries for 30 s). After every device run, check: `pidof` the app is empty, `reverse --list` and `forward --list` are empty. + +## When a hand-run probe passes and the check fails, the check is the bug + +**What happened.** On 2026-11-17 the Android round trip (`e2e/apps/check-garden.ts`) failed three +times at *Bring her back from a file*, while a probe doing the same steps by hand passed. Two +differences, both in the check: it tapped the picker while the screen was still sliding in, and it +matched nodes by description too, so it tapped DocumentsUI's *Preview the file …* button, which +comes before the file's own name in the tree. + +**Why it bit.** A check that drives someone else's screen (Android's picker) carries assumptions +about that screen. When it fails, the app is the first suspect, and the check's own guesses are not. + +**How to apply it.** When a device check fails, do the steps once by hand with screenshots before +changing the app. On a system screen, match the exact visible text, and tap only a node that stands +still across two readings. diff --git a/.agents/reviews/feature-keep-her-safe-apps.md b/.agents/reviews/feature-keep-her-safe-apps.md new file mode 100644 index 0000000..1349325 --- /dev/null +++ b/.agents/reviews/feature-keep-her-safe-apps.md @@ -0,0 +1,95 @@ +# Review — `feature/keep-her-safe-apps` + +Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/keep-her-safe-apps.md`](../features/keep-her-safe-apps.md). +Reviewed 2026-11-17 on Windows 10, Node 22.23.4, Tauri CLI 2.12.5, WebView2 157; the Android tablet is +the WAVE 10C (Android 16, WebView 140). Closes the release blocker G-T4 found in +[`feature-tauri-platforms.md`](feature-tauri-platforms.md) finding 1. No PR: the only remote is Gitea. + +## What changed for the player + +- **In the Android and Windows apps**, *Keep her safe* says *She lives in this app, on this device, + until the app is removed. A saved file keeps her anywhere.* The browser sentences, *Ask the browser + to keep her* and the iPhone install hint are gone there; `persist()` is no longer asked. +- **On Android**, *Save her to a file* opens Android's own save screen. When the file is written the + garden says *She is in that file now.*; a player who steps back hears nothing. +- **The PWA is unchanged** (its words, its download; the e2e suite still passes). + +## Gates + +Run on the branch head (based on `main` 0b72ae0, with the planet garden), 2026-11-17: + +| Gate | Result | +|:--|:--| +| `pnpm lint`, `pnpm typecheck` | 0 problems (svelte-check: 0 errors, 0 warnings, after finding 5) | +| `pnpm lint:copy` | 0 problems | +| `pnpm validate:library` | 13 of 13 fixtures rejected; 78 candidates | +| `pnpm test` (guard waited 28 s at 100 %, then started at 42 %; rerun after findings 10–12 at 71 %) | **572 passed**: identity 5, schema 19, cpu-guard 13, content 88, storage 70, art-prep 63, engine 179, **tauri 47** (+7), **ui 88** (+4 here) | +| `pnpm test:e2e` | 26 passed | +| `pnpm test:offline` | 1 passed | +| `pnpm tauri:android` | built; Kotlin compiled; `aapt2`: still no permission, no backup | +| `pnpm tauri:build` + `check-garden.ts desktop` | **3 of 3 passed**: the app's words shown, no browser words; *Save her to a file* started a download (`rose-2026-11-17.json`, cancelled by the check) | +| `check-garden.ts android` (WAVE 10C over Wi-Fi adb, unlocked by the author) | **2 of 2 passed after the fixes** (findings 10–12): opened, watered, force-stopped, reopened, still watered; the app's words; *Save her to a file* → Android's save screen → *She is in that file now.*; *Bring her back from a file* → Android's picker → *Everything in that file is already here.*; the test file removed from `Download`, the app stopped. Earlier runs: 1 failed on the adb server, 3 on findings 11 and 12. | + +**The app changed** (CLAUDE.md §5.4): the apps' *Keep her safe*. Rebuilt; **not deployed or +distributed** (G0.13; the apps exist on this machine only). + +## Bug drills + +| Put back | Result | +|:--|:--| +| `KeepSafe` ignores where she lives (browser words in the app) | CAUGHT | +| The app still asks the browser to keep her | CAUGHT | +| *She is in that file now.* said whatever the answer | CAUGHT | +| The app words speak of a browser | CAUGHT | +| The Kotlin interface renamed (`roseFile`) | CAUGHT | +| The Kotlin answers on another event | CAUGHT | +| The file-name rule lets any `.json` through | CAUGHT (by *accepts the file name the garden gives … and nothing else*) | +| `@Keep` dropped from the bridge class | CAUGHT | +| The game takes any answer but `false` as success | CAUGHT | +| `android.ts check` with Tauri's own `MainActivity` | CAUGHT (exit 1; `apply` puts Rosea's back, exit 0) | +| The page no longer kept between the bars (listener renamed; padding dropped) | CAUGHT, both — after the first test **missed** the renamed call (it matched a substring; tightened to the exact call and padding) | +| The bars' paper drifts from `tokens.css` | CAUGHT | + +**Not drilled, and nothing off the device would catch it:** the 8 MB limit and one save at a time +(Kotlin only); `evaluateJavascript` being blocked by the page's CSP (only the device run shows the +answer arriving). + +## Findings + +| # | Area | Finding | Resolution | +|:--|:--|:--|:--| +| 1 | **Soul** | The release blocker itself: words of fear and a remedy that did nothing (G-T4). | Fixed: true words in the apps, a working save on Android, a quiet confirmation. | +| 2 | Soul | Should a cancelled save say something (*Nothing was saved.*)? | No: stepping back is the player's choice; commenting on it would scold. The earlier *saved* word is cleared, so nothing false stays on screen. | +| 3 | Privacy | The bridge is a JavaScript interface any script in the WebView could call. | Only the game's page runs there (no network, `'self'` CSP). The bridge accepts only `rose-YYYY-MM-DD.json` and up to 8 MB, and can only open a screen the player must confirm. | +| 4 | Privacy | The player may choose a cloud folder in Android's save screen. | Their choice, made in the system's own screen; the file never holds the town (keep-her-safe.md K4). The game still has no `INTERNET`. | +| 5 | Correctness | svelte-check warned that `inApp` read `wiring` once (`state_referenced_locally`). | `$derived`; 0 warnings. | +| 6 | Test honesty | The desktop check failed twice reading *Her numbers* after the restart: it pressed before her care had been read back (the planet garden made the first paint earlier). | The check waits for her picture, then presses until the button says it is open, never pressing an open one; then 3 of 3 passed. | +| 7 | Correctness | Two quick taps on *Save* while Android's screen opens. | The game returns the same pending promise; Kotlin ignores a second call while busy. Not tried on the device. | +| 8 | Scope | iOS (WKWebView) will need its own save. | G-T1; noted in the analysis. | +| 9 | Process | The tablet was asleep behind a secure lock when the device check was due. | Waited for the author to unlock it; nothing was bypassed. | +| 10 | **Design** | Seen on the tablet's screenshot: the app drew **under Android's system bars** — the clock over the title, the navigation bar over *Bring her back from a file*. Tauri's stock activity turns edge-to-edge on and leaves the page under the bars. | Rosea's `MainActivity` keeps the page between the bars and paints them with the garden's paper, light or dark with the system (as Culina does); a test holds the colours equal to `tokens.css`; seen fixed on the tablet (dark theme). | +| 11 | Test honesty | The check tapped the picker's file while the screen was still sliding in. | It taps only a node that stands still across two readings. | +| 12 | Test honesty | The check matched a node by its description too, and DocumentsUI's *Preview the file …* button comes first: it opened a preview, not the file, and the check failed for a reason that was the check's own. | The file is chosen by its own text only. Found by a probe that did the steps by hand and succeeded. | +| 13 | Process | Git Bash rewrites `/sdcard/…` arguments to Windows paths for `adb shell` typed by hand. | `MSYS_NO_PATHCONV=1` for hand-typed adb; the check passes arguments from Node and is not affected. Lesson in process.md. | +| 14 | Process | The USB link hung `adb install`; the same tablet was reachable over Wi-Fi adb (another session's connection on the shared adb server). | Installed and checked over Wi-Fi; nothing in the other session's state was changed. | + +## Correctness + +- **Second run**: `android.ts apply` copies the activity each time; `check` compares bytes. +- **App closed mid-save**: the file is written on Android's side only after the player presses Save; + if the app dies before the answer, the promise never resolves and the garden simply says nothing + (the next visit is fresh). Not tried. +- **Two tabs**: an app has one window. + +## Reachability, offline + +Nothing reaches anyone. The save and the picker work with no network (the app has none). + +## What was NOT verified + +- iOS, macOS, Linux. +- A minified release APK (the `@Keep` is checked in source only). +- Saving to a cloud folder or a memory card; Android versions other than 16. +- Bringing back a file made on *another* device (the round trip used the same tablet, so it answered *already here*; the merge itself is storage's, tested in keep-her-safe.md). +- The light theme's bars on the tablet (seen in the dark theme only; the colour is tested). +- Bringing her back on Windows (WebView2's file dialog was not driven). diff --git a/CLAUDE.md b/CLAUDE.md index 33e4d5f..d83c3c8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -157,7 +157,8 @@ apps/ # dist-tauri/ for the shell: base /, no service worker, no manifest rosea-tauri/ # the Tauri 2 shell -> @rosea/tauri. Wraps apps/rosea/dist-tauri/; imports no package src-tauri/ # Rust (a window and nothing else), tauri.conf.json; no capabilities/, so no IPC - android/ # what must survive `tauri android init` (gen/ is never committed) + android/ # what must survive `tauri android init` (gen/ is never committed): the backup rules, + # and MainActivity.kt (the save bridge; the page kept between the system bars) scripts/ # icons from apps/rosea/public/icon.svg; the Android privacy patch services/ @@ -609,9 +610,10 @@ No timestamp finer than a day, no precise location, no free text, no link to the | **Base path in the shell** *(measured 2026-11-17)* | The PWA lives under `/Rosea/`; Tauri serves the game at the root of its own origin (`https://tauri.localhost/` on Windows and Android with `useHttpsScheme`, `tauri://localhost/` on macOS and iOS). A shell build with base `/Rosea/` would ask for `/Rosea/assets/…` and open a blank window. The shell's copy is built with base `/` into its own folder, so the two can never be mixed up; measured: the garden opens at `https://tauri.localhost/` on Windows and on Android. | | **A service worker inside a webview** *(answered 2026-11-17)* | Inside Tauri the files are already on the device; a worker would cache a second copy, could serve a stale game after an app update, and *A new version of the garden is ready* would offer a refresh that fetches nothing. The shell's build has no worker and no manifest: `vite-plugin-pwa` is disabled there and `registerSW` is its no-op. Measured: no registration in either app. | | **Two content-security policies** *(conflict predicted; the answer measured 2026-11-17)* | The PWA carries its policy in a `` tag (Pages sends no headers). Tauri can deliver its own policy and adds hashes for the scripts it injects; a page with **both** obeys both, and the `` would block what Tauri adds. So the shell's build has no `` policy and Tauri delivers the same string, held equal by `apps/rosea-tauri` test. Measured: no CSP violation and no request outside the origin, on Windows and on Android. | -| **IndexedDB eviction in a webview** *(partly measured 2026-11-17)* | WebView2 and Android WebView are Chromium: best-effort storage can be cleared under disk pressure, and an app's data is wiped on uninstall (the Windows uninstaller offers to delete app data). WKWebView on iOS may purge website data of an app that is not used. `persist()` answers `false` in WebView2 and in Android WebView (measured). *Keep her safe* is the real defence — and on Android saving a file through `` **does nothing** (measured on the tablet), while the words still speak of *this browser*: a release blocker (`tauri-platforms.md` G-T4). | +| **IndexedDB eviction in a webview** *(partly measured 2026-11-17)* | WebView2 and Android WebView are Chromium: best-effort storage can be cleared under disk pressure, and an app's data is wiped on uninstall (the Windows uninstaller offers to delete app data). WKWebView on iOS may purge website data of an app that is not used. `persist()` answers `false` in WebView2 and in Android WebView (measured). *Keep her safe* is the real defence. In the apps it speaks of the app, not a browser, and on Android it saves through Android's own save screen, because `` does nothing in Android WebView (measured; `keep-her-safe-apps.md`). | | **The webview phones home** *(measured in Amicitia, 2026-11-08; here: Android closed by construction, Windows unmeasured)* | A webview talks to its maker on its own: WebView2 to Microsoft and DNS-over-HTTPS providers, Android WebView to Google's metrics and an Autofill server as soon as a field takes focus. Desktop: `additionalBrowserArgs` switches these off (undocumented feature names a runtime update can break). Android: no `INTERNET` permission at all while Rosea has no network feature, plus metrics and Safe Browsing off in the manifest, applied by a committed patch because `gen/` is regenerated. Measure on every release build. | | **Auto Backup sends the garden to a cloud** *(answered 2026-11-17)* | A stock Tauri Android manifest lets Android copy the app's data — the care log, the keys, the chosen town — to the player's cloud backup, without the player choosing it. The patch sets `allowBackup="false"` and excludes every domain from cloud backup and device transfer; *Keep her safe* is how a rose moves. Measured: the installed package carries no `ALLOW_BACKUP` flag and no `INTERNET` permission (`dumpsys package`); `pnpm tauri:android` checks the APK itself with `aapt2`. | +| **Android draws under the system bars** *(measured 2026-11-17)* | Tauri's stock activity turns edge-to-edge on, and the WebView does not reliably report the bars as `env(safe-area-inset-*)`: the clock sat over the title, the navigation bar over a button. Rosea's own `MainActivity` (`apps/rosea-tauri/android/java/`, copied into `gen/` by `android.ts`) keeps the page between the bars and paints them with `--paper`. | | **iOS cannot be built on Windows** *(known)* | `tauri ios init` and every iOS build need macOS and Xcode; installing on a phone needs an Apple developer account (free for one's own device, paid for TestFlight and the App Store). `pnpm tauri:ios` refuses on Windows with this reason. | | **The bundle identifier and the origin are forever** | An Android `applicationId` or iOS bundle id cannot change after a release without becoming a different app: the old one keeps the player's rose, the new one starts empty. Chosen once (`cz.mareknovak.domi.rosea`), before the first release, even though the product name may still change. The same holds for `useHttpsScheme` (`true`): flipping it changes the webview's origin, and IndexedDB is per origin, so the rose is left behind. The shell's test pins both. | diff --git a/HANDOVER.md b/HANDOVER.md index b882213..849e1ff 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -133,13 +133,20 @@ Rewritten at the end of each session (CLAUDE.md §5.1). (`pnpm tauri:build`) and an **Android debug APK** (`pnpm tauri:android`) were built here; both passed the garden check (watered, closed, reopened, still watered; nothing outside the origin). The APK asks for no permission, not even `INTERNET`, and allows no backup (checked on the APK and - on the tablet). **iOS needs a Mac** (G-T1). **No app goes to a player yet:** inside the apps - *Keep her safe* speaks of *this browser*, and on Android saving to a file does nothing (G-T4, - a release blocker). The debug APK and installer are build output on this machine, not committed: + on the tablet). **iOS needs a Mac** (G-T1). *Keep her safe* in the apps was a release blocker + (G-T4); it is closed, see the next entry. The debug APK and installer are build output on this + machine, not committed: `apps/rosea-tauri/src-tauri/gen/android/app/build/outputs/apk/universal/debug/` and `apps/rosea-tauri/src-tauri/target/release/bundle/nsis/`. Analysis: [`.agents/features/tauri-platforms.md`](.agents/features/tauri-platforms.md). Review: [`.agents/reviews/feature-tauri-platforms.md`](.agents/reviews/feature-tauri-platforms.md). +- **Keep her safe in the apps (2026-11-17):** merged to `main`; closes the release blocker G-T4. + In the apps she *lives in this app, on this device, until the app is removed*; no browser is + asked. On Android *Save her to a file* opens Android's own save screen (a small Kotlin bridge in + `apps/rosea-tauri/android/java/MainActivity.kt`; no plugin, no permission) and the garden says + *She is in that file now.*; bringing her back from that file works. The page now stays between + Android's system bars. Seen on the tablet and on Windows. Review: + [`.agents/reviews/feature-keep-her-safe-apps.md`](.agents/reviews/feature-keep-her-safe-apps.md). - **Phase 1 is built in code.** What remains of it is the author's: verified sentences (the petal appears with them), hosting (G0.13), and the gate itself — two weeks of daily play on a phone. diff --git a/apps/rosea-tauri/android/java/MainActivity.kt b/apps/rosea-tauri/android/java/MainActivity.kt new file mode 100644 index 0000000..d561a55 --- /dev/null +++ b/apps/rosea-tauri/android/java/MainActivity.kt @@ -0,0 +1,120 @@ +package cz.mareknovak.domi.rosea + +// Rosea's own MainActivity, copied over the one `tauri android init` generates by +// apps/rosea-tauri/scripts/android.ts (gen/ is never committed; `android.ts check` compares it). +// .agents/features/keep-her-safe-apps.md A2–A5. + +import android.app.Activity +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Color +import android.os.Bundle +import android.util.Log +import android.webkit.JavascriptInterface +import android.webkit.WebView +import androidx.activity.enableEdgeToEdge +import androidx.annotation.Keep +import androidx.core.graphics.Insets +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat + +class MainActivity : TauriActivity() { + private var webView: WebView? = null + private var busy = false + + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + // Tauri's activity draws edge to edge, and the WebView does not reliably report the bars as + // env(safe-area-inset-*): the clock sat over the title and the navigation bar over *Bring her + // back from a file* (keep-her-safe-apps review). So the page is kept between the bars, and + // the bars show the garden's own paper, light or dark as the system is. + paintBehindBars() + val bars = WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout() + ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content)) { view, insets -> + val inset = insets.getInsets(bars) + view.setPadding(inset.left, inset.top, inset.right, inset.bottom) + WindowInsetsCompat.Builder(insets) + .setInsets(WindowInsetsCompat.Type.systemBars(), Insets.NONE) + .setInsets(WindowInsetsCompat.Type.displayCutout(), Insets.NONE) + .build() + } + } + + // The manifest lets the activity live through a theme change (uiMode), so the paint follows it here. + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + paintBehindBars() + } + + private fun paintBehindBars() { + val night = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES + window.decorView.setBackgroundColor(Color.parseColor(if (night) PAPER_DARK else PAPER)) + } + + // *Save her to a file*: Android WebView does nothing with a blob download, so the game asks + // here instead (window.roseaFile.save), and Android's own save screen lets the player choose + // where the file goes. No permission is needed for it on any Android version. + override fun onWebViewCreate(webView: WebView) { + this.webView = webView + webView.addJavascriptInterface(RoseFile(), "roseaFile") + } + + /** Tells the game whether the file was written (A4): true, or false when the player stepped back. */ + private fun answer(written: Boolean) { + busy = false + val view = webView ?: return + view.post { + view.evaluateJavascript("window.dispatchEvent(new CustomEvent('rosea-file-saved', { detail: $written }))", null) + } + } + + @Keep + inner class RoseFile { + /** Only a rose file: its dated name and a bounded text (A3). One save at a time. */ + @Keep + @JavascriptInterface + fun save(name: String, text: String) { + if (!NAME.matches(name) || text.length > MAX_CHARS) { + Log.w(TAG, "refused a file that is not a rose file: ${name.take(64)}, ${text.length} chars") + answer(false) + return + } + runOnUiThread { + if (busy) return@runOnUiThread + busy = true + val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "application/json" + putExtra(Intent.EXTRA_TITLE, name) + } + launchActivityForResult(intent) { result -> + val uri = result?.data?.data + if (result?.resultCode != Activity.RESULT_OK || uri == null) { + answer(false) + return@launchActivityForResult + } + val written = try { + contentResolver.openOutputStream(uri, "wt")?.use { out -> + out.write(text.toByteArray(Charsets.UTF_8)) + true + } ?: false + } catch (error: Exception) { + Log.e(TAG, "the rose file could not be written", error) + false + } + answer(written) + } + } + } + } + + companion object { + private const val TAG = "RoseaFile" + private val NAME = Regex("^rose-\\d{4}-\\d{2}-\\d{2}\\.json$") + private const val MAX_CHARS = 8 * 1024 * 1024 + // --paper in packages/ui/src/tokens.css, light and dark; a test holds them equal. + private const val PAPER = "#fbf6f1" + private const val PAPER_DARK = "#1d1819" + } +} diff --git a/apps/rosea-tauri/scripts/android.ts b/apps/rosea-tauri/scripts/android.ts index 514af70..f7e557b 100644 --- a/apps/rosea-tauri/scripts/android.ts +++ b/apps/rosea-tauri/scripts/android.ts @@ -13,7 +13,7 @@ */ import { spawnSync } from 'node:child_process'; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { apkProblems, manifestProblems, patchManifest, RULE_FILES, RULE_SECTIONS, ruleProblems } from '../src/android-privacy.js'; import { PACKAGE, SRC_TAURI, tauri } from './tauri.js'; @@ -22,6 +22,10 @@ const MANIFEST = join(MAIN, 'AndroidManifest.xml'); const RES_FROM = join(PACKAGE, 'android', 'res', 'xml'); const RES_TO = join(MAIN, 'res', 'xml'); const OUTPUTS = join(SRC_TAURI, 'gen', 'android', 'app', 'build', 'outputs', 'apk'); +// Rosea's own MainActivity: the save bridge (keep-her-safe-apps.md A2, A5). +const IDENTIFIER = (JSON.parse(readFileSync(join(SRC_TAURI, 'tauri.conf.json'), 'utf8')) as { identifier: string }).identifier; +const ACTIVITY_FROM = join(PACKAGE, 'android', 'java', 'MainActivity.kt'); +const ACTIVITY_TO = join(MAIN, 'java', ...IDENTIFIER.split('.'), 'MainActivity.kt'); function fail(problems: readonly string[]): never { for (const p of problems) console.error(`android: ${p}`); @@ -36,6 +40,10 @@ function problems(): string[] { if (!existsSync(at)) found.push(`res/xml/${f} is missing`); else if (readFileSync(at, 'utf8') !== readFileSync(join(RES_FROM, f), 'utf8')) found.push(`res/xml/${f} differs from android/res/xml/${f}`); } + if (!existsSync(ACTIVITY_TO)) found.push(`no MainActivity.kt at ${ACTIVITY_TO}`); + else if (readFileSync(ACTIVITY_TO, 'utf8') !== readFileSync(ACTIVITY_FROM, 'utf8')) { + found.push("MainActivity.kt is not Rosea's (android/java/MainActivity.kt): no save bridge"); + } // The launcher icon is Rosea's, not the Tauri logo `init` put there (scripts/icons.ts). const ours = join(SRC_TAURI, 'icons', 'android', 'mipmap-mdpi', 'ic_launcher.png'); const there = join(MAIN, 'res', 'mipmap-mdpi', 'ic_launcher.png'); @@ -55,12 +63,14 @@ function apply(): void { const after = patchManifest(before); mkdirSync(RES_TO, { recursive: true }); for (const f of RULE_FILES) copyFileSync(join(RES_FROM, f), join(RES_TO, f)); + if (!existsSync(dirname(ACTIVITY_TO))) fail([`no generated activity folder ${dirname(ACTIVITY_TO)}; the identifier changed?`]); + copyFileSync(ACTIVITY_FROM, ACTIVITY_TO); if (after !== before) writeFileSync(MANIFEST, after); const left = problems(); if (left.length > 0) fail(left); console.log( `android: privacy ${after === before ? 'already in place' : 'applied'} ` + - '(no INTERNET, no backup or transfer, WebView metrics and Safe Browsing off)' + "(no INTERNET, no backup or transfer, WebView metrics and Safe Browsing off; Rosea's MainActivity)" ); } diff --git a/apps/rosea-tauri/test/android-bridge.test.ts b/apps/rosea-tauri/test/android-bridge.test.ts new file mode 100644 index 0000000..6a59da5 --- /dev/null +++ b/apps/rosea-tauri/test/android-bridge.test.ts @@ -0,0 +1,69 @@ +/** + * The save bridge's contract between the Kotlin side (android/java/MainActivity.kt) and the game + * (apps/rosea/src/App.svelte, packages/ui KeepSafe): keep-her-safe-apps.md A2–A5. A mismatch here + * fails silently on the device — the save screen never opens, or the garden never hears back — + * so the names are read from both sources and compared. + */ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const kotlin = readFileSync(join(HERE, '..', 'android', 'java', 'MainActivity.kt'), 'utf8'); +const app = readFileSync(join(HERE, '..', '..', 'rosea', 'src', 'App.svelte'), 'utf8'); +const keepSafe = readFileSync(join(HERE, '..', '..', '..', 'packages', 'ui', 'src', 'rose', 'KeepSafe.svelte'), 'utf8'); +const conf = JSON.parse(readFileSync(join(HERE, '..', 'src-tauri', 'tauri.conf.json'), 'utf8')) as { identifier: string }; + +const nameRule = new RegExp(/Regex\("(.+?)"\)/.exec(kotlin)?.[1]?.replaceAll('\\\\', '\\') ?? 'missing'); + +describe('the Android save bridge', () => { + it('lives in the package of the app it is copied into', () => { + expect(kotlin).toMatch(new RegExp(`^package ${conf.identifier.replaceAll('.', '\\.')}$`, 'm')); + expect(kotlin).toMatch(/class MainActivity : TauriActivity\(\)/); + }); + + it('is found by the game under the name it is registered with', () => { + const registered = /addJavascriptInterface\(RoseFile\(\), "(\w+)"\)/.exec(kotlin)?.[1]; + expect(registered).toBe('roseaFile'); + expect(app).toContain(`roseaFile?: { save(name: string, text: string): void }`); + expect(app).toContain('.roseaFile'); + }); + + it('answers on the event the game listens for, with true or false', () => { + const event = /new CustomEvent\('([\w-]+)', \{ detail: \$written \}\)/.exec(kotlin)?.[1]; + expect(event).toBe('rosea-file-saved'); + expect(app.match(/'rosea-file-saved'/g)?.length).toBeGreaterThanOrEqual(2); + expect(app).toContain('.detail === true'); + }); + + it("accepts the file name the garden gives (rose-.json) and nothing else", () => { + expect(keepSafe).toContain('`rose-${today}.json`'); + expect(nameRule.test('rose-2026-11-17.json')).toBe(true); + for (const wrong of ['rose.json', '../rose-2026-11-17.json', 'rose-2026-11-17.json.exe', 'rose-2026-11-17.apk', 'evil-2026-11-17.json']) { + expect(nameRule.test(wrong)).toBe(false); + } + }); + + it('keeps the bridge through a minified release build', () => { + expect(kotlin).toMatch(/@Keep\s+inner class RoseFile/); + expect(kotlin).toMatch(/@JavascriptInterface\s+fun save\(name: String, text: String\)/); + }); + + it("paints behind the system bars with the garden's own paper, light and dark", () => { + const tokens = readFileSync(join(HERE, '..', '..', '..', 'packages', 'ui', 'src', 'tokens.css'), 'utf8'); + const papers = [...tokens.matchAll(/--paper:\s*(#[0-9a-f]{6})/gi)].map((m) => m[1]!.toLowerCase()); + expect(papers).toHaveLength(2); + expect(/PAPER = "(#[0-9a-f]{6})"/i.exec(kotlin)?.[1]?.toLowerCase()).toBe(papers[0]); + expect(/PAPER_DARK = "(#[0-9a-f]{6})"/i.exec(kotlin)?.[1]?.toLowerCase()).toBe(papers[1]); + // A source check only; the proof is the tablet's screenshot (review). Exact call and padding: + expect(kotlin).toMatch(/ViewCompat\.setOnApplyWindowInsetsListener\(findViewById\(android\.R\.id\.content\)\)/); + expect(kotlin).toMatch(/view\.setPadding\(inset\.left, inset\.top, inset\.right, inset\.bottom\)/); + }); + + it('asks Android for nothing: the save screen needs no permission', () => { + // Asking at run time or naming one; the APK check (aapt2) refuses any declared in the manifest. + expect(kotlin).not.toMatch(/requestPermissions\(|Manifest\.permission|checkSelfPermission/); + expect(kotlin).toContain('Intent.ACTION_CREATE_DOCUMENT'); + }); +}); diff --git a/apps/rosea/src/App.svelte b/apps/rosea/src/App.svelte index ee17a8c..de678cc 100644 --- a/apps/rosea/src/App.svelte +++ b/apps/rosea/src/App.svelte @@ -54,15 +54,17 @@ } // --- Keeping her (keep-her-safe.md) ------------------------------------- + // The Android, iOS and desktop apps are installed by being apps (tauri-platforms.md D9): + // they ask to keep the garden after the first care, as an installed PWA does, and never + // show the hint to add the page to the home screen. Keep her safe speaks of the app, not a + // browser (keep-her-safe-apps.md A1). + const inApp = __ROSEA_SHELL__ === 'tauri'; const browserStorage = typeof navigator !== 'undefined' ? navigator.storage : undefined; const keeping: RoseWiring['keeping'] = { + where: inApp ? 'app' : 'browser', persisted: async () => (browserStorage?.persisted ? browserStorage.persisted() : null), persist: async () => (browserStorage?.persist ? browserStorage.persist() : null) }; - // The Android, iOS and desktop apps are installed by being apps (tauri-platforms.md D9): - // they ask to keep the garden after the first care, as an installed PWA does, and never - // show the hint to add the page to the home screen. - const inApp = __ROSEA_SHELL__ === 'tauri'; const installed = (): boolean => inApp || matchMedia('(display-mode: standalone)').matches || @@ -76,7 +78,36 @@ keeping.persist().catch((error: unknown) => console.error('keep: asking the browser to keep the garden failed', error)); } - function saveFile(name: string, text: string): void { + /** + * Android's save screen, through the app's own bridge (keep-her-safe-apps.md A2): present + * only in the Android app, where `` does nothing. It answers with a window event, + * true when the file was written, false when the player stepped back (A4). + */ + const androidFile = inApp ? (window as Window & { roseaFile?: { save(name: string, text: string): void } }).roseaFile : undefined; + let saving: Promise | undefined; + + function saveFile(name: string, text: string): void | Promise { + if (androidFile) { + // One save at a time: a second tap while the screen is open waits for the first answer. + if (saving) return saving; + saving = new Promise((resolve) => { + const answer = (event: Event): void => { + window.removeEventListener('rosea-file-saved', answer); + saving = undefined; + resolve((event as CustomEvent).detail === true); + }; + window.addEventListener('rosea-file-saved', answer); + try { + androidFile.save(name, text); + } catch (error) { + console.error('keep: the app could not open the save screen', error); + window.removeEventListener('rosea-file-saved', answer); + saving = undefined; + resolve(false); + } + }); + return saving; + } // A file made here and handed over; nothing is sent anywhere. const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); const a = Object.assign(document.createElement('a'), { href: url, download: name }); diff --git a/e2e/apps/check-garden.ts b/e2e/apps/check-garden.ts index 1434301..de6004f 100644 --- a/e2e/apps/check-garden.ts +++ b/e2e/apps/check-garden.ts @@ -81,37 +81,135 @@ async function firstVisit(page: Page): Promise { } /** After the app was closed and opened again: she is still watered. */ +/** On a failure, what the screen showed: a picture in the temporary folder, its path in the report. */ +let lastPage: Page | undefined; + async function secondVisit(page: Page): Promise { + lastPage = page; await garden(page); // By keyboard: on the tablet a pointer click once waited 30 s for the button to stop moving // while the garden animated (review). Enter is a real activation, as for a keyboard player. + // Her picture first: the garden's heading comes before her care is read back, and a press in + // that moment was lost twice on the desktop (keep-her-safe-apps review). Then press until the + // button says it is open: a press is only repeated while it still says closed. + await expect(page.getByRole('img', { name: /^The rose/ })).toBeVisible({ timeout: 20_000 }); const numbers = page.getByRole('button', { name: en.rose.numbers }); - await numbers.focus(); - await numbers.press('Enter'); + await expect(async () => { + if ((await numbers.getAttribute('aria-expanded')) !== 'true') await press(numbers); + await expect(numbers).toHaveAttribute('aria-expanded', 'true', { timeout: 1_000 }); + }).toPass({ timeout: 15_000 }); await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`); await storedCare(page, 1); report['afterRestart'] = 'still watered: 1 day of care, the care log kept'; } -/** What *Save her to a file* does here (G-T4): a download event, or nothing. */ -async function trySave(page: Page): Promise { +/** + * Presses a button from the keyboard. On the tablet a pointer click waits for the button to stop + * moving, and the planet keeps it moving (review); Enter is a real activation, as for a keyboard player. + */ +async function press(button: ReturnType): Promise { + await button.focus(); + await button.press('Enter'); +} + +/** Opens *Keep her safe* and checks the app's own words (keep-her-safe-apps.md A1). */ +async function openKeepSafe(page: Page): Promise { const title = page.getByRole('button', { name: en.rose.safe.title }); - if (!(await title.isVisible().catch(() => false))) { - report['saveToFile'] = 'Keep her safe not visible'; - return; + await expect(async () => { + if ((await title.getAttribute('aria-expanded')) !== 'true') await press(title); + await expect(title).toHaveAttribute('aria-expanded', 'true', { timeout: 1_000 }); + }).toPass({ timeout: 15_000 }); + await expect(page.getByText(en.rose.safe.app)).toBeVisible(); + for (const browserWords of [en.rose.safe.mayClear, en.rose.safe.unknown, en.rose.safe.kept, en.rose.safe.ask]) { + await expect(page.getByText(browserWords)).toHaveCount(0); + } + report['keepHerSafeWords'] = en.rose.safe.app; +} + +/** Desktop: *Save her to a file* starts a WebView2 download (cancelled by the check). */ +async function desktopSave(page: Page): Promise { + await openKeepSafe(page); + const download = page.waitForEvent('download', { timeout: 10_000 }); + await press(page.getByRole('button', { name: en.rose.safe.save })); + const d = await download; + report['saveToFile'] = `a download started: ${d.suggestedFilename()} (cancelled by the check)`; + await d.cancel(); +} + +interface UiNode { + readonly text: string; + readonly desc: string; + readonly cx: number; + readonly cy: number; +} + +/** The screen's accessibility nodes, through uiautomator, printed to stdout (no file left behind). */ +function screenNodes(adb: (...args: string[]) => string): UiNode[] { + const xml = adb('exec-out', 'uiautomator', 'dump', '/dev/tty'); + const nodes: UiNode[] = []; + for (const m of xml.matchAll(/]*?text="([^"]*)"[^>]*?content-desc="([^"]*)"[^>]*?bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/g)) { + const [x1, y1, x2, y2] = [m[3], m[4], m[5], m[6]].map(Number) as [number, number, number, number]; + nodes.push({ text: m[1] ?? '', desc: m[2] ?? '', cx: Math.round((x1 + x2) / 2), cy: Math.round((y1 + y2) / 2) }); + } + return nodes; +} + +/** + * Taps the first node on Android's own screen that matches, waiting up to `ms` for it. Only once + * it stands still: a system screen slides in, and a tap read from the first frame landed where the + * file had been a moment before (keep-her-safe-apps review). + */ +async function tapSystem(adb: (...args: string[]) => string, match: (n: UiNode) => boolean, what: string, ms = 20_000): Promise { + const until = Date.now() + ms; + let last: UiNode | undefined; + while (Date.now() < until) { + const node = screenNodes(adb).find(match); + if (node && last && node.cx === last.cx && node.cy === last.cy) { + adb('shell', 'input', 'tap', String(node.cx), String(node.cy)); + return; + } + last = node; + await new Promise((r) => setTimeout(r, 700)); + } + throw new Error(`Android's screen never showed ${what}, still`); +} + +/** + * Android: the round trip (keep-her-safe-apps.md §5). *Save her to a file* opens Android's save + * screen; the check presses its Save; the garden says she is in that file. Then *Bring her back + * from a file* opens the picker; the check chooses that file; the garden says everything in it is + * already here. The file is removed from the tablet afterwards if this run made it. + */ +async function androidRoundTrip(page: Page, adb: (...args: string[]) => string): Promise { + await openKeepSafe(page); + const name = `rose-${await page.evaluate(() => { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + })}.json`; + const before = adb('shell', 'ls', '/sdcard/Download/'); + const existed = before.split(/\s+/).includes(name); + if (existed) throw new Error(`/sdcard/Download/${name} is already on the tablet; the check will not overwrite a file it did not make`); + try { + await press(page.getByRole('button', { name: en.rose.safe.save })); + await tapSystem(adb, (n) => /^save$/i.test(n.text), "the save screen's Save button"); + await expect(page.locator('.safe [role="status"]')).toHaveText(en.rose.safe.saved, { timeout: 15_000 }); + report['saveToFile'] = `Android's save screen; the garden said: ${en.rose.safe.saved}`; + + await page.locator('input[type="file"]').click({ force: true }); + // By its own text only: a card's preview button is described as "Preview the file …" and comes first. + await tapSystem(adb, (n) => n.text === name, `the file ${name} in the picker`); + // Read from Keep her safe's own status line: it may be below the fold on a small screen. + await expect(page.locator('.safe [role="status"]')).toHaveText(en.rose.safe.alreadyHere, { timeout: 15_000 }); + report['bringBack'] = `chose ${name} in Android's picker; the garden said: ${en.rose.safe.alreadyHere}`; + } finally { + const after = adb('shell', 'ls', '/sdcard/Download/').split(/\s+/); + if (after.includes(name)) { + adb('shell', 'rm', `/sdcard/Download/${name}`); + report['cleanedUp'] = `/sdcard/Download/${name}`; + } else { + report['cleanedUp'] = `nothing at /sdcard/Download/${name} (saved elsewhere, or not saved)`; + } } - await title.click(); - const save = page.getByRole('button', { name: en.rose.safe.save }); - await expect(save).toBeVisible(); - const download = page.waitForEvent('download', { timeout: 5_000 }).then( - async (d) => { - await d.cancel(); - return `a download started: ${d.suggestedFilename()} (cancelled by the check)`; - }, - () => 'nothing happened within 5 s' - ); - await save.click(); - report['saveToFile'] = await download; } async function desktop(exe: string): Promise { @@ -153,7 +251,7 @@ async function desktop(exe: string): Promise { app = start(); session = await attach(); await secondVisit(session.page); - await trySave(session.page); + await desktopSave(session.page); await session.close(); report['dataFolder'] = data; } finally { @@ -203,7 +301,7 @@ async function androidDevice(serial: string | undefined): Promise { await new Promise((r) => setTimeout(r, 1500)); session = await open(); await secondVisit(session.page); - await trySave(session.page); + await androidRoundTrip(session.page, adb); } finally { adb('shell', 'am', 'force-stop', PACKAGE_ID); await session?.close().catch((error: unknown) => console.error('check-garden: closing the device handle failed', error)); @@ -222,6 +320,13 @@ try { console.log(JSON.stringify(report, null, 2)); console.log(`check-garden ${target}: PASSED`); } catch (error) { + if (lastPage) { + const shot = join(tmpdir(), `rosea-check-${target ?? 'unknown'}-failure.png`); + await lastPage.screenshot({ path: shot }).then( + () => (report['failureScreenshot'] = shot), + (e: unknown) => (report['failureScreenshot'] = `could not take one: ${String(e)}`) + ); + } console.log(JSON.stringify(report, null, 2)); console.error(`check-garden ${target}: FAILED — ${(error as Error).message}`); process.exitCode = 1; diff --git a/packages/ui/src/copy/en.ts b/packages/ui/src/copy/en.ts index 33f7845..58aec54 100644 --- a/packages/ui/src/copy/en.ts +++ b/packages/ui/src/copy/en.ts @@ -83,7 +83,11 @@ export const en = { ask: 'Ask the browser to keep her', refused: 'The browser did not promise. A saved file keeps her for sure.', install: 'On an iPhone or iPad, add the garden to your Home Screen to keep her.', + /** In the Android, iOS and desktop apps (keep-her-safe-apps.md A1): no browser, and nothing clears her for being left alone. */ + app: 'She lives in this app, on this device, until the app is removed. A saved file keeps her anywhere.', save: 'Save her to a file', + /** Said only when the app knows the file was written (A4); a cancelled save is not commented on. */ + saved: 'She is in that file now.', fileNote: 'The file holds her care and when it was given. It never holds your town.', bringBack: 'Bring her back from a file', broughtBack: (n: number): string => diff --git a/packages/ui/src/rose/KeepSafe.svelte b/packages/ui/src/rose/KeepSafe.svelte index 4b3366c..459a5d9 100644 --- a/packages/ui/src/rose/KeepSafe.svelte +++ b/packages/ui/src/rose/KeepSafe.svelte @@ -14,7 +14,11 @@ let refused = $state(false); let said = $state(''); + const inApp = $derived(wiring.keeping.where === 'app'); + $effect(() => { + // In an app there is no browser to ask, and the answer would always be no (A1). + if (inApp) return; wiring.keeping.persisted().then( (p) => (persisted = p), (error: unknown) => { @@ -38,7 +42,9 @@ async function save(): Promise { try { const file = await wiring.exportRose(currentKey); - wiring.saveFile(`rose-${today}.json`, JSON.stringify(file, null, 1)); + said = ''; + const written = await wiring.saveFile(`rose-${today}.json`, JSON.stringify(file, null, 1)); + if (written === true) said = en.rose.safe.saved; } catch (error) { console.error('keep: the rose could not be saved to a file', error); } @@ -64,13 +70,15 @@

{en.rose.safe.title}

- {#if persisted !== undefined} + {#if inApp} +

{en.rose.safe.app}

+ {:else if persisted !== undefined}

{refused ? en.rose.safe.refused : persisted === true ? en.rose.safe.kept : persisted === false ? en.rose.safe.mayClear : en.rose.safe.unknown}

{/if} - {#if persisted === false && !refused} + {#if !inApp && persisted === false && !refused} {/if} - {#if wiring.installHint} + {#if !inApp && wiring.installHint}

{en.rose.safe.install}

{/if} diff --git a/packages/ui/src/rose/types.ts b/packages/ui/src/rose/types.ts index 1866ff9..8f21024 100644 --- a/packages/ui/src/rose/types.ts +++ b/packages/ui/src/rose/types.ts @@ -30,10 +30,20 @@ export interface RoseWiring { }; /** Hears care, a petal or a rose brought back in another tab (two-tabs.md); returns the way to stop. */ readonly changes?: (listener: () => void) => () => void; - /** Hands the player a file to keep. */ - readonly saveFile: (name: string, text: string) => void; + /** + * Hands the player a file to keep. Where the app learns the outcome (Android's save screen, + * keep-her-safe-apps.md A4) it answers true when written and false when the player stepped back; + * where it cannot know (a browser download) it answers nothing. + */ + readonly saveFile: (name: string, text: string) => void | Promise; /** The browser's promise to keep the garden: true, false, or null when it cannot say. */ readonly keeping: { + /** + * Where she lives (keep-her-safe-apps.md A1): `'browser'` (the default) or `'app'`, the + * Android, iOS and desktop apps, where there is no browser to ask and nothing clears her + * for being left alone. + */ + readonly where?: 'browser' | 'app'; readonly persisted: () => Promise; readonly persist: () => Promise; }; diff --git a/packages/ui/test/rose.test.ts b/packages/ui/test/rose.test.ts index 20d5317..fbe566d 100644 --- a/packages/ui/test/rose.test.ts +++ b/packages/ui/test/rose.test.ts @@ -229,6 +229,49 @@ describe('keep her safe (keep-her-safe.md)', () => { await waitFor(() => expect(document.getElementById('rose-numbers')?.textContent).toContain(`${en.rose.daysOfCare}1`)); }); + it('in an app, says where she lives and asks no browser, which is not there (keep-her-safe-apps.md A1)', async () => { + const persisted = vi.fn(async () => false); + const persist = vi.fn(async () => false); + render(Rose, { wiring: wiring({ keeping: { where: 'app', persisted, persist }, installHint: true }), timeZone: ZONE }); + await open(); + expect(await screen.findByText(en.rose.safe.app)).toBeTruthy(); + for (const said of [en.rose.safe.mayClear, en.rose.safe.unknown, en.rose.safe.kept, en.rose.safe.install]) { + expect(screen.queryByText(said)).toBeNull(); + } + expect(screen.queryByRole('button', { name: en.rose.safe.ask })).toBeNull(); + expect(screen.getByRole('button', { name: en.rose.safe.save })).toBeTruthy(); + expect(screen.getByLabelText(en.rose.safe.bringBack)).toBeTruthy(); + expect(persisted).not.toHaveBeenCalled(); + expect(persist).not.toHaveBeenCalled(); + }); + + it('the app words never speak of a browser', () => { + expect(en.rose.safe.app).not.toMatch(/browser/i); + expect(en.rose.safe.saved).not.toMatch(/browser/i); + }); + + it('says she is in the file only when the app knows it was written (A4)', async () => { + let answer = true; + render(Rose, { wiring: wiring({ saveFile: async () => answer }), timeZone: ZONE }); + await open(); + const save = screen.getByRole('button', { name: en.rose.safe.save }); + await fireEvent.click(save); + expect(await screen.findByText(en.rose.safe.saved)).toBeTruthy(); + // A second save the player steps back from: the earlier word goes, and nothing is said. + answer = false; + await fireEvent.click(save); + await waitFor(() => expect(screen.queryByText(en.rose.safe.saved)).toBeNull()); + }); + + it('a browser download says nothing of its own: the browser shows it', async () => { + const w = wiring(); + render(Rose, { wiring: w, timeZone: ZONE }); + await open(); + await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.save })); + await waitFor(() => expect(w.saved).toHaveLength(1)); + expect(screen.queryByText(en.rose.safe.saved)).toBeNull(); + }); + it('a file that is not a rose is said calmly, and nothing changes', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); render(Rose, { wiring: wiring({ importRose: () => Promise.reject(new TypeError('storage: this file does not hold a rose')) }), timeZone: ZONE });