[tauri] KeepHerSafeApps: App words for Keep her safe, and Android's own save screen through a narrow bridge

This commit is contained in:
2026-11-17 20:31:35 +01:00
parent 0b72ae05a2
commit 3c4463dbdd
9 changed files with 341 additions and 13 deletions
+77
View File
@@ -0,0 +1,77 @@
# 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<br/>KeepSafe.svelte"] -->|"wiring.saveFile(name, text)<br/>wiring.keeping.where"| app["apps/rosea<br/>App.svelte"]
app -->|"PWA / Windows: &lt;a download&gt;"| browser["browser / WebView2 download"]
app -->|"Android: window.roseaFile.save(name, text)"| bridge["apps/rosea-tauri/android/java<br/>MainActivity.kt (copied into gen/)"]
bridge -->|"ACTION_CREATE_DOCUMENT"| saf["Android's save screen<br/>(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). |
| A6 | Windows keeps `<a download>`: 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. G-T5 (bringing her back) is closed only by a round trip seen on
the device. 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*, `persisted()` never asked | unit | `packages/ui/test/keep-safe.test.ts` |
| In a browser: the browser sentences as before | unit | same, and the existing e2e |
| `saveFile` answering `true` → *She is in that file now.*; `false` or nothing → silence | unit | same |
| The bridge's name and size rules | unit | `apps/rosea-tauri/test/android-bridge.test.ts` (reads the Kotlin source's constants) and the Kotlin itself |
| `android.ts check` refuses a project without Rosea's `MainActivity` | unit | `apps/rosea-tauri/test/android-privacy.test.ts` |
| The APK still asks for no permission | artefact | `pnpm tauri:android` → aapt2 |
| Android: save opens the system screen, a file is written, the garden says so; bring her back from that file | device | review (tablet) |
| Windows: save downloads the file | device | `e2e/apps/check-garden.ts desktop` |
@@ -0,0 +1,87 @@
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.os.Bundle
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.activity.enableEdgeToEdge
import androidx.annotation.Keep
class MainActivity : TauriActivity() {
private var webView: WebView? = null
private var busy = false
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
}
// *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
}
}
+12 -2
View File
@@ -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)"
);
}
@@ -0,0 +1,58 @@
/**
* 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-<day>.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('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');
});
});
+36 -5
View File
@@ -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 `<a download>` 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<boolean> | undefined;
function saveFile(name: string, text: string): void | Promise<boolean> {
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<boolean>((resolve) => {
const answer = (event: Event): void => {
window.removeEventListener('rosea-file-saved', answer);
saving = undefined;
resolve((event as CustomEvent<unknown>).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 });
+4
View File
@@ -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 =>
+12 -4
View File
@@ -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<void> {
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 @@
<section class="safe" aria-labelledby="{uid}-title">
<h3 id="{uid}-title">{en.rose.safe.title}</h3>
{#if persisted !== undefined}
{#if inApp}
<p>{en.rose.safe.app}</p>
{:else if persisted !== undefined}
<p>{refused ? en.rose.safe.refused : persisted === true ? en.rose.safe.kept : persisted === false ? en.rose.safe.mayClear : en.rose.safe.unknown}</p>
{/if}
{#if persisted === false && !refused}
{#if !inApp && persisted === false && !refused}
<button type="button" class="quiet" onclick={ask}>{en.rose.safe.ask}</button>
{/if}
{#if wiring.installHint}
{#if !inApp && wiring.installHint}
<p>{en.rose.safe.install}</p>
{/if}
+12 -2
View File
@@ -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<boolean>;
/** 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<boolean | null>;
readonly persist: () => Promise<boolean | null>;
};
+43
View File
@@ -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 });