Compare commits

...
Author SHA1 Message Date
Thomas SharedInboxandClaude Sonnet 4.6 99b6027faf feat: inject GIT_HASH into Dagger Android/Linux builds so About page shows git hash (#249)
BuildAndroidRelease, BuildAndroidApk, and BuildLinuxRelease in ci/main.go
now accept an optional commitHash parameter and pass it as
--dart-define=GIT_HASH=<hash> to flutter, matching what the local fvm build
tasks already do. PublishAndroid and DeployApk/DeployLinux thread the hash
through. Taskfile publish-android and build-android-bundle tasks are updated
to capture and forward the current HEAD hash.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 15:08:24 +02:00
Thomas SharedInboxandClaude Sonnet 4.6 004aa9e837 fix: disable Save button when no password available, fix changelog fetch-depth (#246, #229)
- Disable Save button (alongside Try connection) when no stored password
  and password field is empty, making both buttons consistent (#246)
- Update deploy-apk and build-linux CI jobs to use fetch-depth: 100 so
  generate-changelog produces a full 50-entry log, matching deploy-playstore (#229)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 14:42:46 +02:00
Bot of Thomas Güttler 3868c160d3 fix: disable Try connection button when no password is available (#235) (#247) 2026-05-25 14:30:13 +02:00
Bot of Thomas Güttler 50fc012e81 Merge pull request 'fix: show password required error instead of crashing when no stored password (#235)' (#238) from issue-235-fix into main 2026-05-25 13:00:44 +02:00
Thomas SharedInboxandClaude Sonnet 4.6 94b20f50be style: format edit_account_screen_test.dart
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 12:49:29 +02:00
Thomas SharedInboxandClaude Sonnet 4.6 885906b204 fix: show password required error instead of crashing when no stored password (#235)
During _load(), check whether a password exists in secure storage and track the result
in _hasStoredPassword. The password field validator now requires user input when no
password is stored, so _tryConnection() fails fast at form validation instead of
throwing an unhandled StateError.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 12:49:29 +02:00
Thomas SharedInboxandClaude Sonnet 4.6 06df3ee200 feat: monitor agent loop health every 2 hours (#217)
- Track a heartbeat timestamp in ~/.sharedinbox-agent-heartbeat at the
  start of each _run_loop() invocation so we can tell when it last ran.
- Add `agent_loop.py monitor` subcommand that exits 1 with a WARNING
  message if the heartbeat is missing, corrupted, or older than 2 hours.
- Add .forgejo/workflows/monitor.yml scheduled workflow that runs the
  monitor check every 2 hours on the self-hosted runner; a CI failure
  serves as the warning when the loop is stalled.
- Add 7 unit tests covering all monitor / heartbeat scenarios.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 12:48:45 +02:00
Bot of Thomas Güttler e03c7708ba feat: show app version as link on crash screen and in MD report (#236) (#245) 2026-05-25 11:40:53 +02:00
27bef3356e fix: skip catch-up merge retry when issue has State/Question (#239) (#242)
When a catch-up PR merge fails (PR stays open after the merge command), the loop sets the issue to State/Question and comments on it. But on the next cron tick the same PR is still open with passing CI, so it tries again — spamming the issue with identical comments every minute.

Fix: before attempting a catch-up merge, fetch the issue's current labels via `_get_issue_labels()`. If `State/Question` is already set, skip the PR entirely.

Closes #239

Co-authored-by: Thomas SharedInbox <sharedinbox@thomas-guettler.de>
Reviewed-on: https://codeberg.org/guettli/sharedinbox/pulls/242
2026-05-25 09:21:23 +02:00
Bot of Thomas Güttler 32ba916cbf fix: trigger deploy on script changes, add changelog dep, deepen fetch (#228) (#233) 2026-05-24 21:05:10 +02:00
Thomas SharedInboxandClaude Sonnet 4.6 86e12ffe72 fix: add fgj to nix store PATH in deploy.sh
fgj is in the nix store but was not included in the PATH glob loop,
causing `FileNotFoundError: 'fgj'` on every cron run.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 19:02:13 +02:00
Thomas SharedInboxandClaude Sonnet 4.6 f4a052bedc feat: add State/ToPlan planning phase to agent loop
Issues labelled State/ToPlan are now picked up by a dedicated planning
agent before any implementation happens. The agent posts a plan as an
issue comment, then the loop transitions the label to State/Planned and
leaves a resume command in a follow-up comment. A human reviews the plan
and manually promotes the issue to State/Ready to trigger implementation.

Planning agents run at higher priority than Ready issues.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 18:56:46 +02:00
Thomas SharedInbox b2c11e0c63 Revert "feat: keep secrets in sync via age-encrypted master key (#208) (#223)"
This reverts commit 96b1660b59.
2026-05-24 18:39:23 +02:00
Bot of Thomas Güttler 09c90c244b fix: load changelog via DefaultAssetBundle for testability (#214) (#225) 2026-05-24 17:50:10 +02:00
23 changed files with 670 additions and 488 deletions
-1
View File
@@ -10,7 +10,6 @@ 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
+28 -44
View File
@@ -38,7 +38,7 @@ jobs:
echo "Changed files:"
echo "$CHANGED"
android_re='^(android/|integration_test/|lib/|pubspec\.yaml|pubspec\.lock|drift_schemas/)'
android_re='^(android/|integration_test/|lib/|pubspec\.yaml|pubspec\.lock|drift_schemas/|scripts/deploy_playstore\.py)'
linux_re='^(linux/|lib/|pubspec\.yaml|pubspec\.lock)'
echo "$CHANGED" | grep -qE "$android_re" \
@@ -65,7 +65,6 @@ 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)
@@ -76,15 +75,11 @@ jobs:
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
run: scripts/setup_dagger_remote.sh
- 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 != ''
if: ${{ secrets.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
@@ -102,13 +97,12 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
fetch-depth: 100
- 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)
@@ -119,15 +113,12 @@ jobs:
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
run: scripts/setup_dagger_remote.sh
- 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 != ''
if: ${{ secrets.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
@@ -145,13 +136,12 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
fetch-depth: 100
- 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)
@@ -162,15 +152,15 @@ jobs:
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
run: scripts/setup_dagger_remote.sh
- 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 != ''
if: ${{ secrets.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
@@ -188,13 +178,12 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
fetch-depth: 100
- 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)
@@ -205,15 +194,13 @@ jobs:
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
run: scripts/setup_dagger_remote.sh
- 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 != ''
if: ${{ secrets.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
@@ -239,7 +226,6 @@ 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)
@@ -250,15 +236,13 @@ jobs:
DAGGER_CLIENT_KEY: ${{ secrets.DAGGER_CLIENT_KEY }}
run: scripts/setup_dagger_remote.sh
- 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 != ''
if: ${{ secrets.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
+18
View File
@@ -0,0 +1,18 @@
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
-1
View File
@@ -22,7 +22,6 @@ assets/changelog.txt
.env.local
.envrc
.direnv/
secrets.env # plaintext secrets — encrypted version (secrets.age) is committed
# --- Android ---
android/.gradle/
+20 -6
View File
@@ -10,9 +10,21 @@ CLI tool `fgj` is available to query issues/PRs/actions.
We use issues, follow this label state machine:
- **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
- **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)
```
List open issues ready to pick up:
@@ -22,9 +34,11 @@ fgj issue list --json --state open | jq '[.[] | select(.labels[].name == "State/
Rules:
- 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.
- 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.
- When working manually: switch to `State/InProgress` as your **first action**:
```bash
fgj issue edit <NUMBER> --remove-label "State/Ready" --add-label "State/InProgress"
+3 -63
View File
@@ -174,70 +174,10 @@ 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 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 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 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 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 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.
**Option 4** (Vault) becomes worthwhile if the project grows to multiple runners or team members who each need audited access to deploy credentials.
+4 -8
View File
@@ -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
- dagger call --progress=plain -q -m ci --source=. build-android-release -o build/app/outputs/bundle/release/app-release.aab
- 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
upload-android-bundle:
desc: Upload AAB from build/ to Play Store via Dagger
@@ -238,6 +238,7 @@ 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"
@@ -246,7 +247,7 @@ tasks:
- sh: test -n "$ANDROID_KEYSTORE_PASSWORD"
msg: "ANDROID_KEYSTORE_PASSWORD is not set"
cmds:
- 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
- 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"
deploy-apk:
desc: Build and deploy Android APK via Dagger
@@ -655,12 +656,7 @@ 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, check-secrets]
check-secrets:
desc: Test secrets encrypt/decrypt scripts (requires age)
cmds:
- bash scripts/test_secrets.sh
deps: [analyze, check-coverage, check-hygiene, check-layers, check-mocks]
check-layers:
desc: Enforce architecture — ui/ must not import data/ (only core/ interfaces allowed)
+40 -30
View File
@@ -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", "age"}).
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{"useradd", "-m", "-s", "/bin/bash", "ci"}).
WithExec([]string{"/bin/sh", "-c",
`flutter_dir=$(dirname $(dirname $(which flutter))); ` +
@@ -381,21 +381,6 @@ 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().
@@ -486,9 +471,6 @@ 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())
@@ -602,9 +584,17 @@ func (m *Ci) BuildLinux() *dagger.Directory {
}
// BuildLinuxRelease builds the Linux release bundle.
func (m *Ci) BuildLinuxRelease() *dagger.Directory {
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)
}
return m.setup(m.linuxSrc()).
WithExec([]string{"flutter", "build", "linux", "--release"}).
WithExec(args).
Directory("build/linux/x64/release/bundle")
}
@@ -617,7 +607,7 @@ func (m *Ci) DeployLinux(
sshHost string,
commitHash string,
) (string, error) {
bundle := m.BuildLinuxRelease()
bundle := m.BuildLinuxRelease(commitHash)
datePath := time.Now().Format("2006/01/02")
remoteDir := fmt.Sprintf("public_html/builds/%s", datePath)
@@ -640,9 +630,20 @@ 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) *dagger.File {
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)
}
return m.setupKeystore(keystoreBase64, keystorePassword).
WithExec([]string{"flutter", "build", "apk", "--release", "--no-pub", "--build-number", buildNumber}).
WithExec(args).
File("build/app/outputs/flutter-apk/app-release.apk")
}
@@ -658,7 +659,7 @@ func (m *Ci) DeployApk(
keystorePassword *dagger.Secret,
buildNumber string,
) (string, error) {
apk := m.BuildAndroidApk(keystoreBase64, keystorePassword, buildNumber)
apk := m.BuildAndroidApk(keystoreBase64, keystorePassword, buildNumber, commitHash)
datePath := time.Now().Format("2006/01/02")
remoteDir := fmt.Sprintf("public_html/builds/%s", datePath)
@@ -734,9 +735,17 @@ 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() *dagger.File {
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)
}
return m.setup(m.androidSrc()).
WithExec([]string{"flutter", "build", "appbundle", "--release", "--no-pub", "--build-number", "1"}).
WithExec(args).
File("build/app/outputs/bundle/release/app-release.aab")
}
@@ -808,9 +817,12 @@ 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()
aab := m.BuildAndroidRelease(commitHash)
stamped := m.StampAndroidVersionCode(aab, versionCode)
signed := m.SignAndroidBundle(stamped, keystoreBase64, keystorePassword)
return m.UploadToPlayStore(ctx, signed, playStoreConfig)
@@ -839,7 +851,6 @@ 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"]
@@ -853,7 +864,6 @@ flowchart TD
hygiene --> check{{"✓ Check"}}
layers --> check
secrets --> check
fmt --> check
analyze --> check
mocks --> check
+1 -1
View File
@@ -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"; do
for pkg in "*go-task-*/bin/task" "*dagger-*/bin/dagger" "*fgj-*/bin/fgj"; do
bin=$(ls -d /nix/store/$pkg 2>/dev/null | sort -V | tail -1)
[ -n "$bin" ] && export PATH="$(dirname "$bin"):$PATH"
done
-3
View File
@@ -87,9 +87,6 @@
# Website
hugo
# Secrets management (master-key encryption for CI sync)
age
# Utilities
git
curl
+2 -2
View File
@@ -1,7 +1,6 @@
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';
@@ -13,7 +12,8 @@ class ChangeLogScreen extends StatelessWidget {
return Scaffold(
appBar: AppBar(title: const Text('ChangeLog')),
body: FutureBuilder<String>(
future: rootBundle.loadString('assets/changelog.txt'),
future:
DefaultAssetBundle.of(context).loadString('assets/changelog.txt'),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
+33 -1
View File
@@ -37,11 +37,14 @@ 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: $version\n'
return 'App Version: $versionDisplay\n'
'Build Mode: $_buildMode\n'
'$gitLine'
'Platform: $platform\n'
@@ -86,6 +89,35 @@ 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(
+21 -4
View File
@@ -38,6 +38,7 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
var _sieveSsl = true;
var _verbose = false;
final _jmapUrlCtrl = TextEditingController();
bool _hasStoredPassword = false;
// -- "Try connection" state ------------------------------------------------
bool _tryTesting = false;
@@ -50,6 +51,7 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
_smtpHostCtrl.addListener(_rebuild);
_sieveHostCtrl.addListener(_rebuild);
_imapHostCtrl.addListener(_rebuild);
_passwordCtrl.addListener(_rebuild);
unawaited(_load());
}
@@ -63,6 +65,11 @@ 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;
@@ -84,6 +91,7 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
_smtpHostCtrl.removeListener(_rebuild);
_sieveHostCtrl.removeListener(_rebuild);
_imapHostCtrl.removeListener(_rebuild);
_passwordCtrl.removeListener(_rebuild);
for (final c in [
_displayNameCtrl,
_usernameCtrl,
@@ -267,10 +275,12 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
),
_field(
_passwordCtrl,
'New password (leave blank to keep)',
_hasStoredPassword
? 'New password (leave blank to keep)'
: 'Password',
key: const Key('editPasswordField'),
obscure: true,
required: false,
required: !_hasStoredPassword,
),
if (account.type == AccountType.jmap) ...[
const Divider(height: 32),
@@ -345,10 +355,17 @@ class _EditAccountScreenState extends ConsumerState<EditAccountScreen> {
testing: _tryTesting,
okMessage: _tryOk,
errorMessage: _tryErr,
onPressed: _tryConnection,
onPressed: _hasStoredPassword || _passwordCtrl.text.isNotEmpty
? _tryConnection
: null,
),
const SizedBox(height: 8),
FilledButton(onPressed: _save, child: const Text('Save')),
FilledButton(
onPressed: _hasStoredPassword || _passwordCtrl.text.isNotEmpty
? _save
: null,
child: const Text('Save'),
),
],
),
),
+141 -11
View File
@@ -8,21 +8,25 @@ 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 + 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,
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,
save state, exit 0
g. No Ready issues print "nothing to do", 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
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" }
"started_at": "2026-05-15T12:00:00+00:00", "type": "issue|plan|ci-fix|pending-ci" }
Output is written to ~/.sharedinbox-agent-logs/<session>-<timestamp>.log.
To resume the Claude conversation, look up the session UUID first:
@@ -53,7 +57,9 @@ 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("/", "-")
)
@@ -63,6 +69,8 @@ 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"}
@@ -145,6 +153,26 @@ 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.
@@ -237,6 +265,14 @@ 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")
@@ -275,6 +311,12 @@ 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.
@@ -444,12 +486,44 @@ 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()
@@ -504,13 +578,29 @@ 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()
# ── 2. Check for a PR opened by the agent ────────────────────────────────
# ── 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 ───────────────────────────────
if pending_issue:
branch = f"issue-{pending_issue}-fix"
pr = _find_pr_for_branch(branch)
@@ -642,6 +732,9 @@ 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)
@@ -738,10 +831,44 @@ 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/Ready. Nothing to do.")
print("No issues with State/ToPlan or State/Ready. Nothing to do.")
return 0
issue = issues[0]
@@ -797,10 +924,13 @@ 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()
-85
View File
@@ -1,85 +0,0 @@
#!/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
-42
View File
@@ -1,42 +0,0 @@
#!/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."
+106
View File
@@ -6,6 +6,7 @@ import json
import os
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -744,5 +745,110 @@ 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()
-153
View File
@@ -1,153 +0,0 @@
#!/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
-28
View File
@@ -1,28 +0,0 @@
# 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=
+54
View File
@@ -0,0 +1,54 @@
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);
});
}
+104
View File
@@ -147,6 +147,7 @@ void main() {
gitHash: testHash,
),
);
await tester.pumpAndSettle();
// Git hash link should be present
final gitLinkFinder = find.textContaining('Git Commit: abc1234');
@@ -199,6 +200,109 @@ 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 {
+82
View File
@@ -105,6 +105,88 @@ 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;
+13 -5
View File
@@ -44,11 +44,12 @@ 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));
@@ -75,7 +76,12 @@ class FakeAccountRepository implements AccountRepository {
_accounts.removeWhere((a) => a.id == id);
@override
Future<String> getPassword(String accountId) async => 'test-password';
Future<String> getPassword(String accountId) async {
if (!hasPassword) {
throw StateError('No password stored for account $accountId');
}
return 'test-password';
}
}
class FakeShareKeyRepository implements ShareKeyRepository {
@@ -514,10 +520,12 @@ List<Override> baseOverrides({
DiscoveryResult? discovery,
Exception? connectionError,
ShareKeyRepository? shareKeyRepository,
bool hasStoredPassword = true,
}) =>
[
accountRepositoryProvider
.overrideWithValue(FakeAccountRepository(accounts)),
accountRepositoryProvider.overrideWithValue(
FakeAccountRepository(accounts)..hasPassword = hasStoredPassword,
),
mailboxRepositoryProvider
.overrideWithValue(FakeMailboxRepository(mailboxes)),
emailRepositoryProvider.overrideWithValue(FakeEmailRepository()),