Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
839a3c63f9 | ||
|
|
a167ebd0a3 | ||
|
|
881a240155 | ||
|
|
117b546b2c |
@@ -10,6 +10,7 @@ FROM ghcr.io/catthehacker/ubuntu:go-24.04
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
stunnel4 \
|
||||
netcat-openbsd \
|
||||
age \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Dagger CLI — pinned to match the engine version on the runner host
|
||||
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
echo "Changed files:"
|
||||
echo "$CHANGED"
|
||||
|
||||
android_re='^(android/|integration_test/|lib/|pubspec\.yaml|pubspec\.lock|drift_schemas/|scripts/deploy_playstore\.py)'
|
||||
android_re='^(android/|integration_test/|lib/|pubspec\.yaml|pubspec\.lock|drift_schemas/)'
|
||||
linux_re='^(linux/|lib/|pubspec\.yaml|pubspec\.lock)'
|
||||
|
||||
echo "$CHANGED" | grep -qE "$android_re" \
|
||||
@@ -65,6 +65,7 @@ jobs:
|
||||
run: |
|
||||
command -v dagger >/dev/null 2>&1 || { echo "ERROR: dagger is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v task >/dev/null 2>&1 || { echo "ERROR: task is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v age >/dev/null 2>&1 || { echo "ERROR: age is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
dpkg -s stunnel4 netcat-openbsd >/dev/null 2>&1 || { echo "ERROR: stunnel4/netcat-openbsd are not installed in the runner image. Add them to .forgejo/Dockerfile."; exit 1; }
|
||||
|
||||
- name: Setup Dagger Remote Engine (via stunnel)
|
||||
@@ -75,11 +76,15 @@ jobs:
|
||||
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
|
||||
run: scripts/setup_dagger_remote.sh
|
||||
|
||||
- name: Run Android Tests on Firebase Test Lab
|
||||
if: ${{ secrets.FIREBASE_TEST_LAB_SERVICE_ACCOUNT_KEY != '' }}
|
||||
- name: Decrypt production secrets
|
||||
if: ${{ secrets.SECRETS_AGE_KEY != '' }}
|
||||
env:
|
||||
SECRETS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY }}
|
||||
run: scripts/secrets-decrypt.sh
|
||||
|
||||
- name: Run Android Tests on Firebase Test Lab
|
||||
if: env.FIREBASE_TEST_LAB_SERVICE_ACCOUNT_KEY != ''
|
||||
env:
|
||||
FIREBASE_TEST_LAB_SERVICE_ACCOUNT_KEY: ${{ secrets.FIREBASE_TEST_LAB_SERVICE_ACCOUNT_KEY }}
|
||||
FIREBASE_PROJECT_ID: ${{ vars.FIREBASE_PROJECT_ID }}
|
||||
DAGGER_NO_NAG: "1"
|
||||
run: task test-android-firebase
|
||||
|
||||
@@ -97,12 +102,13 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 100
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Check runner tools
|
||||
run: |
|
||||
command -v dagger >/dev/null 2>&1 || { echo "ERROR: dagger is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v task >/dev/null 2>&1 || { echo "ERROR: task is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v age >/dev/null 2>&1 || { echo "ERROR: age is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
dpkg -s stunnel4 netcat-openbsd >/dev/null 2>&1 || { echo "ERROR: stunnel4/netcat-openbsd are not installed in the runner image. Add them to .forgejo/Dockerfile."; exit 1; }
|
||||
|
||||
- name: Setup Dagger Remote Engine (via stunnel)
|
||||
@@ -113,12 +119,15 @@ jobs:
|
||||
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
|
||||
run: scripts/setup_dagger_remote.sh
|
||||
|
||||
- name: Publish Android to Play Store
|
||||
if: ${{ secrets.PLAY_STORE_CONFIG_JSON != '' }}
|
||||
- name: Decrypt production secrets
|
||||
if: ${{ secrets.SECRETS_AGE_KEY != '' }}
|
||||
env:
|
||||
SECRETS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY }}
|
||||
run: scripts/secrets-decrypt.sh
|
||||
|
||||
- name: Publish Android to Play Store
|
||||
if: env.PLAY_STORE_CONFIG_JSON != ''
|
||||
env:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
PLAY_STORE_CONFIG_JSON: ${{ secrets.PLAY_STORE_CONFIG_JSON }}
|
||||
DAGGER_NO_NAG: "1"
|
||||
run: task publish-android
|
||||
|
||||
@@ -136,12 +145,13 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 100
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Check runner tools
|
||||
run: |
|
||||
command -v dagger >/dev/null 2>&1 || { echo "ERROR: dagger is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v task >/dev/null 2>&1 || { echo "ERROR: task is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v age >/dev/null 2>&1 || { echo "ERROR: age is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
dpkg -s stunnel4 netcat-openbsd >/dev/null 2>&1 || { echo "ERROR: stunnel4/netcat-openbsd are not installed in the runner image. Add them to .forgejo/Dockerfile."; exit 1; }
|
||||
|
||||
- name: Setup Dagger Remote Engine (via stunnel)
|
||||
@@ -152,15 +162,15 @@ jobs:
|
||||
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
|
||||
run: scripts/setup_dagger_remote.sh
|
||||
|
||||
- name: Build & Deploy APK to server
|
||||
if: ${{ secrets.SSH_PRIVATE_KEY != '' }}
|
||||
- name: Decrypt production secrets
|
||||
if: ${{ secrets.SECRETS_AGE_KEY != '' }}
|
||||
env:
|
||||
SECRETS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY }}
|
||||
run: scripts/secrets-decrypt.sh
|
||||
|
||||
- name: Build & Deploy APK to server
|
||||
if: env.SSH_PRIVATE_KEY != ''
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
|
||||
SSH_USER: ${{ secrets.SSH_USER }}
|
||||
SSH_HOST: ${{ secrets.SSH_HOST }}
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
DAGGER_NO_NAG: "1"
|
||||
run: task deploy-apk
|
||||
|
||||
@@ -178,12 +188,13 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 100
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Check runner tools
|
||||
run: |
|
||||
command -v dagger >/dev/null 2>&1 || { echo "ERROR: dagger is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v task >/dev/null 2>&1 || { echo "ERROR: task is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v age >/dev/null 2>&1 || { echo "ERROR: age is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
dpkg -s stunnel4 netcat-openbsd >/dev/null 2>&1 || { echo "ERROR: stunnel4/netcat-openbsd are not installed in the runner image. Add them to .forgejo/Dockerfile."; exit 1; }
|
||||
|
||||
- name: Setup Dagger Remote Engine (via stunnel)
|
||||
@@ -194,13 +205,15 @@ jobs:
|
||||
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
|
||||
run: scripts/setup_dagger_remote.sh
|
||||
|
||||
- name: Build & Deploy Linux to server
|
||||
if: ${{ secrets.SSH_PRIVATE_KEY != '' }}
|
||||
- name: Decrypt production secrets
|
||||
if: ${{ secrets.SECRETS_AGE_KEY != '' }}
|
||||
env:
|
||||
SECRETS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY }}
|
||||
run: scripts/secrets-decrypt.sh
|
||||
|
||||
- name: Build & Deploy Linux to server
|
||||
if: env.SSH_PRIVATE_KEY != ''
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
|
||||
SSH_USER: ${{ secrets.SSH_USER }}
|
||||
SSH_HOST: ${{ secrets.SSH_HOST }}
|
||||
DAGGER_NO_NAG: "1"
|
||||
run: task deploy-linux
|
||||
|
||||
@@ -226,6 +239,7 @@ jobs:
|
||||
run: |
|
||||
command -v dagger >/dev/null 2>&1 || { echo "ERROR: dagger is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v task >/dev/null 2>&1 || { echo "ERROR: task is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
command -v age >/dev/null 2>&1 || { echo "ERROR: age is not installed in the runner image. Add it to .forgejo/Dockerfile."; exit 1; }
|
||||
dpkg -s stunnel4 netcat-openbsd >/dev/null 2>&1 || { echo "ERROR: stunnel4/netcat-openbsd are not installed in the runner image. Add them to .forgejo/Dockerfile."; exit 1; }
|
||||
|
||||
- name: Setup Dagger Remote Engine (via stunnel)
|
||||
@@ -236,13 +250,15 @@ jobs:
|
||||
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
|
||||
run: scripts/setup_dagger_remote.sh
|
||||
|
||||
- name: Generate build history and deploy website
|
||||
if: ${{ secrets.SSH_PRIVATE_KEY != '' }}
|
||||
- name: Decrypt production secrets
|
||||
if: ${{ secrets.SECRETS_AGE_KEY != '' }}
|
||||
env:
|
||||
SECRETS_AGE_KEY: ${{ secrets.SECRETS_AGE_KEY }}
|
||||
run: scripts/secrets-decrypt.sh
|
||||
|
||||
- name: Generate build history and deploy website
|
||||
if: env.SSH_PRIVATE_KEY != ''
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
|
||||
SSH_USER: ${{ secrets.SSH_USER }}
|
||||
SSH_HOST: ${{ secrets.SSH_HOST }}
|
||||
DAGGER_NO_NAG: "1"
|
||||
run: task publish-website
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
name: Monitor Agent Loop
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 */2 * * *' # every 2 hours
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
monitor:
|
||||
name: Check Agent Loop Health
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Check agent loop heartbeat
|
||||
run: python3 scripts/agent_loop.py monitor
|
||||
+2
-2
@@ -22,14 +22,14 @@ assets/changelog.txt
|
||||
.env.local
|
||||
.envrc
|
||||
.direnv/
|
||||
secrets.env # plaintext secrets — encrypted version (secrets.age) is committed
|
||||
|
||||
# --- Android ---
|
||||
android/.gradle/
|
||||
android/local.properties
|
||||
android/app/google-services.json
|
||||
android/key.properties
|
||||
# android/app/src/main/java/io/flutter/plugins/ intentionally tracked so that
|
||||
# GeneratedPluginRegistrant.java (catch Throwable) is committed and used by CI.
|
||||
android/app/src/main/java/io/flutter/plugins/
|
||||
.android/
|
||||
Android/
|
||||
.gradle/
|
||||
|
||||
@@ -10,21 +10,9 @@ CLI tool `fgj` is available to query issues/PRs/actions.
|
||||
|
||||
We use issues, follow this label state machine:
|
||||
|
||||
- **State/ToPlan** — Issue needs a plan written by an agent before implementation
|
||||
- **State/Planned** — Plan has been posted as a comment; awaiting human review
|
||||
- **State/Ready** — Issue is approved and ready for implementation
|
||||
- **State/InProgress** — Set while an agent (or human) is actively working
|
||||
- **State/Question** — Agent hit a blocker or needs clarification
|
||||
|
||||
Full lifecycle:
|
||||
|
||||
```
|
||||
State/ToPlan → State/Planned (automated: agent_loop.py runs a planning agent)
|
||||
State/Planned → State/Ready (manual: human reviews the plan and approves)
|
||||
State/Ready → State/InProgress (automated: agent_loop.py before starting implementation)
|
||||
State/InProgress → closed (automated: after PR is merged and CI passes)
|
||||
any state → State/Question (automated or manual: when blocked)
|
||||
```
|
||||
- **State/Ready** — Issue is available to pick up
|
||||
- **State/InProgress** — Set this when you start working on an issue
|
||||
- **State/Question** — Set this when you hit a blocker or need clarification
|
||||
|
||||
List open issues ready to pick up:
|
||||
|
||||
@@ -34,11 +22,9 @@ fgj issue list --json --state open | jq '[.[] | select(.labels[].name == "State/
|
||||
|
||||
Rules:
|
||||
|
||||
- Never start implementation on an issue without `State/Ready`
|
||||
- Planning agents only post a plan comment — they do NOT write code or open PRs
|
||||
- After `State/Planned`, a human must review the plan and manually add `State/Ready`
|
||||
- When working via the agent loop: label transitions are set automatically
|
||||
by `agent_loop.py` — do **not** set them yourself.
|
||||
- Never start work on an issue without `State/Ready`
|
||||
- When working via the agent loop: `State/Ready` → `State/InProgress` is set automatically
|
||||
by `agent_loop.py` before the agent starts — do **not** set it yourself.
|
||||
- When working manually: switch to `State/InProgress` as your **first action**:
|
||||
```bash
|
||||
fgj issue edit <NUMBER> --remove-label "State/Ready" --add-label "State/InProgress"
|
||||
|
||||
@@ -174,10 +174,70 @@ Run a secret manager co-located with the Dagger host. The CI job authenticates w
|
||||
- Vault itself becomes a security-critical single point of failure.
|
||||
- Operational overhead likely disproportionate for a small single-developer project.
|
||||
|
||||
### Option 5: Encrypted secrets file (age) — **implemented**
|
||||
|
||||
Store all production secrets in a file (`secrets.env`) that is encrypted with
|
||||
[age](https://age-encryption.org/) into `secrets.age`. The encrypted file is
|
||||
committed to the repository. Only the age private key — a single string — is
|
||||
stored in Codeberg as `SECRETS_AGE_KEY`. Any CI job or developer with the key
|
||||
can decrypt the file and obtain all secrets.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. Generate a key pair once:
|
||||
```bash
|
||||
age-keygen -o ~/.config/age/sharedinbox.key
|
||||
age-keygen -y ~/.config/age/sharedinbox.key > .age-public-key
|
||||
```
|
||||
2. Copy `secrets.env.example` to `secrets.env`, fill in all values, then encrypt:
|
||||
```bash
|
||||
scripts/secrets-encrypt.sh # reads public key from .age-public-key
|
||||
git add secrets.age && git commit -m "chore: update encrypted secrets"
|
||||
```
|
||||
3. Add the private key content as `SECRETS_AGE_KEY` in Codeberg repository secrets.
|
||||
4. CI jobs call `scripts/secrets-decrypt.sh` (with `SECRETS_AGE_KEY` set) before
|
||||
any step that needs production credentials. The script writes each variable
|
||||
to `$GITHUB_ENV` so subsequent steps see them automatically.
|
||||
|
||||
**Keeping local and CI in sync:**
|
||||
When you rotate a secret locally, update `secrets.env`, re-run
|
||||
`scripts/secrets-encrypt.sh`, and commit the new `secrets.age`. CI will pick
|
||||
up the fresh secrets on the next push — no manual CI variable updates needed.
|
||||
|
||||
Multi-line values (SSH keys, certificates) must be stored as a single line
|
||||
with `\n` escape sequences inside double quotes. Example:
|
||||
```
|
||||
SSH_PRIVATE_KEY="<header>\n<base64 key body>\n<footer>"
|
||||
```
|
||||
|
||||
**Pro:**
|
||||
- One secret (`SECRETS_AGE_KEY`) in Codeberg instead of many.
|
||||
- Encrypted secrets are version-controlled — rotating a secret is a git commit.
|
||||
- Local dev environment and CI always use the same encrypted source of truth.
|
||||
- `age` is a simple, audited tool with no server infrastructure.
|
||||
- The private key never appears in workflow files or logs.
|
||||
|
||||
**Con:**
|
||||
- `secrets.age` exposes the list of variable *names* (visible in the encrypted
|
||||
file if the format leaks, though not the values).
|
||||
- All credentials share a single key — compromising `SECRETS_AGE_KEY` exposes
|
||||
everything at once.
|
||||
- Key rotation requires re-encrypting `secrets.age` and updating the CI secret.
|
||||
|
||||
### Recommendation
|
||||
|
||||
**Option 1** (runner-level env vars) or **Option 2** (secret files) are the pragmatic starting point for a single self-hosted runner. They require no new infrastructure and move all production secrets off Codeberg immediately.
|
||||
**Option 5** (encrypted secrets file) is now the active approach. It reduces
|
||||
Codeberg secrets to exactly two categories:
|
||||
- **Dagger access credentials** — `DAGGER_STUNNEL_URL`, `DAGGER_CA_CERT`,
|
||||
`DAGGER_CLIENT_CERT`, `DAGGER_CLIENT_KEY`.
|
||||
- **Master key** — `SECRETS_AGE_KEY`.
|
||||
|
||||
**Option 3** (Dagger host as orchestrator) is worth considering once the trigger SSH key replaces all other secrets in Codeberg — it offers the cleanest security boundary at the cost of reduced CI observability.
|
||||
**Option 1** (runner-level env vars) or **Option 2** (secret files) remain
|
||||
valid if you prefer not to commit an encrypted file to the repository.
|
||||
|
||||
**Option 4** (Vault) becomes worthwhile if the project grows to multiple runners or team members who each need audited access to deploy credentials.
|
||||
**Option 3** (Dagger host as orchestrator) is worth considering once the
|
||||
trigger SSH key replaces all other secrets in Codeberg — it offers the cleanest
|
||||
security boundary at the cost of reduced CI observability.
|
||||
|
||||
**Option 4** (Vault) becomes worthwhile if the project grows to multiple
|
||||
runners or team members who each need audited access to deploy credentials.
|
||||
|
||||
+8
-4
@@ -224,7 +224,7 @@ tasks:
|
||||
desc: Build AAB via Dagger (cached, versionCode=1 placeholder) and export locally
|
||||
cmds:
|
||||
- mkdir -p build/app/outputs/bundle/release
|
||||
- HASH=$(git rev-parse --short HEAD) && dagger call --progress=plain -q -m ci --source=. build-android-release --commit-hash "$HASH" -o build/app/outputs/bundle/release/app-release.aab
|
||||
- dagger call --progress=plain -q -m ci --source=. build-android-release -o build/app/outputs/bundle/release/app-release.aab
|
||||
|
||||
upload-android-bundle:
|
||||
desc: Upload AAB from build/ to Play Store via Dagger
|
||||
@@ -238,7 +238,6 @@ tasks:
|
||||
|
||||
publish-android:
|
||||
desc: Build cached AAB, stamp versionCode, sign, and publish to Play Store via Dagger
|
||||
deps: [generate-changelog]
|
||||
preconditions:
|
||||
- sh: test -n "$PLAY_STORE_CONFIG_JSON"
|
||||
msg: "PLAY_STORE_CONFIG_JSON is not set"
|
||||
@@ -247,7 +246,7 @@ tasks:
|
||||
- sh: test -n "$ANDROID_KEYSTORE_PASSWORD"
|
||||
msg: "ANDROID_KEYSTORE_PASSWORD is not set"
|
||||
cmds:
|
||||
- HASH=$(git rev-parse --short HEAD) && dagger call --progress=plain -q -m ci --source=. publish-android --play-store-config env:PLAY_STORE_CONFIG_JSON --keystore-base64 env:ANDROID_KEYSTORE_BASE64 --keystore-password env:ANDROID_KEYSTORE_PASSWORD --commit-hash "$HASH"
|
||||
- dagger call --progress=plain -q -m ci --source=. publish-android --play-store-config env:PLAY_STORE_CONFIG_JSON --keystore-base64 env:ANDROID_KEYSTORE_BASE64 --keystore-password env:ANDROID_KEYSTORE_PASSWORD
|
||||
|
||||
deploy-apk:
|
||||
desc: Build and deploy Android APK via Dagger
|
||||
@@ -656,7 +655,12 @@ tasks:
|
||||
|
||||
check-fast:
|
||||
desc: Pre-commit checks — analyze + unit+widget tests + coverage gate (no build, no integration)
|
||||
deps: [analyze, check-coverage, check-hygiene, check-layers, check-mocks]
|
||||
deps: [analyze, check-coverage, check-hygiene, check-layers, check-mocks, check-secrets]
|
||||
|
||||
check-secrets:
|
||||
desc: Test secrets encrypt/decrypt scripts (requires age)
|
||||
cmds:
|
||||
- bash scripts/test_secrets.sh
|
||||
|
||||
check-layers:
|
||||
desc: Enforce architecture — ui/ must not import data/ (only core/ interfaces allowed)
|
||||
|
||||
@@ -4,6 +4,7 @@ gradle-wrapper.jar
|
||||
/gradlew
|
||||
/gradlew.bat
|
||||
/local.properties
|
||||
GeneratedPluginRegistrant.java
|
||||
.cxx/
|
||||
|
||||
# Remember to never publicly share your keystore.
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
package io.flutter.plugins;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import io.flutter.Log;
|
||||
|
||||
import io.flutter.embedding.engine.FlutterEngine;
|
||||
|
||||
/**
|
||||
* Generated file. Do not edit.
|
||||
* This file is generated by the Flutter tool based on the
|
||||
* plugins that support the Android platform.
|
||||
*/
|
||||
@Keep
|
||||
public final class GeneratedPluginRegistrant {
|
||||
private static final String TAG = "GeneratedPluginRegistrant";
|
||||
public static void registerWith(@NonNull FlutterEngine flutterEngine) {
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new com.mr.flutter.plugin.filepicker.FilePickerPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin file_picker, com.mr.flutter.plugin.filepicker.FilePickerPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin flutter_local_notifications, com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin flutter_plugin_android_lifecycle, io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin flutter_secure_storage, com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new dev.flutter.plugins.integration_test.IntegrationTestPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin integration_test, dev.flutter.plugins.integration_test.IntegrationTestPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new dev.steenbakker.mobile_scanner.MobileScannerPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin mobile_scanner, dev.steenbakker.mobile_scanner.MobileScannerPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new com.crazecoder.openfile.OpenFilePlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin open_filex, com.crazecoder.openfile.OpenFilePlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new dev.fluttercommunity.plus.packageinfo.PackageInfoPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin package_info_plus, dev.fluttercommunity.plus.packageinfo.PackageInfoPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new io.flutter.plugins.pathprovider.PathProviderPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin path_provider_android, io.flutter.plugins.pathprovider.PathProviderPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new dev.fluttercommunity.plus.share.SharePlusPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin share_plus, dev.fluttercommunity.plus.share.SharePlusPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new io.flutter.plugins.urllauncher.UrlLauncherPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin url_launcher_android, io.flutter.plugins.urllauncher.UrlLauncherPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new io.flutter.plugins.webviewflutter.WebViewFlutterPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin webview_flutter_android, io.flutter.plugins.webviewflutter.WebViewFlutterPlugin", e);
|
||||
}
|
||||
try {
|
||||
flutterEngine.getPlugins().add(new dev.fluttercommunity.workmanager.WorkmanagerPlugin());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error registering plugin workmanager_android, dev.fluttercommunity.workmanager.WorkmanagerPlugin", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-40
@@ -183,7 +183,7 @@ func (m *Ci) toolchain() *dagger.Container {
|
||||
return dag.Container().
|
||||
From("ghcr.io/cirruslabs/flutter:3.41.6").
|
||||
WithExec([]string{"apt-get", "-qq", "update"}).
|
||||
WithExec([]string{"apt-get", "install", "-y", "-qq", "clang", "cmake", "ninja-build", "pkg-config", "libgtk-3-dev", "liblzma-dev", "libsecret-1-dev", "libgcrypt20-dev", "libjsoncpp-dev", "sqlite3", "iproute2", "netcat-openbsd", "xvfb", "libosmesa6", "libegl1", "lld"}).
|
||||
WithExec([]string{"apt-get", "install", "-y", "-qq", "clang", "cmake", "ninja-build", "pkg-config", "libgtk-3-dev", "liblzma-dev", "libsecret-1-dev", "libgcrypt20-dev", "libjsoncpp-dev", "sqlite3", "iproute2", "netcat-openbsd", "xvfb", "libosmesa6", "libegl1", "lld", "age"}).
|
||||
WithExec([]string{"useradd", "-m", "-s", "/bin/bash", "ci"}).
|
||||
WithExec([]string{"/bin/sh", "-c",
|
||||
`flutter_dir=$(dirname $(dirname $(which flutter))); ` +
|
||||
@@ -381,6 +381,21 @@ func (m *Ci) CheckHygiene(ctx context.Context) (string, error) {
|
||||
Stdout(ctx)
|
||||
}
|
||||
|
||||
// CheckSecrets verifies the secrets encrypt/decrypt scripts work correctly.
|
||||
func (m *Ci) CheckSecrets(ctx context.Context) (string, error) {
|
||||
scriptSrc := m.Source.Filter(dagger.DirectoryFilterOpts{
|
||||
Include: []string{"scripts/secrets-encrypt.sh", "scripts/secrets-decrypt.sh", "scripts/test_secrets.sh"},
|
||||
})
|
||||
return dag.Container().
|
||||
From("ghcr.io/cirruslabs/flutter:3.41.6").
|
||||
WithExec([]string{"apt-get", "-qq", "update"}).
|
||||
WithExec([]string{"apt-get", "install", "-y", "-qq", "age"}).
|
||||
WithDirectory("/src", scriptSrc).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{"bash", "scripts/test_secrets.sh"}).
|
||||
Stdout(ctx)
|
||||
}
|
||||
|
||||
// CheckLayers enforces that ui/ does not import data/.
|
||||
func (m *Ci) CheckLayers(ctx context.Context) (string, error) {
|
||||
return m.Base().
|
||||
@@ -471,6 +486,9 @@ func (m *Ci) Check(ctx context.Context) (string, error) {
|
||||
if _, err := m.CheckLayers(ctx); err != nil {
|
||||
return "Layer check failed", err
|
||||
}
|
||||
if _, err := m.CheckSecrets(ctx); err != nil {
|
||||
return "Secrets script check failed", err
|
||||
}
|
||||
|
||||
checkSetup := m.setup(m.checkSrc())
|
||||
|
||||
@@ -584,17 +602,9 @@ func (m *Ci) BuildLinux() *dagger.Directory {
|
||||
}
|
||||
|
||||
// BuildLinuxRelease builds the Linux release bundle.
|
||||
func (m *Ci) BuildLinuxRelease(
|
||||
// Git commit hash injected as GIT_HASH dart-define so the About page can display it.
|
||||
// +optional
|
||||
commitHash string,
|
||||
) *dagger.Directory {
|
||||
args := []string{"flutter", "build", "linux", "--release"}
|
||||
if commitHash != "" {
|
||||
args = append(args, "--dart-define=GIT_HASH="+commitHash)
|
||||
}
|
||||
func (m *Ci) BuildLinuxRelease() *dagger.Directory {
|
||||
return m.setup(m.linuxSrc()).
|
||||
WithExec(args).
|
||||
WithExec([]string{"flutter", "build", "linux", "--release"}).
|
||||
Directory("build/linux/x64/release/bundle")
|
||||
}
|
||||
|
||||
@@ -607,7 +617,7 @@ func (m *Ci) DeployLinux(
|
||||
sshHost string,
|
||||
commitHash string,
|
||||
) (string, error) {
|
||||
bundle := m.BuildLinuxRelease(commitHash)
|
||||
bundle := m.BuildLinuxRelease()
|
||||
|
||||
datePath := time.Now().Format("2006/01/02")
|
||||
remoteDir := fmt.Sprintf("public_html/builds/%s", datePath)
|
||||
@@ -630,20 +640,9 @@ func (m *Ci) setupKeystore(keystoreBase64 *dagger.Secret, keystorePassword *dagg
|
||||
}
|
||||
|
||||
// BuildAndroidApk builds a release APK signed with the upload key.
|
||||
func (m *Ci) BuildAndroidApk(
|
||||
keystoreBase64 *dagger.Secret,
|
||||
keystorePassword *dagger.Secret,
|
||||
buildNumber string,
|
||||
// Git commit hash injected as GIT_HASH dart-define so the About page can display it.
|
||||
// +optional
|
||||
commitHash string,
|
||||
) *dagger.File {
|
||||
args := []string{"flutter", "build", "apk", "--release", "--no-pub", "--build-number", buildNumber}
|
||||
if commitHash != "" {
|
||||
args = append(args, "--dart-define=GIT_HASH="+commitHash)
|
||||
}
|
||||
func (m *Ci) BuildAndroidApk(keystoreBase64 *dagger.Secret, keystorePassword *dagger.Secret, buildNumber string) *dagger.File {
|
||||
return m.setupKeystore(keystoreBase64, keystorePassword).
|
||||
WithExec(args).
|
||||
WithExec([]string{"flutter", "build", "apk", "--release", "--no-pub", "--build-number", buildNumber}).
|
||||
File("build/app/outputs/flutter-apk/app-release.apk")
|
||||
}
|
||||
|
||||
@@ -659,7 +658,7 @@ func (m *Ci) DeployApk(
|
||||
keystorePassword *dagger.Secret,
|
||||
buildNumber string,
|
||||
) (string, error) {
|
||||
apk := m.BuildAndroidApk(keystoreBase64, keystorePassword, buildNumber, commitHash)
|
||||
apk := m.BuildAndroidApk(keystoreBase64, keystorePassword, buildNumber)
|
||||
|
||||
datePath := time.Now().Format("2006/01/02")
|
||||
remoteDir := fmt.Sprintf("public_html/builds/%s", datePath)
|
||||
@@ -735,17 +734,9 @@ func (m *Ci) TestAndroidFirebase(
|
||||
|
||||
// BuildAndroidRelease builds the AAB with a fixed build-number so Dagger can cache it.
|
||||
// versionCode and signing are applied separately via StampAndroidVersionCode + SignAndroidBundle.
|
||||
func (m *Ci) BuildAndroidRelease(
|
||||
// Git commit hash injected as GIT_HASH dart-define so the About page can display it.
|
||||
// +optional
|
||||
commitHash string,
|
||||
) *dagger.File {
|
||||
args := []string{"flutter", "build", "appbundle", "--release", "--no-pub", "--build-number", "1"}
|
||||
if commitHash != "" {
|
||||
args = append(args, "--dart-define=GIT_HASH="+commitHash)
|
||||
}
|
||||
func (m *Ci) BuildAndroidRelease() *dagger.File {
|
||||
return m.setup(m.androidSrc()).
|
||||
WithExec(args).
|
||||
WithExec([]string{"flutter", "build", "appbundle", "--release", "--no-pub", "--build-number", "1"}).
|
||||
File("build/app/outputs/bundle/release/app-release.aab")
|
||||
}
|
||||
|
||||
@@ -817,12 +808,9 @@ func (m *Ci) PublishAndroid(
|
||||
playStoreConfig *dagger.Secret,
|
||||
keystoreBase64 *dagger.Secret,
|
||||
keystorePassword *dagger.Secret,
|
||||
// Git commit hash injected as GIT_HASH dart-define so the About page can display it.
|
||||
// +optional
|
||||
commitHash string,
|
||||
) (string, error) {
|
||||
versionCode := int(time.Now().Unix())
|
||||
aab := m.BuildAndroidRelease(commitHash)
|
||||
aab := m.BuildAndroidRelease()
|
||||
stamped := m.StampAndroidVersionCode(aab, versionCode)
|
||||
signed := m.SignAndroidBundle(stamped, keystoreBase64, keystorePassword)
|
||||
return m.UploadToPlayStore(ctx, signed, playStoreConfig)
|
||||
@@ -851,6 +839,7 @@ flowchart TD
|
||||
|
||||
pubGet --> hygiene["CheckHygiene"]
|
||||
pubGet --> layers["CheckLayers"]
|
||||
pubGet --> secrets["CheckSecrets\nage encrypt/decrypt"]
|
||||
pubGet --> mocks["CheckMocks\n(own build_runner run)"]
|
||||
|
||||
codegen --> fmt["Format"]
|
||||
@@ -864,6 +853,7 @@ flowchart TD
|
||||
|
||||
hygiene --> check{{"✓ Check"}}
|
||||
layers --> check
|
||||
secrets --> check
|
||||
fmt --> check
|
||||
analyze --> check
|
||||
mocks --> check
|
||||
|
||||
@@ -13,7 +13,7 @@ export SSH_PRIVATE_KEY=$(cat "$HOME/.ssh/id_ed25519")
|
||||
|
||||
# Add nix profile and nix store tools (task, dagger) to PATH
|
||||
export PATH="$HOME/.nix-profile/bin:$PATH"
|
||||
for pkg in "*go-task-*/bin/task" "*dagger-*/bin/dagger" "*fgj-*/bin/fgj"; do
|
||||
for pkg in "*go-task-*/bin/task" "*dagger-*/bin/dagger"; do
|
||||
bin=$(ls -d /nix/store/$pkg 2>/dev/null | sort -V | tail -1)
|
||||
[ -n "$bin" ] && export PATH="$(dirname "$bin"):$PATH"
|
||||
done
|
||||
|
||||
@@ -87,6 +87,9 @@
|
||||
# Website
|
||||
hugo
|
||||
|
||||
# Secrets management (master-key encryption for CI sync)
|
||||
age
|
||||
|
||||
# Utilities
|
||||
git
|
||||
curl
|
||||
|
||||
@@ -95,30 +95,6 @@ class _AboutScreenState extends ConsumerState<AboutScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _launchUrl(BuildContext context, Uri url) async {
|
||||
try {
|
||||
final launched =
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
if (!launched && context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
duration: Duration(seconds: 5),
|
||||
content: Text('Could not open browser.'),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
duration: const Duration(seconds: 5),
|
||||
content: Text('Error: $e'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _createIssue(
|
||||
BuildContext context,
|
||||
int imapCount,
|
||||
@@ -191,7 +167,10 @@ class _AboutScreenState extends ConsumerState<AboutScreen> {
|
||||
onTapLink: (text, href, title) {
|
||||
if (href != null) {
|
||||
unawaited(
|
||||
_launchUrl(context, Uri.parse(href)),
|
||||
launchUrl(
|
||||
Uri.parse(href),
|
||||
mode: LaunchMode.externalApplication,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart' show rootBundle;
|
||||
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
@@ -12,8 +13,7 @@ class ChangeLogScreen extends StatelessWidget {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('ChangeLog')),
|
||||
body: FutureBuilder<String>(
|
||||
future:
|
||||
DefaultAssetBundle.of(context).loadString('assets/changelog.txt'),
|
||||
future: rootBundle.loadString('assets/changelog.txt'),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
|
||||
@@ -37,14 +37,11 @@ class CrashScreen extends StatelessWidget {
|
||||
final version = await _fetchVersion();
|
||||
final platform =
|
||||
'${Platform.operatingSystem} ${Platform.operatingSystemVersion}';
|
||||
final versionDisplay = gitHash.isNotEmpty
|
||||
? '[$version](https://codeberg.org/guettli/sharedinbox/commit/$gitHash)'
|
||||
: version;
|
||||
final gitLine = gitHash.isNotEmpty
|
||||
? 'Git Commit: [$gitHash](https://codeberg.org/guettli/sharedinbox/commit/$gitHash)\n'
|
||||
: '';
|
||||
final timestamp = DateTime.now().toUtc().toIso8601String();
|
||||
return 'App Version: $versionDisplay\n'
|
||||
return 'App Version: $version\n'
|
||||
'Build Mode: $_buildMode\n'
|
||||
'$gitLine'
|
||||
'Platform: $platform\n'
|
||||
@@ -89,35 +86,6 @@ class CrashScreen extends StatelessWidget {
|
||||
),
|
||||
if (gitHash.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
FutureBuilder<PackageInfo>(
|
||||
future: PackageInfo.fromPlatform(),
|
||||
builder: (_, snapshot) {
|
||||
if (!snapshot.hasData) return const SizedBox.shrink();
|
||||
final version =
|
||||
'${snapshot.data!.version}+${snapshot.data!.buildNumber}';
|
||||
return GestureDetector(
|
||||
onTap: () async {
|
||||
final url = Uri.parse(
|
||||
'https://codeberg.org/guettli/sharedinbox/commit/$gitHash',
|
||||
);
|
||||
await launchUrl(
|
||||
url,
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
},
|
||||
child: Text(
|
||||
'App Version: $version',
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.blue,
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
GestureDetector(
|
||||
onTap: () async {
|
||||
final url = Uri.parse(
|
||||
|
||||
@@ -38,7 +38,6 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
|
||||
var _sieveSsl = true;
|
||||
var _verbose = false;
|
||||
final _jmapUrlCtrl = TextEditingController();
|
||||
bool _hasStoredPassword = false;
|
||||
|
||||
// -- "Try connection" state ------------------------------------------------
|
||||
bool _tryTesting = false;
|
||||
@@ -51,7 +50,6 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
|
||||
_smtpHostCtrl.addListener(_rebuild);
|
||||
_sieveHostCtrl.addListener(_rebuild);
|
||||
_imapHostCtrl.addListener(_rebuild);
|
||||
_passwordCtrl.addListener(_rebuild);
|
||||
unawaited(_load());
|
||||
}
|
||||
|
||||
@@ -65,11 +63,6 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
|
||||
context.pop();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await repo.getPassword(account.id);
|
||||
_hasStoredPassword = true;
|
||||
} catch (_) {}
|
||||
if (!mounted) return;
|
||||
_account = account;
|
||||
_displayNameCtrl.text = account.displayName;
|
||||
_usernameCtrl.text = account.username;
|
||||
@@ -91,7 +84,6 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
|
||||
_smtpHostCtrl.removeListener(_rebuild);
|
||||
_sieveHostCtrl.removeListener(_rebuild);
|
||||
_imapHostCtrl.removeListener(_rebuild);
|
||||
_passwordCtrl.removeListener(_rebuild);
|
||||
for (final c in [
|
||||
_displayNameCtrl,
|
||||
_usernameCtrl,
|
||||
@@ -275,12 +267,10 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
|
||||
),
|
||||
_field(
|
||||
_passwordCtrl,
|
||||
_hasStoredPassword
|
||||
? 'New password (leave blank to keep)'
|
||||
: 'Password',
|
||||
'New password (leave blank to keep)',
|
||||
key: const Key('editPasswordField'),
|
||||
obscure: true,
|
||||
required: !_hasStoredPassword,
|
||||
required: false,
|
||||
),
|
||||
if (account.type == AccountType.jmap) ...[
|
||||
const Divider(height: 32),
|
||||
@@ -355,17 +345,10 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
|
||||
testing: _tryTesting,
|
||||
okMessage: _tryOk,
|
||||
errorMessage: _tryErr,
|
||||
onPressed: _hasStoredPassword || _passwordCtrl.text.isNotEmpty
|
||||
? _tryConnection
|
||||
: null,
|
||||
onPressed: _tryConnection,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
FilledButton(
|
||||
onPressed: _hasStoredPassword || _passwordCtrl.text.isNotEmpty
|
||||
? _save
|
||||
: null,
|
||||
child: const Text('Save'),
|
||||
),
|
||||
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
+3
-3
@@ -1117,13 +1117,13 @@ packages:
|
||||
source: hosted
|
||||
version: "6.3.2"
|
||||
url_launcher_android:
|
||||
dependency: "direct overridden"
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_android
|
||||
sha256: "5c8b6c2d89a78f5a1cca70a73d9d5f86c701b36b42f9c9dac7bad592113c28e9"
|
||||
sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.3.24"
|
||||
version: "6.3.30"
|
||||
url_launcher_ios:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -89,7 +89,3 @@ dependency_overrides:
|
||||
# (SIGSEGV in libdartjni.so FindClassUnchecked). Pin to 2.2.20 which uses
|
||||
# stable Pigeon and is known to work reliably.
|
||||
path_provider_android: ">=2.2.0 <2.2.21"
|
||||
# url_launcher_android 6.3.25 updated to Pigeon 26, which causes a
|
||||
# channel-error on launchUrl on some Android devices (same root cause as
|
||||
# path_provider_android). Pin to <6.3.25 which uses stable Pigeon.
|
||||
url_launcher_android: ">=6.3.0 <6.3.25"
|
||||
|
||||
+11
-141
@@ -8,25 +8,21 @@ Flow
|
||||
a. Age > 1 h → kill it, set its issue to State/Question, exit 1
|
||||
b. Age ≤ 1 h → print status, exit 0 (let it keep working)
|
||||
2. No agent running → extract pending_issue from state (if any), then check CI
|
||||
a. pending_issue type=="plan" → post resume comment, set State/Planned, exit 0
|
||||
b. pending_issue + open PR → check PR branch CI, merge/fix/wait as needed
|
||||
c. Catch-up: orphaned issue-N-fix PRs with passing CI → merge them
|
||||
d. Main CI running → save pending-ci state, exit 0
|
||||
e. Main CI failed → start fix-CI agent (pushes fix to main), exit 0
|
||||
f. Main CI ok + pending_issue → close the issue, exit 0 (dead code path —
|
||||
section 2b always returns first)
|
||||
g. Main CI ok (or no run yet) → find oldest ToPlan issue, start plan agent,
|
||||
a. pending_issue + open PR → check PR branch CI, merge/fix/wait as needed
|
||||
b. Catch-up: orphaned issue-N-fix PRs with passing CI → merge them
|
||||
c. Main CI running → save pending-ci state, exit 0
|
||||
d. Main CI failed → start fix-CI agent (pushes fix to main), exit 0
|
||||
e. Main CI ok + pending_issue → close the issue, exit 0 (dead code path —
|
||||
section 2a always returns first)
|
||||
f. Main CI ok (or no run yet) → find oldest Ready issue, start issue agent,
|
||||
save state, exit 0
|
||||
h. No ToPlan issues → find oldest Ready issue, start issue agent,
|
||||
save state, exit 0
|
||||
i. No Ready issues → print "nothing to do", exit 0
|
||||
g. No Ready issues → print "nothing to do", exit 0
|
||||
|
||||
Issue agents must NOT close the issue themselves; the loop closes it after CI passes.
|
||||
Plan agents must NOT write any code or create PRs; they only post a plan comment.
|
||||
|
||||
State file: ~/.sharedinbox-agent-state.json
|
||||
{ "pid": 12345, "issue": 91,
|
||||
"started_at": "2026-05-15T12:00:00+00:00", "type": "issue|plan|ci-fix|pending-ci" }
|
||||
"started_at": "2026-05-15T12:00:00+00:00", "type": "issue" }
|
||||
|
||||
Output is written to ~/.sharedinbox-agent-logs/<session>-<timestamp>.log.
|
||||
To resume the Claude conversation, look up the session UUID first:
|
||||
@@ -57,9 +53,7 @@ os.environ["PATH"] = (
|
||||
REPO = "guettli/sharedinbox"
|
||||
REPO_URL = f"https://codeberg.org/{REPO}"
|
||||
STATE_FILE = Path.home() / ".sharedinbox-agent-state.json"
|
||||
HEARTBEAT_FILE = Path.home() / ".sharedinbox-agent-heartbeat"
|
||||
MAX_AGENT_AGE_SECONDS = 3600 # 1 hour
|
||||
MAX_HEARTBEAT_AGE_SECONDS = 7200 # 2 hours
|
||||
CLAUDE_PROJECTS_DIR = Path.home() / ".claude" / "projects" / (
|
||||
"-" + str(Path.home())[1:].replace("/", "-")
|
||||
)
|
||||
@@ -69,8 +63,6 @@ LABEL_READY = "State/Ready"
|
||||
LABEL_IN_PROGRESS = "State/InProgress"
|
||||
LABEL_QUESTION = "State/Question"
|
||||
LABEL_PRIO_HIGH = "Prio/High"
|
||||
LABEL_TO_PLAN = "State/ToPlan"
|
||||
LABEL_PLANNED = "State/Planned"
|
||||
|
||||
# Only pick up issues filed by these accounts.
|
||||
ALLOWED_ISSUE_AUTHORS = {"guettli", "guettlibot", "guettlibot2"}
|
||||
@@ -153,26 +145,6 @@ def _ready_issues() -> list[dict]:
|
||||
return ready
|
||||
|
||||
|
||||
def _to_plan_issues() -> list[dict]:
|
||||
"""Return open issues with State/ToPlan, Prio/High first, then oldest."""
|
||||
result = subprocess.run(
|
||||
["fgj", "--hostname", "codeberg.org", "issue", "list",
|
||||
"--repo", REPO, "--state", "open", "--json"],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
data = json.loads(result.stdout) if result.stdout.strip() else []
|
||||
to_plan = [
|
||||
i for i in data
|
||||
if any(lbl["name"] == LABEL_TO_PLAN for lbl in i.get("labels", []))
|
||||
and i.get("user", {}).get("login", "") in ALLOWED_ISSUE_AUTHORS
|
||||
]
|
||||
to_plan.sort(key=lambda i: (
|
||||
0 if any(lbl["name"] == LABEL_PRIO_HIGH for lbl in i.get("labels", [])) else 1,
|
||||
i["number"],
|
||||
))
|
||||
return to_plan
|
||||
|
||||
|
||||
def _latest_main_ci_run() -> dict | None:
|
||||
"""Return the latest ci.yml run on the main branch.
|
||||
|
||||
@@ -265,14 +237,6 @@ def _latest_ci_run_for_pr(pr_number: int) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
def _get_issue_labels(issue: int) -> list[str]:
|
||||
"""Return label names for an issue."""
|
||||
data = _tea_get(f"repos/{REPO}/issues/{issue}")
|
||||
if not data:
|
||||
return []
|
||||
return [lbl["name"] for lbl in data.get("labels", [])]
|
||||
|
||||
|
||||
def _merge_pr(pr_number: int) -> None:
|
||||
"""Squash-merge a PR via fgj."""
|
||||
_fgj("pr", "merge", str(pr_number), "--repo", REPO, "--merge-method", "squash")
|
||||
@@ -311,12 +275,6 @@ def _clear_state() -> None:
|
||||
STATE_FILE.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _update_heartbeat() -> None:
|
||||
"""Record that the agent loop ran right now."""
|
||||
HEARTBEAT_FILE.write_text(datetime.now(timezone.utc).isoformat())
|
||||
HEARTBEAT_FILE.chmod(0o600)
|
||||
|
||||
|
||||
def _find_session_uuid(session_name: str) -> str | None:
|
||||
"""Return the Claude session UUID for *session_name*, or None if not found.
|
||||
|
||||
@@ -486,44 +444,12 @@ def cmd_list() -> int:
|
||||
return 0
|
||||
|
||||
|
||||
# ── monitor subcommand ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def cmd_monitor() -> int:
|
||||
"""Check that the agent loop has run within the last 2 hours.
|
||||
|
||||
Exits 0 if healthy, 1 if the heartbeat is missing or stale.
|
||||
Intended to be called from a scheduled CI job or cron every 2 hours.
|
||||
"""
|
||||
if not HEARTBEAT_FILE.exists():
|
||||
print(
|
||||
f"WARNING: Agent loop heartbeat file missing — "
|
||||
f"the loop may not have run yet or the file was deleted ({HEARTBEAT_FILE})."
|
||||
)
|
||||
return 1
|
||||
try:
|
||||
last_run = datetime.fromisoformat(HEARTBEAT_FILE.read_text().strip())
|
||||
except ValueError:
|
||||
print(f"WARNING: Agent loop heartbeat file is corrupted: {HEARTBEAT_FILE}")
|
||||
return 1
|
||||
age = (datetime.now(timezone.utc) - last_run).total_seconds()
|
||||
if age > MAX_HEARTBEAT_AGE_SECONDS:
|
||||
print(
|
||||
f"WARNING: Agent loop last ran {age / 3600:.1f}h ago "
|
||||
f"(limit: {MAX_HEARTBEAT_AGE_SECONDS // 3600}h) — the loop may be stalled."
|
||||
)
|
||||
return 1
|
||||
print(f"Agent loop is healthy. Last run: {age / 60:.0f} min ago.")
|
||||
return 0
|
||||
|
||||
|
||||
# ── main flow ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _run_loop() -> int:
|
||||
now = datetime.now(timezone.utc)
|
||||
print(f"---------------------- Starting {now.strftime('%Y-%m-%d %H:%MZ')}")
|
||||
_update_heartbeat()
|
||||
|
||||
state = _read_state()
|
||||
|
||||
@@ -578,29 +504,13 @@ def _run_loop() -> int:
|
||||
|
||||
# Agent not running (or no state) — extract any pending issue, then clean up.
|
||||
pending_issue: int | None = None
|
||||
pending_type: str | None = None
|
||||
ci_run_id_at_start: int | None = None
|
||||
if state:
|
||||
pending_issue = state.get("issue")
|
||||
pending_type = state.get("type")
|
||||
ci_run_id_at_start = state.get("ci_run_id_at_start")
|
||||
_clear_state()
|
||||
|
||||
# ── 2a. Finished planning agent ───────────────────────────────────────────
|
||||
if pending_issue and pending_type == "plan":
|
||||
session_name = f"plan-issue-{pending_issue}"
|
||||
uuid = _find_session_uuid(session_name)
|
||||
if uuid:
|
||||
resume_cmd = f"claude --resume {shlex.quote(uuid)}"
|
||||
_comment_issue(
|
||||
pending_issue,
|
||||
f"Planning complete. To resume this session:\n\n```\n{resume_cmd}\n```",
|
||||
)
|
||||
_set_labels(pending_issue, add=[LABEL_PLANNED], remove=[LABEL_IN_PROGRESS])
|
||||
print(f"Planning done for {_issue_url(pending_issue)} — set State/Planned.")
|
||||
return 0
|
||||
|
||||
# ── 2b. Check for a PR opened by the agent ───────────────────────────────
|
||||
# ── 2. Check for a PR opened by the agent ────────────────────────────────
|
||||
if pending_issue:
|
||||
branch = f"issue-{pending_issue}-fix"
|
||||
pr = _find_pr_for_branch(branch)
|
||||
@@ -732,9 +642,6 @@ def _run_loop() -> int:
|
||||
continue
|
||||
|
||||
if pr_run and pr_run.get("status") == "success":
|
||||
if issue_num and LABEL_QUESTION in _get_issue_labels(issue_num):
|
||||
print(f"Catch-up: PR #{pr_number} — issue #{issue_num} is State/Question, skipping.")
|
||||
continue
|
||||
print(f"Catch-up: CI passed on PR #{pr_number} ({pr_url}) — merging.")
|
||||
try:
|
||||
_merge_pr(pr_number)
|
||||
@@ -831,44 +738,10 @@ def _run_loop() -> int:
|
||||
print(f"CI passed{ci_run_part} — closed {_issue_url(pending_issue)}.")
|
||||
return 0
|
||||
|
||||
# Find a ToPlan issue — planning takes priority over implementation.
|
||||
to_plan = _to_plan_issues()
|
||||
if to_plan:
|
||||
issue = to_plan[0]
|
||||
issue_number = issue["number"]
|
||||
issue_title = issue["title"]
|
||||
issue_body = issue.get("body", "")
|
||||
|
||||
print(f"Starting planning agent for {_issue_url(issue_number)} {issue_title}")
|
||||
_set_labels(issue_number, add=[LABEL_IN_PROGRESS], remove=[LABEL_TO_PLAN])
|
||||
|
||||
plan_prompt = f"""Analyze Codeberg issue #{issue_number} in the guettli/sharedinbox repository and write a detailed implementation plan.
|
||||
|
||||
Issue title: {issue_title}
|
||||
|
||||
Issue body:
|
||||
{issue_body}
|
||||
|
||||
Instructions:
|
||||
- Read and understand the issue thoroughly.
|
||||
- Explore the relevant parts of the codebase to understand the current structure.
|
||||
- Write a detailed implementation plan as a comment on the issue using:
|
||||
fgj issue comment {issue_number} --repo {REPO} --body "..."
|
||||
The plan should cover: which files to change, what approach to take, and any risks or open questions.
|
||||
- Do NOT write any code, do NOT create any branches or PRs, do NOT modify any files.
|
||||
- If the issue is unclear or you need more information, set the label to State/Question
|
||||
and stop (do NOT close the issue).
|
||||
- When you have posted the plan as an issue comment, stop.
|
||||
"""
|
||||
session_name = f"plan-issue-{issue_number}"
|
||||
pid = _start_agent(plan_prompt, session_name)
|
||||
_write_state(pid, issue_number, "plan", issue_title, session_name=session_name)
|
||||
return 0
|
||||
|
||||
# Find a Ready issue.
|
||||
issues = _ready_issues()
|
||||
if not issues:
|
||||
print("No issues with State/ToPlan or State/Ready. Nothing to do.")
|
||||
print("No issues with State/Ready. Nothing to do.")
|
||||
return 0
|
||||
|
||||
issue = issues[0]
|
||||
@@ -924,13 +797,10 @@ def main() -> int:
|
||||
parser = argparse.ArgumentParser(prog="agent_loop")
|
||||
sub = parser.add_subparsers(dest="cmd")
|
||||
sub.add_parser("list", help="List recent agent sessions")
|
||||
sub.add_parser("monitor", help="Check that the loop ran within the last 2 hours")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.cmd == "list":
|
||||
return cmd_list()
|
||||
if args.cmd == "monitor":
|
||||
return cmd_monitor()
|
||||
return _run_loop()
|
||||
|
||||
|
||||
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
# Decrypts secrets.age and exports all KEY=VALUE pairs as environment variables.
|
||||
#
|
||||
# In CI (GITHUB_ENV set): writes to $GITHUB_ENV so subsequent job steps can
|
||||
# read the variables. Multi-line values use the heredoc syntax required by
|
||||
# Forgejo/GitHub Actions.
|
||||
#
|
||||
# Locally: prints an eval-safe export block to stdout. Source it with:
|
||||
# eval "$(SECRETS_AGE_KEY=$(cat ~/.config/age/sharedinbox.key) scripts/secrets-decrypt.sh)"
|
||||
# or pass a key file:
|
||||
# eval "$(scripts/secrets-decrypt.sh ~/.config/age/sharedinbox.key)"
|
||||
#
|
||||
# Private key sources (first match wins):
|
||||
# 1. Path to a key file passed as $1
|
||||
# 2. SECRETS_AGE_KEY env var (the raw private key content — used in CI)
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) \
|
||||
|| REPO_ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
SECRETS_AGE="${SECRETS_AGE:-${REPO_ROOT}/secrets.age}"
|
||||
|
||||
if [ ! -f "$SECRETS_AGE" ]; then
|
||||
echo "ERROR: secrets.age not found at $SECRETS_AGE" >&2
|
||||
echo " Run: scripts/secrets-encrypt.sh to create it." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TMP_KEY=""
|
||||
cleanup() { [ -n "$TMP_KEY" ] && rm -f "$TMP_KEY"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
if [ -n "${1:-}" ]; then
|
||||
KEY_FILE="$1"
|
||||
elif [ -n "${SECRETS_AGE_KEY:-}" ]; then
|
||||
TMP_KEY=$(mktemp)
|
||||
chmod 600 "$TMP_KEY"
|
||||
printf '%s\n' "$SECRETS_AGE_KEY" > "$TMP_KEY"
|
||||
KEY_FILE="$TMP_KEY"
|
||||
else
|
||||
echo "ERROR: No age private key provided." >&2
|
||||
echo " Pass a key file: scripts/secrets-decrypt.sh ~/.config/age/sharedinbox.key" >&2
|
||||
echo " Or set SECRETS_AGE_KEY env var (CI: store as SECRETS_AGE_KEY secret)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
DECRYPTED=$(age --decrypt -i "$KEY_FILE" "$SECRETS_AGE")
|
||||
|
||||
# Process each KEY=VALUE line.
|
||||
# Double-quoted values have \n escape sequences converted to real newlines.
|
||||
process_secrets() {
|
||||
local line key raw_value value
|
||||
while IFS= read -r line; do
|
||||
[[ -z "$line" || "$line" == \#* ]] && continue
|
||||
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
|
||||
|
||||
key="${line%%=*}"
|
||||
raw_value="${line#*=}"
|
||||
|
||||
# Double-quoted: strip quotes and expand \n → newline
|
||||
if [[ "$raw_value" == '"'*'"' ]]; then
|
||||
raw_value="${raw_value:1:${#raw_value}-2}"
|
||||
value=$(printf '%b' "$raw_value")
|
||||
# Single-quoted: strip quotes, no expansion
|
||||
elif [[ "$raw_value" == "'"*"'" ]]; then
|
||||
value="${raw_value:1:${#raw_value}-2}"
|
||||
else
|
||||
value="$raw_value"
|
||||
fi
|
||||
|
||||
if [ -n "${GITHUB_ENV:-}" ]; then
|
||||
# Heredoc syntax handles multi-line values safely
|
||||
local delim="EOF_${key}_$$"
|
||||
printf '%s<<%s\n%s\n%s\n' "$key" "$delim" "$value" "$delim" >> "$GITHUB_ENV"
|
||||
else
|
||||
# Print as export statements for eval
|
||||
printf "export %s=%q\n" "$key" "$value"
|
||||
fi
|
||||
done <<< "$DECRYPTED"
|
||||
}
|
||||
|
||||
process_secrets
|
||||
|
||||
if [ -n "${GITHUB_ENV:-}" ]; then
|
||||
echo "Secrets written to \$GITHUB_ENV." >&2
|
||||
fi
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Encrypts secrets.env → secrets.age using an age public key.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/secrets-encrypt.sh [AGE1...] public key as positional argument
|
||||
# AGE_PUBLIC_KEY=AGE1... scripts/secrets-encrypt.sh
|
||||
# scripts/secrets-encrypt.sh reads public key from .age-public-key
|
||||
#
|
||||
# The private key never touches this script. Only the public key is needed to
|
||||
# encrypt. Store the private key in CI as SECRETS_AGE_KEY and keep a local
|
||||
# copy at ~/.config/age/sharedinbox.key (or wherever you prefer).
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) \
|
||||
|| REPO_ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
SECRETS_ENV="${SECRETS_ENV:-${REPO_ROOT}/secrets.env}"
|
||||
SECRETS_AGE="${SECRETS_AGE:-${REPO_ROOT}/secrets.age}"
|
||||
KEY_FILE="${REPO_ROOT}/.age-public-key"
|
||||
|
||||
if [ -n "${1:-}" ]; then
|
||||
PUBLIC_KEY="$1"
|
||||
elif [ -n "${AGE_PUBLIC_KEY:-}" ]; then
|
||||
PUBLIC_KEY="$AGE_PUBLIC_KEY"
|
||||
elif [ -f "$KEY_FILE" ]; then
|
||||
PUBLIC_KEY=$(cat "$KEY_FILE")
|
||||
PUBLIC_KEY="${PUBLIC_KEY%%$'\n'*}" # take only the first line
|
||||
else
|
||||
echo "ERROR: No age public key provided." >&2
|
||||
echo " Pass it as an argument: scripts/secrets-encrypt.sh AGE1..." >&2
|
||||
echo " Or store it in .age-public-key: age-keygen -y ~/.config/age/sharedinbox.key > .age-public-key" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$SECRETS_ENV" ]; then
|
||||
echo "ERROR: secrets.env not found at $SECRETS_ENV" >&2
|
||||
echo " Copy secrets.env.example to secrets.env and fill in values." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
age --encrypt --recipient "$PUBLIC_KEY" --output "$SECRETS_AGE" "$SECRETS_ENV"
|
||||
echo "Encrypted $SECRETS_ENV → $SECRETS_AGE"
|
||||
echo "Commit secrets.age to keep CI in sync."
|
||||
@@ -6,7 +6,6 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -745,110 +744,5 @@ class TestRunLoopResumeCommand(unittest.TestCase):
|
||||
self.assertNotIn("Resume:", output)
|
||||
|
||||
|
||||
|
||||
class TestCatchupSkipsQuestionIssues(unittest.TestCase):
|
||||
"""Catch-up must not retry merging a PR whose issue is already State/Question."""
|
||||
|
||||
def _make_pr(self, pr_number=50, branch="issue-10-fix"):
|
||||
return {"number": pr_number, "head": {"ref": branch}}
|
||||
|
||||
def test_skips_merge_when_issue_has_question_label(self):
|
||||
pr = self._make_pr()
|
||||
ci_run = {"id": 999, "status": "success"}
|
||||
with patch("agent_loop._read_state", return_value=None), \
|
||||
patch("agent_loop._open_issue_prs", return_value=[pr]), \
|
||||
patch("agent_loop._latest_ci_run_for_pr", return_value=ci_run), \
|
||||
patch("agent_loop._get_issue_labels", return_value=[agent_loop.LABEL_QUESTION]), \
|
||||
patch("agent_loop._merge_pr") as mock_merge, \
|
||||
patch("agent_loop._comment_issue") as mock_comment, \
|
||||
patch("agent_loop._set_labels") as mock_labels, \
|
||||
patch("agent_loop._latest_main_ci_run", return_value=None), \
|
||||
patch("agent_loop._ready_issues", return_value=[]):
|
||||
result = agent_loop._run_loop()
|
||||
self.assertEqual(result, 0)
|
||||
mock_merge.assert_not_called()
|
||||
mock_comment.assert_not_called()
|
||||
mock_labels.assert_not_called()
|
||||
|
||||
def test_proceeds_with_merge_when_issue_lacks_question_label(self):
|
||||
pr = self._make_pr()
|
||||
ci_run = {"id": 999, "status": "success"}
|
||||
with patch("agent_loop._read_state", return_value=None), \
|
||||
patch("agent_loop._open_issue_prs", return_value=[pr]), \
|
||||
patch("agent_loop._latest_ci_run_for_pr", return_value=ci_run), \
|
||||
patch("agent_loop._get_issue_labels", return_value=[agent_loop.LABEL_IN_PROGRESS]), \
|
||||
patch("agent_loop._merge_pr") as mock_merge, \
|
||||
patch("agent_loop._find_pr_for_branch", return_value=None), \
|
||||
patch("agent_loop._close_issue"):
|
||||
result = agent_loop._run_loop()
|
||||
self.assertEqual(result, 0)
|
||||
mock_merge.assert_called_once_with(50)
|
||||
|
||||
|
||||
class TestHeartbeat(unittest.TestCase):
|
||||
"""Tests for _update_heartbeat() and cmd_monitor()."""
|
||||
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".heartbeat")
|
||||
self._tmp.close()
|
||||
self._orig = agent_loop.HEARTBEAT_FILE
|
||||
agent_loop.HEARTBEAT_FILE = Path(self._tmp.name)
|
||||
Path(self._tmp.name).unlink() # Start with no heartbeat file.
|
||||
|
||||
def tearDown(self):
|
||||
agent_loop.HEARTBEAT_FILE = self._orig
|
||||
Path(self._tmp.name).unlink(missing_ok=True)
|
||||
|
||||
def test_update_heartbeat_writes_timestamp(self):
|
||||
agent_loop._update_heartbeat()
|
||||
content = Path(self._tmp.name).read_text().strip()
|
||||
dt = datetime.fromisoformat(content)
|
||||
age = (datetime.now(timezone.utc) - dt).total_seconds()
|
||||
self.assertLess(age, 5)
|
||||
|
||||
def test_update_heartbeat_creates_file(self):
|
||||
self.assertFalse(Path(self._tmp.name).exists())
|
||||
agent_loop._update_heartbeat()
|
||||
self.assertTrue(Path(self._tmp.name).exists())
|
||||
|
||||
def test_monitor_healthy_when_recent(self):
|
||||
agent_loop._update_heartbeat()
|
||||
result = agent_loop.cmd_monitor()
|
||||
self.assertEqual(result, 0)
|
||||
|
||||
def test_monitor_warns_when_heartbeat_missing(self):
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
result = agent_loop.cmd_monitor()
|
||||
self.assertEqual(result, 1)
|
||||
self.assertIn("WARNING", buf.getvalue())
|
||||
|
||||
def test_monitor_warns_when_stale(self):
|
||||
stale = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
|
||||
Path(self._tmp.name).write_text(stale)
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
result = agent_loop.cmd_monitor()
|
||||
self.assertEqual(result, 1)
|
||||
self.assertIn("WARNING", buf.getvalue())
|
||||
|
||||
def test_monitor_warns_when_corrupted(self):
|
||||
Path(self._tmp.name).write_text("not-a-timestamp")
|
||||
buf = io.StringIO()
|
||||
with contextlib.redirect_stdout(buf):
|
||||
result = agent_loop.cmd_monitor()
|
||||
self.assertEqual(result, 1)
|
||||
self.assertIn("WARNING", buf.getvalue())
|
||||
|
||||
def test_run_loop_updates_heartbeat(self):
|
||||
self.assertFalse(Path(self._tmp.name).exists())
|
||||
with patch("agent_loop._read_state", return_value=None), \
|
||||
patch("agent_loop._open_issue_prs", return_value=[]), \
|
||||
patch("agent_loop._latest_main_ci_run", return_value=None), \
|
||||
patch("agent_loop._ready_issues", return_value=[]):
|
||||
agent_loop._run_loop()
|
||||
self.assertTrue(Path(self._tmp.name).exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Executable
+153
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests for scripts/secrets-encrypt.sh and scripts/secrets-decrypt.sh.
|
||||
# Run directly: bash scripts/test_secrets.sh
|
||||
# Requires: age, age-keygen
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
_assert() {
|
||||
local name="$1" expected="$2" actual="$3"
|
||||
if [ "$actual" = "$expected" ]; then
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo "FAIL: $name"
|
||||
echo " expected: $(printf '%s' "$expected" | head -c 80)"
|
||||
echo " actual: $(printf '%s' "$actual" | head -c 80)"
|
||||
FAIL=$((FAIL + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
_assert_contains() {
|
||||
local name="$1" needle="$2" haystack="$3"
|
||||
if printf '%s' "$haystack" | grep -qF -- "$needle"; then
|
||||
PASS=$((PASS + 1))
|
||||
else
|
||||
echo "FAIL: $name"
|
||||
echo " expected to contain: $needle"
|
||||
echo " actual: $(printf '%s' "$haystack" | head -c 200)"
|
||||
FAIL=$((FAIL + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
if ! command -v age >/dev/null 2>&1 || ! command -v age-keygen >/dev/null 2>&1; then
|
||||
echo "SKIP: age/age-keygen not found — install age to run secrets tests"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
WORKDIR=$(mktemp -d)
|
||||
cleanup() { rm -rf "$WORKDIR"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
KEY_FILE="$WORKDIR/test.key"
|
||||
SECRETS_ENV="$WORKDIR/secrets.env"
|
||||
SECRETS_AGE="$WORKDIR/secrets.age"
|
||||
GITHUB_ENV_FILE="$WORKDIR/github.env"
|
||||
|
||||
# Generate a test age key pair
|
||||
age-keygen -o "$KEY_FILE" 2>/dev/null
|
||||
PUBLIC_KEY=$(age-keygen -y "$KEY_FILE")
|
||||
|
||||
PRIVATE_KEY=$(cat "$KEY_FILE")
|
||||
|
||||
# Helper: decrypt and eval, capturing specific variables
|
||||
_decrypt_vars() {
|
||||
local vars
|
||||
vars=$(SECRETS_AGE_KEY="$PRIVATE_KEY" \
|
||||
SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-decrypt.sh")
|
||||
eval "$vars"
|
||||
}
|
||||
|
||||
# --- simple values ---
|
||||
cat > "$SECRETS_ENV" << 'EOF'
|
||||
SIMPLE_VAR=hello
|
||||
QUOTED_DOUBLE="world"
|
||||
QUOTED_SINGLE='literal'
|
||||
EMPTY_VAR=
|
||||
# comment line — should be ignored
|
||||
NUMERIC=42
|
||||
EOF
|
||||
|
||||
AGE_PUBLIC_KEY="$PUBLIC_KEY" \
|
||||
SECRETS_ENV="$SECRETS_ENV" \
|
||||
SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-encrypt.sh"
|
||||
|
||||
_decrypt_vars
|
||||
_assert "simple value" "hello" "${SIMPLE_VAR:-}"
|
||||
_assert "double-quoted value" "world" "${QUOTED_DOUBLE:-}"
|
||||
_assert "single-quoted value" "literal" "${QUOTED_SINGLE:-}"
|
||||
_assert "empty value" "" "${EMPTY_VAR:-}"
|
||||
_assert "numeric value" "42" "${NUMERIC:-}"
|
||||
unset SIMPLE_VAR QUOTED_DOUBLE QUOTED_SINGLE EMPTY_VAR NUMERIC
|
||||
|
||||
# --- multi-line value with \n escape sequences ---
|
||||
# Use a made-up key format to avoid triggering the detect-private-key pre-commit hook.
|
||||
printf '%s\n' \
|
||||
'SSH_KEY="FAKE-KEY-HEADER\nfakekey\nFAKE-KEY-FOOTER"' \
|
||||
'SIDE=plain' \
|
||||
> "$SECRETS_ENV"
|
||||
|
||||
rm -f "$SECRETS_AGE"
|
||||
AGE_PUBLIC_KEY="$PUBLIC_KEY" \
|
||||
SECRETS_ENV="$SECRETS_ENV" \
|
||||
SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-encrypt.sh"
|
||||
|
||||
_decrypt_vars
|
||||
_assert_contains "multi-line: header present" "FAKE-KEY-HEADER" "${SSH_KEY:-}"
|
||||
_assert_contains "multi-line: body present" "fakekey" "${SSH_KEY:-}"
|
||||
_assert_contains "multi-line: footer present" "FAKE-KEY-FOOTER" "${SSH_KEY:-}"
|
||||
_assert "variable alongside multi-line" "plain" "${SIDE:-}"
|
||||
unset SSH_KEY SIDE
|
||||
|
||||
# --- GITHUB_ENV output uses heredoc syntax ---
|
||||
printf '%s\n' 'CI_SECRET=supersecret' > "$SECRETS_ENV"
|
||||
rm -f "$SECRETS_AGE" "$GITHUB_ENV_FILE"
|
||||
AGE_PUBLIC_KEY="$PUBLIC_KEY" \
|
||||
SECRETS_ENV="$SECRETS_ENV" \
|
||||
SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-encrypt.sh"
|
||||
|
||||
GITHUB_ENV="$GITHUB_ENV_FILE" \
|
||||
SECRETS_AGE_KEY="$PRIVATE_KEY" \
|
||||
SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-decrypt.sh"
|
||||
|
||||
_assert_contains "GITHUB_ENV contains key" "CI_SECRET" "$(cat "$GITHUB_ENV_FILE")"
|
||||
_assert_contains "GITHUB_ENV contains value" "supersecret" "$(cat "$GITHUB_ENV_FILE")"
|
||||
|
||||
# --- missing secrets.age exits non-zero with a helpful message ---
|
||||
ERR=$(SECRETS_AGE="$WORKDIR/nonexistent.age" \
|
||||
SECRETS_AGE_KEY="$PRIVATE_KEY" \
|
||||
bash "$SCRIPT_DIR/secrets-decrypt.sh" 2>&1) && GOT=0 || GOT=$?
|
||||
_assert "missing secrets.age: exits non-zero" "1" "$GOT"
|
||||
_assert_contains "missing secrets.age: error mentions file" "secrets.age" "$ERR"
|
||||
|
||||
# --- missing key exits non-zero ---
|
||||
ERR=$(SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-decrypt.sh" 2>&1) && GOT=0 || GOT=$?
|
||||
_assert "missing key: exits non-zero" "1" "$GOT"
|
||||
|
||||
# --- wrong key fails decryption ---
|
||||
OTHER_KEY="$WORKDIR/other.key"
|
||||
age-keygen -o "$OTHER_KEY" 2>/dev/null
|
||||
ERR=$(SECRETS_AGE_KEY=$(cat "$OTHER_KEY") \
|
||||
SECRETS_AGE="$SECRETS_AGE" \
|
||||
bash "$SCRIPT_DIR/secrets-decrypt.sh" 2>&1) && GOT=0 || GOT=$?
|
||||
_assert "wrong key: exits non-zero" "1" "$GOT"
|
||||
|
||||
# --- encrypt without secrets.env exits non-zero ---
|
||||
ERR=$(AGE_PUBLIC_KEY="$PUBLIC_KEY" \
|
||||
SECRETS_ENV="$WORKDIR/missing_secrets.env" \
|
||||
SECRETS_AGE="$WORKDIR/out.age" \
|
||||
bash "$SCRIPT_DIR/secrets-encrypt.sh" 2>&1) && GOT=0 || GOT=$?
|
||||
_assert "encrypt without secrets.env: exits non-zero" "1" "$GOT"
|
||||
_assert_contains "encrypt without secrets.env: error mentions file" "secrets.env" "$ERR"
|
||||
|
||||
echo ""
|
||||
echo "Results: $PASS passed, $FAIL failed"
|
||||
[ "$FAIL" -eq 0 ] || exit 1
|
||||
@@ -0,0 +1,28 @@
|
||||
# Copy this file to secrets.env and fill in real values.
|
||||
# Then encrypt to secrets.age: scripts/secrets-encrypt.sh
|
||||
#
|
||||
# secrets.env — plaintext, git-ignored
|
||||
# secrets.age — encrypted, committed to the repository
|
||||
# .age-public-key — age public key, committed (not secret)
|
||||
#
|
||||
# Multi-line values (SSH keys, certificates) must be stored as a single line
|
||||
# with literal \n for newlines, wrapped in double quotes. Example:
|
||||
# SSH_PRIVATE_KEY="<header line>\n<base64 body lines>\n<footer line>"
|
||||
#
|
||||
# One-time setup:
|
||||
# age-keygen -o ~/.config/age/sharedinbox.key
|
||||
# age-keygen -y ~/.config/age/sharedinbox.key > .age-public-key
|
||||
# # Store the private key content in CI as SECRETS_AGE_KEY secret.
|
||||
|
||||
ANDROID_KEYSTORE_BASE64=
|
||||
ANDROID_KEYSTORE_PASSWORD=
|
||||
PLAY_STORE_CONFIG_JSON=
|
||||
SSH_PRIVATE_KEY=
|
||||
SSH_KNOWN_HOSTS=
|
||||
SSH_USER=
|
||||
SSH_HOST=
|
||||
ANDROID_APK_SCP_HOST=
|
||||
ANDROID_APK_SCP_USER=
|
||||
ANDROID_APK_SCP_PATH=
|
||||
FIREBASE_TEST_LAB_SERVICE_ACCOUNT_KEY=
|
||||
FIREBASE_PROJECT_ID=
|
||||
@@ -27,22 +27,6 @@ class MockUrlLauncher extends Mock
|
||||
}
|
||||
}
|
||||
|
||||
class ThrowingUrlLauncher extends Mock
|
||||
with MockPlatformInterfaceMixin
|
||||
implements UrlLauncherPlatform {
|
||||
@override
|
||||
Future<bool> canLaunch(String? url) async => true;
|
||||
|
||||
@override
|
||||
Future<bool> launchUrl(String? url, LaunchOptions? options) async {
|
||||
throw PlatformException(
|
||||
code: 'channel-error',
|
||||
message: 'Unable to establish connection on channel: '
|
||||
'"dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.launchUrl".',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildScreen({List<Account> accounts = const []}) {
|
||||
return ProviderScope(
|
||||
overrides: [
|
||||
@@ -196,24 +180,4 @@ void main() {
|
||||
);
|
||||
expect(mock.launchedUrl, contains('1.2.3%2B99'));
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'AboutScreen link tap with failed url_launcher shows error snackbar',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1200);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
UrlLauncherPlatform.instance = ThrowingUrlLauncher();
|
||||
|
||||
await tester.pumpWidget(_buildScreen());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.textContaining('sharedinbox.de').first);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('Error:'), findsOneWidget);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:sharedinbox/ui/screens/changelog_screen.dart';
|
||||
|
||||
class _FakeAssetBundle extends CachingAssetBundle {
|
||||
final Map<String, String> _assets;
|
||||
_FakeAssetBundle(this._assets);
|
||||
|
||||
@override
|
||||
Future<ByteData> load(String key) async {
|
||||
if (_assets.containsKey(key)) {
|
||||
final encoded = utf8.encode(_assets[key]!);
|
||||
return ByteData.view(Uint8List.fromList(encoded).buffer);
|
||||
}
|
||||
throw FlutterError('Asset not found: "$key"');
|
||||
}
|
||||
}
|
||||
|
||||
const _fakeChangelog =
|
||||
'* 2024-01-01 feat: initial release\n* 2024-01-02 fix: resolve crash\n';
|
||||
|
||||
void main() {
|
||||
testWidgets('ChangeLogScreen shows changelog content', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
DefaultAssetBundle(
|
||||
bundle: _FakeAssetBundle({'assets/changelog.txt': _fakeChangelog}),
|
||||
child: const MaterialApp(home: ChangeLogScreen()),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('ChangeLog'), findsOneWidget);
|
||||
expect(find.textContaining('initial release'), findsOneWidget);
|
||||
expect(find.textContaining('resolve crash'), findsOneWidget);
|
||||
expect(find.textContaining('Error loading changelog'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('ChangeLogScreen shows error when asset is missing', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
DefaultAssetBundle(
|
||||
bundle: _FakeAssetBundle({}),
|
||||
child: const MaterialApp(home: ChangeLogScreen()),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('Error loading changelog'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -147,7 +147,6 @@ void main() {
|
||||
gitHash: testHash,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Git hash link should be present
|
||||
final gitLinkFinder = find.textContaining('Git Commit: abc1234');
|
||||
@@ -200,109 +199,6 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'CrashScreen shows app version as clickable link when git hash is set',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1200);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(() => tester.view.resetPhysicalSize());
|
||||
|
||||
final mock = MockUrlLauncher();
|
||||
UrlLauncherPlatform.instance = mock;
|
||||
|
||||
const exception = 'TestException: version link test';
|
||||
final stackTrace = StackTrace.current;
|
||||
const testHash = 'abc1234';
|
||||
|
||||
await tester.pumpWidget(
|
||||
CrashScreen(
|
||||
exception: exception,
|
||||
stackTrace: stackTrace,
|
||||
gitHash: testHash,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// App version link should be present (mocked as 1.0.0+42)
|
||||
final versionLinkFinder = find.textContaining('App Version: 1.0.0+42');
|
||||
expect(versionLinkFinder, findsOneWidget);
|
||||
|
||||
// It must appear above the git hash link
|
||||
final gitLinkFinder = find.textContaining('Git Commit: abc1234');
|
||||
expect(
|
||||
tester.getTopLeft(versionLinkFinder).dy,
|
||||
lessThan(tester.getTopLeft(gitLinkFinder).dy),
|
||||
);
|
||||
|
||||
// Tapping it should open the Codeberg commit URL
|
||||
await tester.tap(versionLinkFinder);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
mock.launchedUrl,
|
||||
equals('https://codeberg.org/guettli/sharedinbox/commit/abc1234'),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'CrashScreen copy-to-clipboard includes app version as markdown link when git hash is set',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1200);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(() => tester.view.resetPhysicalSize());
|
||||
|
||||
String? clipboardText;
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(MethodCall call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
clipboardText =
|
||||
(call.arguments as Map<dynamic, dynamic>)['text'] as String?;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
|
||||
const exception = 'TestException: version link clipboard test';
|
||||
final stackTrace = StackTrace.current;
|
||||
const testHash = 'abc1234';
|
||||
|
||||
await tester.pumpWidget(
|
||||
CrashScreen(
|
||||
exception: exception,
|
||||
stackTrace: stackTrace,
|
||||
gitHash: testHash,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Copy to Clipboard'));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(clipboardText, isNotNull);
|
||||
// App Version must be a markdown link pointing to the commit
|
||||
expect(
|
||||
clipboardText,
|
||||
contains(
|
||||
'App Version: [1.0.0+42](https://codeberg.org/guettli/sharedinbox/commit/abc1234)',
|
||||
),
|
||||
);
|
||||
expect(
|
||||
clipboardText,
|
||||
contains(
|
||||
'Git Commit: [abc1234](https://codeberg.org/guettli/sharedinbox/commit/abc1234)',
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'CrashScreen used as root widget — buttons work without ScaffoldMessenger crash',
|
||||
(tester) async {
|
||||
|
||||
@@ -105,88 +105,6 @@ void main() {
|
||||
expect(find.text('Edit account'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'try connection button is disabled when no password stored or entered',
|
||||
(
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
await tester.pumpWidget(
|
||||
buildApp(
|
||||
initialLocation: '/accounts/acc-1/edit',
|
||||
overrides: baseOverrides(
|
||||
accounts: [kTestAccount],
|
||||
hasStoredPassword: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final button = tester.widget<OutlinedButton>(
|
||||
find.byKey(const Key('editTryConnectionButton')),
|
||||
);
|
||||
expect(button.onPressed, isNull);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'try connection button is enabled after typing password with no stored password',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
await tester.pumpWidget(
|
||||
buildApp(
|
||||
initialLocation: '/accounts/acc-1/edit',
|
||||
overrides: baseOverrides(
|
||||
accounts: [kTestAccount],
|
||||
hasStoredPassword: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('editPasswordField')),
|
||||
'mypassword',
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
final button = tester.widget<OutlinedButton>(
|
||||
find.byKey(const Key('editTryConnectionButton')),
|
||||
);
|
||||
expect(button.onPressed, isNotNull);
|
||||
});
|
||||
|
||||
testWidgets('save button is disabled when no password stored or entered', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
await tester.pumpWidget(
|
||||
buildApp(
|
||||
initialLocation: '/accounts/acc-1/edit',
|
||||
overrides: baseOverrides(
|
||||
accounts: [kTestAccount],
|
||||
hasStoredPassword: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final button = tester
|
||||
.widget<FilledButton>(find.widgetWithText(FilledButton, 'Save'));
|
||||
expect(button.onPressed, isNull);
|
||||
});
|
||||
|
||||
testWidgets('connection error shows error message', (tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
|
||||
@@ -44,12 +44,11 @@ import 'package:sharedinbox/ui/screens/thread_detail_screen.dart';
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class FakeAccountRepository implements AccountRepository {
|
||||
final List<Account> _accounts;
|
||||
|
||||
FakeAccountRepository([List<Account>? accounts])
|
||||
: _accounts = List.of(accounts ?? []);
|
||||
|
||||
final List<Account> _accounts;
|
||||
bool hasPassword = true;
|
||||
|
||||
@override
|
||||
Stream<List<Account>> observeAccounts() => Stream.value(List.of(_accounts));
|
||||
|
||||
@@ -76,12 +75,7 @@ class FakeAccountRepository implements AccountRepository {
|
||||
_accounts.removeWhere((a) => a.id == id);
|
||||
|
||||
@override
|
||||
Future<String> getPassword(String accountId) async {
|
||||
if (!hasPassword) {
|
||||
throw StateError('No password stored for account $accountId');
|
||||
}
|
||||
return 'test-password';
|
||||
}
|
||||
Future<String> getPassword(String accountId) async => 'test-password';
|
||||
}
|
||||
|
||||
class FakeShareKeyRepository implements ShareKeyRepository {
|
||||
@@ -520,12 +514,10 @@ List<Override> baseOverrides({
|
||||
DiscoveryResult? discovery,
|
||||
Exception? connectionError,
|
||||
ShareKeyRepository? shareKeyRepository,
|
||||
bool hasStoredPassword = true,
|
||||
}) =>
|
||||
[
|
||||
accountRepositoryProvider.overrideWithValue(
|
||||
FakeAccountRepository(accounts)..hasPassword = hasStoredPassword,
|
||||
),
|
||||
accountRepositoryProvider
|
||||
.overrideWithValue(FakeAccountRepository(accounts)),
|
||||
mailboxRepositoryProvider
|
||||
.overrideWithValue(FakeMailboxRepository(mailboxes)),
|
||||
emailRepositoryProvider.overrideWithValue(FakeEmailRepository()),
|
||||
|
||||
Reference in New Issue
Block a user