git.iko.soy/opencode-android
on master help sign in
.github/workflows/build.yml+12−28
since splitsnapshots
unifiedsplit
@@ -12,7 +12,19 @@ concurrency:
12 cancel-in-progress: true
12 cancel-in-progress: true
13
13
14jobs:
14jobs:
15+ # The Crux core is plain Rust — build and unit-test it natively (the Android
16+ # shell mirrors this logic; see README).
17+ core:
18+ name: Crux core
19+ runs-on: ubuntu-latest
20+ steps:
21+ - uses: actions/checkout@v4
22+ - name: Test the Crux core
23+ working-directory: shared
24+ run: cargo test
25+
15 build:
26 build:
27+ name: Android app
16 runs-on: ubuntu-latest
28 runs-on: ubuntu-latest
17
29
18 steps:
30 steps:
@@ -30,43 +42,15 @@ jobs:
30 - name: Run unit tests
42 - name: Run unit tests
31 run: ./gradlew testDebugUnitTest --no-daemon
43 run: ./gradlew testDebugUnitTest --no-daemon
32
44
33− - name: Static analysis (detekt)
34− run: ./gradlew detekt --no-daemon
35−
36 - name: Lint
45 - name: Lint
37 run: ./gradlew lintDebug --no-daemon
46 run: ./gradlew lintDebug --no-daemon
38
47
39 - name: Build debug APK
48 - name: Build debug APK
40 run: ./gradlew assembleDebug --no-daemon
49 run: ./gradlew assembleDebug --no-daemon
41
50
42− - name: Decode release keystore
43− run: |
44− mkdir -p keystore
45− printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > keystore/opencode-release.jks
46− env:
47− OPENCODE_STORE_BASE64: ${{ secrets.OPENCODE_STORE_BASE64 }}
48−
49− - name: Build release APK
50− env:
51− OPENCODE_STORE_FILE: ${{ github.workspace }}/keystore/opencode-release.jks
52− OPENCODE_STORE_PASSWORD: ${{ secrets.OPENCODE_STORE_PASSWORD }}
53− OPENCODE_KEY_ALIAS: ${{ secrets.OPENCODE_KEY_ALIAS }}
54− OPENCODE_KEY_PASSWORD: ${{ secrets.OPENCODE_KEY_PASSWORD }}
55− run: ./gradlew assembleRelease --no-daemon
56−
57 - name: Upload debug APK
51 - name: Upload debug APK
58 uses: actions/upload-artifact@v4
52 uses: actions/upload-artifact@v4
59 with:
53 with:
60 name: opencode-debug.apk
54 name: opencode-debug.apk
61 path: app/build/outputs/apk/debug/*.apk
55 path: app/build/outputs/apk/debug/*.apk
62 if-no-files-found: error
56 if-no-files-found: error
63−
64− # The release output dir is `release/` when unsigned but `release-signed/` (or a
65− # variant name) once a signing config is applied. Match both so CI keeps working
66− # once the OPENCODE_STORE_* secrets are wired up.
67− - name: Upload release APK
68− uses: actions/upload-artifact@v4
69− with:
70− name: opencode-release.apk
71− path: app/build/outputs/apk/**/*.apk
72− if-no-files-found: error
.github/workflows/release.yml+53−36
@@ -1,17 +1,28 @@
1name: Release
1name: Release
2
2
3−# Build the production (release) APK and publish a GitHub Release for every
3+# Build a minified, signed release APK and publish it as a GitHub Release.
4−# commit that lands on master. The version -- and the git tag / release name --
4+#
5−# is derived from the commit's committer date in UTC, formatted as
5+# Runs automatically on every push to `master` (e.g. a merged PR), on a pushed
6−# YYYY.MM.DD.HHMM (e.g. 2026.07.04.1430). It is passed to the Gradle build as
6+# version tag (e.g. `git tag v1.2.0 && git push --tags`), or manually from the
7+# Actions tab (workflow_dispatch). For a branch push or manual run the version
8+# is derived from the current UTC time as YYYY.MM.DD.HHMM; a tag push uses the
9+# tag name (with the leading `v` stripped) as the version.
10+#
11+# The `v*` tag this workflow pushes when publishing a release does NOT retrigger
12+# it: events created with the default GITHUB_TOKEN don't start new workflow runs.
13+#
14+# Signing: if the `OPENCODE_STORE_*` secrets are configured the APK is signed
15+# with that keystore; otherwise the Gradle build falls back to the debug key so
16+# the released APK is still installable (see app/build.gradle.kts). The version
7−# `-PversionName=...` so it is stamped into the APK and surfaces in-app.
17+# is passed to Gradle as `-PversionName/-PversionCode` and stamped into the APK.
8on:
18on:
9 push:
19 push:
10 branches: [master]
20 branches: [master]
21+ tags: ["v*"]
22+ workflow_dispatch:
11
23
12−# A release run should never be aborted mid-flight by a newer push (a
24+# Never abort a release mid-flight — a half-published release with a missing
13−# half-published release with a missing artifact is worse than a slightly stale
25+# artifact is worse than a slightly delayed one.
14−# one), so the group is per-ref but cancel-in-progress is left off.
15concurrency:
26concurrency:
16 group: ${{ github.workflow }}-${{ github.ref }}
27 group: ${{ github.workflow }}-${{ github.ref }}
17 cancel-in-progress: false
28 cancel-in-progress: false
@@ -20,9 +31,14 @@ jobs:
20 release:
31 release:
21 runs-on: ubuntu-latest
32 runs-on: ubuntu-latest
22 permissions:
33 permissions:
23− contents: write # required to push the tag and create the release
34+ contents: write # push the tag and create the release
24− id-token: write # required for OIDC so GitHub can sign the attestation
35+ id-token: write # OIDC so GitHub can sign the provenance attestation
25− attestations: write # required to publish the attestation record
36+ attestations: write # publish the attestation record
37+ env:
38+ OPENCODE_STORE_BASE64: ${{ secrets.OPENCODE_STORE_BASE64 }}
39+ OPENCODE_STORE_PASSWORD: ${{ secrets.OPENCODE_STORE_PASSWORD }}
40+ OPENCODE_KEY_ALIAS: ${{ secrets.OPENCODE_KEY_ALIAS }}
41+ OPENCODE_KEY_PASSWORD: ${{ secrets.OPENCODE_KEY_PASSWORD }}
26 steps:
42 steps:
27 - uses: actions/checkout@v4
43 - uses: actions/checkout@v4
28 with:
44 with:
@@ -30,12 +46,23 @@ jobs:
30 # accurate instead of collapsing to 1 on a shallow clone.
46 # accurate instead of collapsing to 1 on a shallow clone.
31 fetch-depth: 0
47 fetch-depth: 0
32
48
33− - name: Compute version from commit date
49+ - name: Compute version
34 id: version
50 id: version
35 run: |
51 run: |
52+ if [ "${{ github.ref_type }}" = "tag" ]; then
53+ VERSION="${GITHUB_REF_NAME#v}"
54+ TAG="${GITHUB_REF_NAME}"
55+ else
36− VERSION="$(TZ=UTC git log -1 --format=%cd --date=format-local:%Y.%m.%d.%H%M)"
56+ VERSION="$(TZ=UTC date +%Y.%m.%d.%H%M)"
57+ TAG="v${VERSION}"
58+ fi
59+ CODE="$(git rev-list --count HEAD)"
60+ {
37− echo "version=$VERSION" >> "$GITHUB_OUTPUT"
61+ echo "version=$VERSION"
38− echo "Version: $VERSION"
62+ echo "tag=$TAG"
63+ echo "code=$CODE"
64+ } >> "$GITHUB_OUTPUT"
65+ echo "Releasing $TAG (version $VERSION, code $CODE)"
39
66
40 - uses: actions/setup-java@v4
67 - uses: actions/setup-java@v4
41 with:
68 with:
@@ -47,40 +74,30 @@ jobs:
47 - uses: gradle/actions/setup-gradle@v4
74 - uses: gradle/actions/setup-gradle@v4
48
75
49 # The keystore ships as base64 in a secret so it never touches the repo.
76 # The keystore ships as base64 in a secret so it never touches the repo.
50− # When the secret isn't configured the Gradle build falls back to an
77+ # Job-level env makes OPENCODE_STORE_BASE64 available to this `if`.
51− # unsigned APK (the same behavior as a local build), so this workflow is
52− # green even before signing is wired up.
53 - name: Decode signing keystore
78 - name: Decode signing keystore
54 if: env.OPENCODE_STORE_BASE64 != ''
79 if: env.OPENCODE_STORE_BASE64 != ''
55− env:
56− OPENCODE_STORE_BASE64: ${{ secrets.OPENCODE_STORE_BASE64 }}
57 run: |
80 run: |
58 STORE_FILE="$RUNNER_TEMP/release.keystore"
81 STORE_FILE="$RUNNER_TEMP/release.keystore"
59 printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > "$STORE_FILE"
82 printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > "$STORE_FILE"
60 echo "OPENCODE_STORE_FILE=$STORE_FILE" >> "$GITHUB_ENV"
83 echo "OPENCODE_STORE_FILE=$STORE_FILE" >> "$GITHUB_ENV"
61
84
62 - name: Build release APK
85 - name: Build release APK
63− env:
86+ run: |
64− OPENCODE_STORE_FILE: ${{ env.OPENCODE_STORE_FILE }}
87+ ./gradlew assembleRelease \
65− OPENCODE_STORE_PASSWORD: ${{ secrets.OPENCODE_STORE_PASSWORD }}
66− OPENCODE_KEY_ALIAS: ${{ secrets.OPENCODE_KEY_ALIAS }}
67− OPENCODE_KEY_PASSWORD: ${{ secrets.OPENCODE_KEY_PASSWORD }}
68− run: ./gradlew assembleRelease -PversionName="${{ steps.version.outputs.version }}" --no-daemon
88+ -PversionName="${{ steps.version.outputs.version }}" \
89+ -PversionCode="${{ steps.version.outputs.code }}" \
90+ --no-daemon
69
91
70− # Rename to a stable, version-tagged filename so the release attachment is
92+ # Rename to a stable, version-tagged filename for the release attachment.
71− # recognizable regardless of the release/ vs release-signed/ output dir.
72 - name: Stage APK
93 - name: Stage APK
73 run: |
94 run: |
74 mkdir -p staging
95 mkdir -p staging
75− APK="$(find app/build/outputs/apk -name '*.apk' | head -n1)"
96+ APK="$(find app/build/outputs/apk/release -name '*.apk' | head -n1)"
76 cp "$APK" "staging/opencode-${{ steps.version.outputs.version }}.apk"
97 cp "$APK" "staging/opencode-${{ steps.version.outputs.version }}.apk"
77
98
78− # Generate a signed build-provenance attestation for the staged APK and
99+ # Signed build-provenance attestation for the exact artifact being
79− # store it in GitHub's artifact attestation store, keyed by the file's
100+ # published; later verifiable with `gh attestation verify <apk>`.
80− # digest. Anyone can later verify the APK's origin/provenance with
81− # `gh attestation verify` -- its repository & workflow. Run *after*
82− # staging and *before* the release is published so the attested subject
83− # is byte-identical to the artifact attached to the release.
84 - name: Attest build provenance
101 - name: Attest build provenance
85 uses: actions/attest-build-provenance@v2
102 uses: actions/attest-build-provenance@v2
86 with:
103 with:
@@ -89,7 +106,7 @@ jobs:
89 - name: Create release
106 - name: Create release
90 uses: softprops/action-gh-release@v2
107 uses: softprops/action-gh-release@v2
91 with:
108 with:
92− tag_name: ${{ steps.version.outputs.version }}
109+ tag_name: ${{ steps.version.outputs.tag }}
93 name: ${{ steps.version.outputs.version }}
110 name: ${{ steps.version.outputs.version }}
94 make_latest: true
111 make_latest: true
95 generate_release_notes: true
112 generate_release_notes: true
.gitignore+19
@@ -1,6 +1,8 @@
1# Gradle
1# Gradle
2.gradle/
2.gradle/
3build/
3build/
4+*.apk
5+*.aab
4
6
5# Kotlin
7# Kotlin
6.kotlin/
8.kotlin/
@@ -29,4 +31,21 @@ Thumbs.db
29
31
30# Nix
32# Nix
31result
33result
34+result-*
32.direnv/
35.direnv/
36+
37+# Local tooling / editor state (not part of the project)
38+.crush/
39+.crush.db
40+*.log
41+
42+# Rust
43+shared/target/
44+/target/
45+
46+# The `generated/` shared type sources ARE committed (regenerable via
47+# `cargo run --features typegen --bin codegen`); only the built JNI .so
48+# artifacts are ignored.
49+generated/jniLibs/
50+
51+# Gradle wrapper jar is committed so CI can run ./gradlew
AGENTS.mddeleted−197
@@ -1,197 +0,0 @@
1−# AGENTS.md
2−
3−Guidance for AI coding agents (and humans) working in this repository.
4−
5−## Project
6−
7−opencode-android is a native Android client (Kotlin + Jetpack Compose) for the
8−[`opencode serve`](https://opencode.ai/docs/server/) HTTP API. It talks to a
9−remote opencode server over REST plus a long-lived Server-Sent Events stream,
10−and renders conversations (markdown, diffs, tool calls, reasoning, images) with
11−an adaptive single-pane / two-pane Material 3 UI.
12−
13−- Application id / namespace: `soy.iko.opencode`
14−- Package root: `app/src/main/java/soy/iko/opencode`
15−- minSdk 26, compileSdk/targetSdk 37, JDK 17, Kotlin 2.2.x, AGP 9.2.x
16−- Single Gradle module (`:app`); no dynamic feature modules.
17−
18−## Build & environment
19−
20−A Nix flake provides the exact toolchain (JDK 17, Gradle, Android SDK 37, and a
21−Nix-built `aapt2` override because Gradle's bundled aapt2 segfaults on NixOS).
22−
23−```bash
24−nix develop # enter the dev shell (sets ANDROID_HOME, JAVA_HOME, GRADLE_OPTS)
25−./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
26−./gradlew assembleRelease # R8-minified + resource-shrunk; signed only when OPENCODE_STORE_* env vars are set
27−```
28−
29−Outside Nix, you need JDK 17 and the Android SDK (platform 37, build-tools
30−37.0.0) installed manually; `ANDROID_HOME` / `ANDROID_SDK_ROOT` must point at it.
31−
32−Install on a connected device/emulator:
33−
34−```bash
35−adb install -r app/build/outputs/apk/debug/app-debug.apk
36−adb shell am start -n soy.iko.opencode/.MainActivity
37−```
38−
39−## Test, lint, and static analysis
40−
41−```bash
42−./gradlew testDebugUnitTest # JVM unit tests (JSON/reducer/ViewModel logic)
43−./gradlew detekt # static analysis; config: config/detekt/detekt.yml, baseline: app/detekt-baseline.xml
44−./gradlew lintDebug # Android Lint (abortOnError = true)
45−./gradlew connectedAndroidTest # instrumented tests; needs a running AVD or device
46−```
47−
48−- Unit tests live in `app/src/test/...` and run on the JVM. They use fakes from
49− `app/src/test/java/soy/iko/opencode/ui/testing/TestFakes.kt` (Fake* subclasses
50− that override the `open` members of the real stores/clients). JUnit 4 +
51− `kotlinx-coroutines-test`; no Robolectric — `testOptions.unitTests.isReturnDefaultValues = true`
52− stubs Android framework calls so tests brushing `Log.d` etc. don't need it.
53−- Instrumented tests live in `app/src/androidTest/...` and need a device.
54−- detekt runs with a baseline (`app/detekt-baseline.xml`) so only **new**
55− findings block CI; existing ones are grandfathered.
56−- CI (`.github/workflows/build.yml`) runs: `testDebugUnitTest` → `detekt` →
57− `lintDebug` → `assembleDebug` → `assembleRelease`, then uploads both APKs.
58−
59−## Running a server to develop against
60−
61−```bash
62−opencode serve --hostname 0.0.0.0 --port 4096
63−```
64−
65−Connect the app over LAN (`http://<host-ip>:4096`) or USB
66−(`adb reverse tcp:4096 tcp:4096` then `http://127.0.0.1:4096`). Auth is optional
67−(`OPENCODE_SERVER_PASSWORD`; username defaults to `opencode`). See the README's
68−"Set up a server and connect to it" section for full details.
69−
70−## Architecture
71−
72−Unidirectional data flow with manual DI, no annotation processing (no Hilt/KSP).
73−
74−```
75−OpencodeApp (Application)
76− └─ AppContainer (service locator: profile/settings/draft stores, active connection,
77− unread tracker, auto-reconnect, pending share / open-session signals)
78− └─ OpencodeConnection (one per active server profile)
79− ├─ HttpClient (Ktor + OkHttp, base URL + Basic auth + JSON + SSE)
80− ├─ OpencodeApiClient (REST: sessions, messages, files, providers, agents, commands, permissions)
81− ├─ EventStreamClient (long-lived GET /event SSE -> hot SharedFlow<BusEvent>)
82− └─ SessionRepository (reduces BusEvents + REST seeds -> Flow<List<MessageWithParts>>)
83− └─ MessageStore (in-memory reducer; internal, unit-tested)
84−
85−ViewModels (ui/<feature>/<Feature>ViewModel.kt)
86− └─ expose StateFlow; Compose collects with collectAsStateWithLifecycle
87− └─ built via ui/VmFactory.kt (viewModelFactory { initializer { ... } }) from the AppContainer
88−```
89−
90−Key invariants:
91−
92−- **Subscribe before you prompt.** `SessionRepository.observeMessages` collects
93− the SSE stream *before* the initial REST load and before any prompt POST, so
94− early streamed parts aren't missed. Preserve this ordering if you touch it.
95−- **Resilient decoding.** `OpencodeJson` registers `polymorphicDefaultDeserializer`
96− for `Part`, `BusEvent`, `MessageInfo`, and `ToolState`, so an unknown
97− discriminator decodes to an `Unknown*` / `ToolUnknown` variant instead of
98− throwing. Never add a `when (event)` that isn't exhaustive or that crashes on
99− `UnknownEvent` — the whole point is that a new server release can't break the
100− client. Add new modeled variants alongside the `Unknown` fallback.
101−- **Conflated message stream.** `observeMessages` is `.conflate()`d so a burst of
102− per-token snapshots doesn't back-pressure the reducer. Don't remove this.
103−- **Re-seed on SSE reconnect.** When `EventStreamClient.state` returns to
104− `Connected` after a prior connection, the repository re-fetches messages from
105− REST and merges (without pruning) under a generation counter so a stale fetch
106− can't clobber a newer one. See `SessionRepository.kt` for the contract.
107−- **One Ktor client per profile.** `HttpClientFactory.create(profile)` carries
108− the base URL, JSON negotiation, SSE plugin, and auth. Basic auth is sent
109− eagerly (no 401 challenge round-trip) and only installed for HTTPS profiles;
110− for HTTP profiles the `Authorization` header is set proactively in
111− `defaultRequest` instead, and the reactive Auth plugin is deliberately NOT
112− installed so credentials can't be re-sent silently on a cleartext 401.
113−- **Process lifetime.** `OpencodeApp` installs a `CrashLogger`, builds the
114− `AppContainer`, and registers a JVM shutdown hook (since `onTerminate()` isn't
115− called on real devices) that cancels the app scope and closes the active
116− connection. `AppContainer.shutdown()` is guarded against double-invocation.
117−
118−## Source map
119−
120−```
121−data/model Wire models (kotlinx.serialization, sealed polymorphism, @Immutable)
122−data/network Ktor: HttpClientFactory, OpencodeApiClient (REST), EventStreamClient (SSE),
123− OpencodeJson (shared Json), NetworkConfig (all tuning constants)
124−data/repo SessionRepository + MessageStore (reducer), ProfileStore (DataStore +
125− EncryptedSharedPreferences), SettingsStore (theme/dynamic color),
126− DraftStore (per-session draft persistence), CrashLogger, ErrorKind
127−di AppContainer (service locator) + OpencodeConnection (per-server bundle)
128−notification NotificationChannels, RunForegroundService (holds process priority
129− during a run), SessionNotifications (completion notifications)
130−ui OpencodeApp (NavHost), Routes, VmFactory, theme/
131−ui/chat ChatScreen + ChatViewModel, message bubbles, part rendering,
132− agent/model/command picker sheets, permission dialog, export
133−ui/session SessionListScreen + ViewModel, TwoPaneSessionChat (≥840dp)
134−ui/server ServerListScreen + ServerEditScreen (+ ViewModels)
135−ui/file FileBrowserScreen + FileViewScreen (+ ViewModels)
136−ui/settings SettingsScreen, DiagnosticsScreen (crash reports)
137−util Coroutines.kt (runCatchingCancellable, safeExceptionSummary)
138−```
139−
140−## Conventions
141−
142−- **No comments unless asked** — existing code has extensive `//` comments
143− explaining *why* (invariants, race conditions, security rationale). When you
144− add code, match that style only for genuinely non-obvious invariants; don't
145− narrate *what* the code does.
146−- **`runCatchingCancellable`** (`util/Coroutines.kt`) instead of `runCatching`
147− inside coroutines — plain `runCatching` swallows `CancellationException` and
148− breaks structured concurrency. Use it for any try/catch in a suspend context.
149−- **`safeExceptionSummary`** for logging Ktor exceptions — `ClientRequestException`
150− messages embed the full request URL (may contain auth/paths); never log the
151− raw exception from an HTTP call. Crash reports scrub URLs via a regex too.
152−- **`open` classes with protected no-arg test constructors.** Stores, the API
153− client, `EventStreamClient`, `OpencodeConnection`, and `AppContainer` are
154− `open` and have a `protected constructor()` so tests can subclass and override
155− individual members without instantiating Android frameworks. Keep this pattern
156− when adding new injectable components.
157−- **`NetworkConfig`** holds all tuning constants (timeouts, backoffs, buffer
158− sizes, layout thresholds, debounce delays). Add new magic numbers here rather
159− than scattering literals.
160−- **REST path encoding.** `OpencodeApiClient` URL-encodes path segments via
161− `encode()` (e.g. `session/${encode(id)}`). Deep-link session ids are validated
162− against `[A-Za-z0-9_-]+` in `MainActivity` to prevent path traversal.
163−- **Idempotency keys.** `sendPrompt` and `runCommand` generate the
164− `Idempotency-Key` header *before* `withRetry` so all retry attempts share it.
165− Preserve this when adding mutating endpoints.
166−- **`withRetry`** wraps all REST reads and the permission response. Transient
167− failures back off with jitter; see `NetworkConfig` for the parameters.
168−- **Compose:** `collectAsStateWithLifecycle` everywhere; `WhileSubscribed` with a
169− 5s grace period (`stateFlowSubscriptionTimeoutMs`). `@Composable` functions
170− use PascalCase (detekt `FunctionNaming` disabled for this reason). Long
171− composables and long parameter lists are accepted (detekt `LongMethod` /
172− `LongParameterList` disabled).
173−- **Manifest:** cleartext HTTP is permitted via `network_security_config.xml`
174− (opencode serves plain `http://`). `enableOnBackInvokedCallback="true"` for
175− Android 14 predictive back. Deep link scheme `opencode://session/{id}`.
176−- **`@Immutable`** on data models exposed to Compose so they skip recomposition
177− correctly.
178−- **Kotlin code style: `official`** (see `gradle.properties`).
179−
180−## Things to avoid
181−
182−- Don't add Hilt/Dagger/KSP — DI is intentionally hand-written (`AppContainer`).
183−- Don't add Robolectric — JVM tests use `isReturnDefaultValues = true` stubs and
184− fakes; only device-dependent code goes in `androidTest`.
185−- Don't run `nix flake check` manually (CI only — per repo convention).
186−- Don't read or query `/nix/store` (extremely large — per repo convention).
187−- Don't introduce new detekt findings; the baseline only grandfathers existing
188− ones. Run `./gradlew detekt` before considering work done.
189−- Don't log raw Ktor/OkHttp exceptions — use `safeExceptionSummary`.
190−- Don't make a `when (BusEvent)` / `when (Part)` non-exhaustive; the `Unknown*`
191− variants exist for forward compatibility and must remain reachable.
192−
193−## Renovate
194−
195−`renovate.json` keeps dependencies current: Kotlin+AGP and Compose are grouped;
196−Ktor is grouped; AndroidX majors are held for manual review (pinned to
197−compileSdk 37). Dependency upgrades land via Renovate PRs, not manual bumps.
CLAUDE.mdmode 120000 → 100644+40−1
@@ -1 +0,0 @@
1−AGENTS.md
@@ -0,0 +1,40 @@
1+# opencode-android
2+
3+Native Android client for the opencode server, built with Crux (Rust core), Kotlin, and Jetpack Compose.
4+
5+## Architecture
6+
7+- **shared/** — Rust Crux core (canonical spec, unit-tested with `cargo test`)
8+- **app/** — Android shell with Kotlin port of the reducer (`OpencodeCore`)
9+- All app logic in `OpencodeCore.kt`; UI is a thin Compose shell
10+- Three screens: Connect → Sessions → Chat
11+
12+## Key Files
13+
14+- `app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt` — reducer, all state management
15+- `app/src/main/java/soy/iko/opencode/core/ViewModel.kt` — UiState, Event, data classes
16+- `app/src/main/java/soy/iko/opencode/core/Protocol.kt` — wire types, SSE event parser
17+- `app/src/main/java/soy/iko/opencode/core/HttpClient.kt` — OkHttp wrapper
18+- `app/src/main/java/soy/iko/opencode/core/SseClient.kt` — SSE stream client
19+- `app/src/main/java/soy/iko/opencode/ui/screens/` — ConnectScreen, SessionsScreen, ChatScreen
20+- `app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt` — message rendering
21+
22+## Build
23+
24+```sh
25+source .buildenv.sh
26+nix develop -c ./gradlew assembleDebug
27+```
28+
29+## Code Conventions
30+
31+- Kotlin + Jetpack Compose (Material 3)
32+- State flows through `MutableStateFlow<UiState>` → `collectAsStateWithLifecycle`
33+- All state mutations on main dispatcher (viewModelScope)
34+- Network I/O on `Dispatchers.IO` inside HttpClient/SseClient
35+- Keep the Rust core and Kotlin port behaviourally identical
36+
37+## Version Control
38+
39+- Uses `jj` (jujutsu) colocated with git
40+- Push to master: `jj git push --change @` to create a bookmark, or commit then push
README.md+126−64
@@ -1,91 +1,153 @@
1# opencode-android
1# opencode-android
2
2
3−A native Android client (Kotlin + Jetpack Compose) for the [`opencode serve`](https://opencode.ai/docs/server/) HTTP API.
3+A native Android client for the [**opencode**](https://opencode.ai) server (the
4+`sst/opencode` AI coding agent), built with **Crux** (a Rust core), **Kotlin**,
5+and **Jetpack Compose**.
4
6
5−Application id: `soy.iko.opencode`
7+Connect to a running `opencode serve`, browse and create sessions, and chat with
8+the agent — assistant replies (text, reasoning, and tool calls) stream in live
9+over the server's SSE event stream.
6
10
7−## Set up a server and connect to it
11+<p align="center"><em>Connect → Sessions → Chat, with token-by-token streaming.</em></p>
8
12
9−This app is a client for the [`opencode serve`](https://opencode.ai/docs/server/) HTTP API, so you
13+## Architecture
10−need an opencode server running somewhere reachable from your device.
11−
12−### 1. Start the server
13
14
14−On the host that has your project and opencode installed:
15+The app follows the Crux pattern: **all application logic lives in a pure,
16+platform-agnostic core; the platform is a thin shell** that renders the core's
17+view model, sends it events, and performs the side effects it requests.
15
18
16−```bash
19+```
17−opencode serve --hostname 0.0.0.0 --port 4096
20+┌─────────────────────────── shared/ (Rust) ───────────────────────────┐
21+│ Crux core — the single source of truth │
22+│ • Model / Event / Effect / ViewModel │
23+│ • update(): connect+auth, sessions, chat, SSE stream application │
24+│ • crux_http for HTTP effects; unit-tested with `cargo test` │
25+└───────────────────────────────────────────────────────────────────────┘
26+ ▲ mirrored, behaviour-for-behaviour
27+┌─────────────────────────── app/ (Kotlin) ────────────────────────────┐
28+│ Jetpack Compose shell │
29+│ • OpencodeCore — Kotlin port of the reducer (same ViewModel) │
30+│ • HttpClient (OkHttp) + SseClient (okhttp-sse) — the effects │
31+│ • Compose UI: Connect / Sessions / Chat │
32+└───────────────────────────────────────────────────────────────────────┘
18```
33```
19
34
20−Useful flags:
35+### Why a Kotlin port instead of a JNI `.so`?
21
36
22−| Flag | Default | Description |
37+Crux normally compiles the Rust core to a native library and the shell talks to
23−| --- | --- | --- |
38+it over an FFI bridge. That requires an Android cross-compilation toolchain
24−| `--port` | `4096` | Port to listen on |
39+(NDK + a Rust `std` for the `*-linux-android` targets). This project's dev
25−| `--hostname` | `127.0.0.1` | Hostname/interface to bind (`0.0.0.0` exposes it on your LAN) |
40+environment intentionally ships **without** an NDK, so instead:
26−| `--mdns` | `false` | Enable mDNS discovery |
27−| `--cors` | `[]` | Extra browser origins to allow (repeatable) |
28
41
29−The server publishes an OpenAPI 3.1 spec at `http://<hostname>:<port>/doc`.
42+- The **Rust core is the canonical specification** of behaviour and is fully
43+ unit-tested (`cd shared && cargo test`).
44+- The **Android shell runs `OpencodeCore`**, a faithful Kotlin port of the same
45+ reducer, driving an identical `UiState`/`ViewModel`.
30
46
31−### 2. (Optional) Add authentication
47+The FFI boundary is kept clean, so the day an NDK is available the Kotlin port
48+can be swapped for the compiled `.so` behind the same seam. The crate already
49+builds as a `cdylib`/`staticlib` and a `codegen` binary is wired for Crux
50+type-generation.
32
51
33−opencode has no auth by default. To protect the server with HTTP Basic auth:
52+## Project layout
34
53
35−```bash
54+```
36−OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 --port 4096
55+flake.nix Reproducible dev shell (JDK 17, Gradle, Rust, Android SDK 35)
56+shared/ Crux core (Rust)
57+ src/app.rs App: Model, Event, Effect, ViewModel, update, view, tests
58+ src/protocol.rs Lenient serde wire types for the opencode HTTP + SSE API
59+ src/bin/codegen.rs Type-generation entry point (feature = "typegen")
60+generated/ Crux-generated FFI-shared JVM types (from `codegen`)
61+app/ Android app (Kotlin + Compose)
62+ src/main/java/soy/iko/opencode/
63+ core/ OpencodeCore (reducer port), Protocol, HttpClient, SseClient
64+ ui/ Compose screens (Connect/Sessions/Chat), theme, components
65+ MainActivity.kt, CoreViewModel.kt
37```
66```
38
67
39−The username defaults to `opencode` (override with `OPENCODE_SERVER_USERNAME`). Enter these in the
68+## Getting started
40−app's add-server dialog.
41−
42−### 3. Connect from the app
43
69
44−**Over Wi-Fi / LAN** — add a server with base URL `http://<host-LAN-ip>:4096`.
70+### Dev shell
45
71
46−**Over USB only** — forward the port to the device and point the app at localhost:
72+Everything you need is provided by the Nix flake:
47
73
48−```bash
74+```sh
49−adb reverse tcp:4096 tcp:4096
75+nix develop # or: direnv allow (an .envrc with `use flake` is included)
50```
76```
51
77
52−Then use base URL `http://127.0.0.1:4096` in the app.
78+This puts JDK 17, Gradle, `rustc`/`cargo`, and the Android SDK (platform 35,
79+build-tools 35.0.0) on your `PATH`.
53
80
54−> The app permits cleartext HTTP because opencode serves plain `http://`. If you terminate TLS with
81+### Build & test
55−> a reverse proxy, use an `https://` base URL instead.
56
82
57−## Architecture
83+```sh
84+# Rust core — logic + streaming unit tests
85+cd shared && cargo test
86+
87+# Android app — debug APK
88+./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
89+
90+# Android unit tests + lint
91+./gradlew testDebugUnitTest lintDebug
92+```
93+
94+### Run against a server
95+
96+Start opencode's server on your machine or LAN:
58
97
59−- **Ktor 3 (OkHttp engine)** for REST + the long-lived `GET /event` SSE stream.
98+```sh
60−- **kotlinx.serialization** with sealed polymorphism for opencode's discriminated unions
99+opencode serve --port 4096 # optionally behind OPENCODE_SERVER_PASSWORD
61− (`Part`/`type`, `MessageInfo`/`role`, `ToolState`/`status`, `BusEvent`/`type`). Unknown
62− discriminator values fall back to `Unknown*` variants (`OpencodeJson`) so a new server release
63− can't break decoding.
64−- **Manual DI** (`AppContainer` on the `Application`) — no Hilt/KSP.
65−- **Unidirectional state**: `EventStreamClient` exposes the SSE stream as a hot `SharedFlow`;
66− `SessionRepository` reduces events into per-session message state; ViewModels expose `StateFlow`;
67− Compose collects with `collectAsStateWithLifecycle`.
68−- The repository subscribes to `/event` **before** the prompt POST so no early streamed part is missed.
69−
70−Source map: `data/network` (Ktor, SSE, JSON), `data/model` (wire models), `data/repo`
71−(reducer + profile persistence), `di` (container/connection), `ui/<feature>` (Compose screens).
72−
73−## Build
74−
75−```bash
76−nix develop # JDK 17, Gradle 9.6.1, Android SDK 37, aapt2 override
77−./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
78−./gradlew assembleRelease # R8-minified + resource-shrunk release APK
79−./gradlew testDebugUnitTest # JVM tests for the JSON/serialization layer
80−./gradlew detekt # static analysis (config: config/detekt/detekt.yml)
81−./gradlew lintDebug # Android Lint
82−./gradlew connectedAndroidTest # device/emulator tests (needs an AVD)
83```
100```
84
101
85−## Install & run
102+Install the APK, launch the app, and enter the server URL (e.g.
103+`http://192.168.1.10:4096`). If the server was started with a password the app
104+detects the `401`, shows credential fields, and connects with HTTP Basic auth.
105+
106+> Cleartext HTTP is enabled so you can reach a `http://` server on your LAN.
107+
108+## The opencode API this client speaks
109+
110+- **Connect / auth** — `GET /global/health` probes reachability; a `401` triggers
111+ HTTP Basic auth.
112+- **Sessions** — `GET /session`, `POST /session`, `DELETE /session/{id}`.
113+- **Messages** — `GET /session/{id}/message` (each item is `{ info, parts }`).
114+- **Send** — `POST /session/{id}/prompt_async` (returns immediately; the reply
115+ streams over SSE).
116+- **Cancel** — `POST /session/{id}/abort`.
117+- **Stream** — `GET /event` (SSE). The client applies `message.updated`,
118+ `message.part.updated` (text/reasoning/tool, with deltas), `message.removed`,
119+ `session.idle` (clears the "generating" state), `session.error`, and
120+ `session.{created,updated,deleted}` incrementally. Unknown event types are
121+ ignored so new server versions don't break the stream.
122+
123+## Continuous integration & releases
124+
125+- **CI** (`.github/workflows/build.yml`) runs on pushes to `master` and PRs: it
126+ unit-tests the Crux core (`cargo test`), runs the Android unit tests + lint,
127+ and builds the debug APK (uploaded as an artifact).
128+- **Releases** (`.github/workflows/release.yml`): push a version tag to cut a
129+ release — it builds a minified, signed release APK and publishes a GitHub
130+ Release with the APK attached and a signed build-provenance attestation.
131+
132+ ```sh
133+ git tag v1.0.0 && git push origin v1.0.0 # or run the workflow manually
134+ ```
135+
136+ The tag name becomes the version (a manual run uses a `YYYY.MM.DD.HHMM`
137+ timestamp), stamped into the APK via `-PversionName/-PversionCode`.
138+
139+ **Signing:** set the repo secrets `OPENCODE_STORE_BASE64` (base64 of your
140+ keystore), `OPENCODE_STORE_PASSWORD`, `OPENCODE_KEY_ALIAS`, and
141+ `OPENCODE_KEY_PASSWORD` to sign with your own key. Without them the release
142+ build falls back to the debug key, so the APK is still installable.
143+
144+## Notes & limitations
145+
146+- Rendering covers text, reasoning, and tool-call parts. Interactive tool
147+ **permission** prompts (`permission.updated`) are not yet surfaced.
148+- Model/agent selection uses the server's configured default (no picker yet).
149+- No `.so` is built in this environment (see *Architecture* above).
150+
151+## License
86
152
87−```bash
153+Apache-2.0.
88−adb install -r app/build/outputs/apk/debug/app-debug.apk
89−adb shell am start -n soy.iko.opencode/.MainActivity
90−adb logcat --pid=$(adb shell pidof soy.iko.opencode)
91−```
app/build.gradle.kts+46−116
@@ -1,66 +1,59 @@
1plugins {
1plugins {
2 alias(libs.plugins.android.application)
2 alias(libs.plugins.android.application)
3− alias(libs.plugins.kotlin.serialization)
3+ alias(libs.plugins.kotlin.android)
4 alias(libs.plugins.kotlin.compose)
4 alias(libs.plugins.kotlin.compose)
5− alias(libs.plugins.detekt)
5+ alias(libs.plugins.kotlin.serialization)
6}
6}
7
7
8−/**
8+// Version is overridable from the release workflow via
9− * Monotonically increasing versionCode: the git commit count on HEAD, so each release
9+// `-PversionName=... -PversionCode=...`; falls back to sensible defaults locally.
10− * ships a strictly higher code (never a "downgrade" block) without manual bookkeeping.
10+val appVersionName = (project.findProperty("versionName") as String?) ?: "0.1.0"
11− * Falls back to 1 when git or the history isn't available (e.g. a plain source export).
11+val appVersionCode = (project.findProperty("versionCode") as String?)?.toIntOrNull() ?: 1
12− */
13−val gitCommitCount: Int = runCatching {
14− providers.exec {
15− commandLine("git", "rev-list", "--count", "HEAD")
16− }.standardOutput.asText.get().trim().toInt()
17−}.getOrDefault(1)
18
12
19−// Optional versionName override supplied via `-PversionName=...` (used by the
13+// A release keystore is supplied by CI (decoded from a secret) via env vars.
20−// release workflow to stamp the commit-date version into the APK). Falls back to
14+// When it's absent — local builds, or CI before signing is configured — the
21−// the hard-coded version when absent so local builds are unaffected.
15+// release build falls back to the debug signing config so the APK is still
22−val versionNameOverride: String? = providers.gradleProperty("versionName").orNull
16+// installable, rather than producing an uninstallable unsigned APK.
17+val releaseStorePath: String? = System.getenv("OPENCODE_STORE_FILE")
18+val hasReleaseKeystore = releaseStorePath != null && file(releaseStorePath).exists()
23
19
24android {
20android {
25 namespace = "soy.iko.opencode"
21 namespace = "soy.iko.opencode"
26− compileSdk = 37
22+ compileSdk = 35
27− buildToolsVersion = "37.0.0"
28
23
29 defaultConfig {
24 defaultConfig {
30 applicationId = "soy.iko.opencode"
25 applicationId = "soy.iko.opencode"
31 minSdk = 26
26 minSdk = 26
32− targetSdk = 37
27+ targetSdk = 35
33− // Monotonically increasing across builds: derived from the git commit count so
34− // each release ships a strictly higher versionCode without manual bookkeeping
35− // (and never triggers a "downgrade" install block). Falls back to 1 when the
36− // .git history isn't available (e.g. a plain source export).
37− versionCode = gitCommitCount
28+ versionCode = appVersionCode
38− versionName = versionNameOverride ?: "0.1.0"
29+ versionName = appVersionName
30+
39 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
31 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
40 }
32 }
41
33
42− // Release builds are signed when keystore credentials are supplied via env vars
34+ signingConfigs {
43− // (so CI can publish an installable APK). When the env vars are absent, the
35+ if (hasReleaseKeystore) {
44− // release build falls back to unsigned — same behavior as before — so local
45− // builds keep working without any keystore setup.
46− val releaseSigning = providers.environmentVariable("OPENCODE_STORE_FILE").orNull?.let { path ->
47− signingConfigs.create("release") {
36+ create("release") {
48− storeFile = file(path)
37+ storeFile = file(releaseStorePath!!)
49− storePassword = providers.environmentVariable("OPENCODE_STORE_PASSWORD").orNull
38+ storePassword = System.getenv("OPENCODE_STORE_PASSWORD")
50− keyAlias = providers.environmentVariable("OPENCODE_KEY_ALIAS").orNull
39+ keyAlias = System.getenv("OPENCODE_KEY_ALIAS")
51− keyPassword = providers.environmentVariable("OPENCODE_KEY_PASSWORD").orNull
40+ keyPassword = System.getenv("OPENCODE_KEY_PASSWORD")
41+ }
52 }
42 }
53 }
43 }
54
44
55 buildTypes {
45 buildTypes {
56 release {
46 release {
57 isMinifyEnabled = true
47 isMinifyEnabled = true
58− isShrinkResources = true
59 proguardFiles(
48 proguardFiles(
60 getDefaultProguardFile("proguard-android-optimize.txt"),
49 getDefaultProguardFile("proguard-android-optimize.txt"),
61 "proguard-rules.pro",
50 "proguard-rules.pro",
62 )
51 )
63− releaseSigning?.let { signingConfig = it }
52+ signingConfig = if (hasReleaseKeystore) {
53+ signingConfigs.getByName("release")
54+ } else {
55+ signingConfigs.getByName("debug")
56+ }
64 }
57 }
65 }
58 }
66
59
@@ -69,105 +62,42 @@ android {
69 targetCompatibility = JavaVersion.VERSION_17
62 targetCompatibility = JavaVersion.VERSION_17
70 }
63 }
71
64
72− // Use the kotlin { compilerOptions {} } block (the kotlinOptions DSL is deprecated
65+ kotlinOptions {
73− // in favor of the type-safe extension exposed by the Kotlin Gradle plugin).
66+ jvmTarget = "17"
74− kotlin {
75− compilerOptions {
76− jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
77− }
78 }
67 }
79
68
80 buildFeatures {
69 buildFeatures {
81 compose = true
70 compose = true
82 }
71 }
83
72
84− lint {
85− // Fail CI on real errors. Warnings are reported but don't break the build so
86− // minor/style issues don't gate development.
87− abortOnError = true
88− // Dependency upgrades are tracked by Renovate, so don't lint for them here.
89− // ProduceStateDoesNotAssignValue false-positives on valid produceState calls that
90− // assign `value` via a conditional/`withContext` expression (see FileViewScreen's
91− // match-index scan), so it's disabled rather than worked around at each call site.
92− // InvalidFragmentVersionForActivityResult false-positives on FragmentActivity
93− // (the app doesn't use fragments, but BiometricPrompt requires FragmentActivity).
94− // LocalContextGetResourceValueCall flags context.getString() inside LaunchedEffect /
95− // remember lambdas where stringResource() can't be called (not a @Composable scope);
96− // the check is overly aggressive for valid non-composable coroutine contexts.
97− disable += setOf(
98− "GradleDependency",
99− "AndroidGradlePluginVersion",
100− "ProduceStateDoesNotAssignValue",
101− "InvalidFragmentVersionForActivityResult",
102− "LocalContextGetResourceValueCall",
103− )
104− }
105−
106 packaging {
73 packaging {
107 resources {
74 resources {
108 excludes += "/META-INF/{AL2.0,LGPL2.1}"
75 excludes += "/META-INF/{AL2.0,LGPL2.1}"
109 }
76 }
110 }
77 }
111−
112− testOptions {
113− unitTests {
114− // Return default values for Android framework stubs (e.g. Log.d, Context.getString)
115− // instead of throwing "not mocked" exceptions, so JVM unit tests that brush
116− // against Android APIs don't need Robolectric.
117− isReturnDefaultValues = true
118− isIncludeAndroidResources = true
119− }
120− }
121}
78}
122
79
123dependencies {
80dependencies {
124 implementation(libs.androidx.core.ktx)
81 implementation(libs.androidx.core.ktx)
125− implementation(libs.androidx.core.splashscreen)
82+ implementation(libs.androidx.lifecycle.runtime.ktx)
126− implementation(libs.androidx.window)
127− implementation(libs.androidx.activity.compose)
128− implementation(libs.androidx.lifecycle.viewmodel.compose)
129 implementation(libs.androidx.lifecycle.runtime.compose)
83 implementation(libs.androidx.lifecycle.runtime.compose)
130− implementation(libs.androidx.navigation.compose)
84+ implementation(libs.androidx.lifecycle.viewmodel.ktx)
131−
132− implementation(platform(libs.compose.bom))
133− implementation(libs.compose.ui)
134− implementation(libs.compose.ui.graphics)
85+ implementation(libs.androidx.lifecycle.viewmodel.compose)
135− implementation(libs.compose.ui.tooling.preview)
136− implementation(libs.compose.material3)
137− implementation(libs.compose.material.icons.extended)
86+ implementation(libs.androidx.activity.compose)
138− debugImplementation(libs.compose.ui.tooling)
139
87
140− implementation(libs.ktor.client.core)
88+ implementation(platform(libs.androidx.compose.bom))
141− implementation(libs.ktor.client.okhttp)
89+ implementation(libs.androidx.compose.ui)
142− implementation(libs.ktor.client.content.negotiation)
90+ implementation(libs.androidx.compose.ui.graphics)
143− implementation(libs.ktor.serialization.kotlinx.json)
91+ implementation(libs.androidx.compose.ui.tooling.preview)
144− implementation(libs.ktor.client.auth)
92+ implementation(libs.androidx.compose.material3)
93+ implementation(libs.androidx.compose.material.icons.extended)
94+ debugImplementation(libs.androidx.compose.ui.tooling)
145
95
146− implementation(libs.kotlinx.serialization.json)
147 implementation(libs.kotlinx.coroutines.android)
96 implementation(libs.kotlinx.coroutines.android)
148−
149− implementation(libs.androidx.datastore.preferences)
150− implementation(libs.androidx.security.crypto)
151− implementation(libs.androidx.biometric)
97+ implementation(libs.kotlinx.serialization.json)
152− implementation(libs.coil.compose)
153− implementation(libs.coil.network.okhttp)
98+ implementation(libs.okhttp)
154− implementation(libs.markdown.renderer)
99+ implementation(libs.okhttp.sse)
155− implementation(libs.markdown.renderer.m3)
156
100
157 testImplementation(libs.junit)
101 testImplementation(libs.junit)
158 testImplementation(libs.kotlinx.coroutines.test)
102 testImplementation(libs.kotlinx.coroutines.test)
159− testImplementation(libs.ktor.client.mock)
160−
161− androidTestImplementation(libs.androidx.test.ext.junit)
162− androidTestImplementation(libs.androidx.test.runner)
163− androidTestImplementation(libs.androidx.test.core)
164− androidTestImplementation(libs.kotlinx.coroutines.test)
165−}
166−
167−detekt {
168− buildUponDefaultConfig = true
169− // Carry forward the current baseline so CI only fails on *new* findings;
170− // existing issues are grandfathered rather than blocking the migration.
171− baseline = file("detekt-baseline.xml")
172− config.setFrom("$rootDir/config/detekt/detekt.yml")
173}
103}
app/detekt-baseline.xmldeleted−33
@@ -1,33 +0,0 @@
1−<?xml version="1.0" ?>
2−<SmellBaseline>
3− <ManuallySuppressedIssues/>
4− <CurrentIssues>
5− <ID>ComplexCondition:ChatScreen.kt$searchActive &amp;&amp; searchQuery.isNotEmpty() &amp;&amp; searchMessages.isEmpty() &amp;&amp; messages.isNotEmpty()</ID>
6− <ID>ComplexCondition:PartRenderer.kt$part.isImage &amp;&amp; imageContext != null &amp;&amp; (part.source != null || !part.url.isNullOrBlank())</ID>
7− <ID>ComplexCondition:SessionListViewModel.kt$SessionListState$q.isEmpty() &amp;&amp; pinnedIds.isEmpty() &amp;&amp; noArchivedHidden &amp;&amp; directoryFilter == null</ID>
8− <ID>CyclomaticComplexMethod:AppContainer.kt$AppContainer$@OptIn(ExperimentalCoroutinesApi::class) private fun observeMessageActivity()</ID>
9− <ID>CyclomaticComplexMethod:ChatScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( container: AppContainer, sessionId: String, onBack: () -&gt; Unit, onOpenFile: ((String) -&gt; Unit)? = null, onOpenSession: ((String) -&gt; Unit)? = null, focusMessageId: String? = null, onEditProfile: ((String) -&gt; Unit)? = null, )</ID>
10− <ID>CyclomaticComplexMethod:CodeHighlighter.kt$fun highlightLine(line: String, syntax: FileSyntax, palette: HighlightPalette, state: BlockCommentState): AnnotatedString</ID>
11− <ID>CyclomaticComplexMethod:CodeHighlighter.kt$private fun findNumberEnd(line: String, start: Int): Int</ID>
12− <ID>CyclomaticComplexMethod:ConversationExport.kt$fun buildConversationMarkdown(messages: List&lt;MessageWithParts&gt;, title: String?): String</ID>
13− <ID>CyclomaticComplexMethod:DiagnosticsScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun DiagnosticsScreen(onBack: () -&gt; Unit)</ID>
14− <ID>CyclomaticComplexMethod:EventStreamClient.kt$EventStreamClient$private fun stream(): Flow&lt;BusEvent&gt;</ID>
15− <ID>CyclomaticComplexMethod:FileViewScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun FileViewScreen( container: AppContainer, path: String, onBack: () -&gt; Unit, initialLine: Int? = null, )</ID>
16− <ID>CyclomaticComplexMethod:GlobalSearchScreen.kt$@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun GlobalSearchScreen( container: AppContainer, onOpenSession: (String, String?) -&gt; Unit, onBack: () -&gt; Unit, )</ID>
17− <ID>CyclomaticComplexMethod:MainActivity.kt$MainActivity$private fun handleIntent(intent: Intent?)</ID>
18− <ID>CyclomaticComplexMethod:OpencodeApp.kt$@Composable fun OpencodeApp(container: AppContainer)</ID>
19− <ID>CyclomaticComplexMethod:ServerListScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ServerListScreen( container: AppContainer, onConnected: () -&gt; Unit, onAddProfile: () -&gt; Unit, onEditProfile: (String) -&gt; Unit, onDuplicateProfile: (String) -&gt; Unit, )</ID>
20− <ID>CyclomaticComplexMethod:SessionListScreen.kt$@OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable fun SessionListScreen( container: AppContainer, onOpenSession: (String) -&gt; Unit, onDisconnect: () -&gt; Unit, onOpenFiles: () -&gt; Unit, onOpenSettings: () -&gt; Unit, onAddServer: () -&gt; Unit, onOpenSearch: () -&gt; Unit = {}, onEditProfile: ((String) -&gt; Unit)? = null, // Incremented by a host (the two-pane empty-detail pane) to open the new-session // directory picker, so that pane shares this screen's dialog instead of bypassing it. externalNewSessionTrigger: Int = 0, selectedSessionId: String? = null, )</ID>
21− <ID>CyclomaticComplexMethod:SettingsScreen.kt$@OptIn(ExperimentalMaterial3Api::class, ExperimentalCoroutinesApi::class) @Composable fun SettingsScreen( container: AppContainer, onBack: () -&gt; Unit, onManageServers: () -&gt; Unit, onOpenDiagnostics: () -&gt; Unit, onOpenUsage: () -&gt; Unit = {}, onOpenMcp: () -&gt; Unit = {}, onEditProfile: ((String) -&gt; Unit)? = null, )</ID>
22− <ID>LargeClass:AppContainer.kt$AppContainer</ID>
23− <ID>LargeClass:SessionListViewModel.kt$SessionListViewModel : ViewModel</ID>
24− <ID>MatchingDeclarationName:DiffView.kt$DiffLine</ID>
25− <ID>MatchingDeclarationName:RemoteImage.kt$ImageLoadContext</ID>
26− <ID>TooManyFunctions:AppContainer.kt$AppContainer</ID>
27− <ID>TooManyFunctions:ChatViewModel.kt$ChatViewModel : ViewModel</ID>
28− <ID>TooManyFunctions:CrashLogger.kt$CrashLogger</ID>
29− <ID>TooManyFunctions:MessageBubble.kt$soy.iko.opencode.ui.chat.MessageBubble.kt</ID>
30− <ID>TooManyFunctions:OpencodeApiClient.kt$OpencodeApiClient</ID>
31− <ID>TooManyFunctions:SessionNotifications.kt$SessionNotifications</ID>
32− </CurrentIssues>
33−</SmellBaseline>
app/proguard-rules.pro+13−48
@@ -1,51 +1,16 @@
1−# --- kotlinx.serialization ---
1+# kotlinx.serialization — keep generated serializers and @Serializable metadata.
2−# The plugin generates serializers; keep them and the $$serializer companion members.
3−-keepattributes *Annotation*, InnerClasses, Signature, Exceptions
2+-keepattributes *Annotation*, InnerClasses
4-dontnote kotlinx.serialization.**
3-dontnote kotlinx.serialization.**
5−-keepclassmembers class soy.iko.opencode.** {
6− *** Companion;
7−}
8−-keepclasseswithmembers class soy.iko.opencode.** {
9− kotlinx.serialization.KSerializer serializer(...);
10−}
11−# Keep @Serializable classes themselves so their generated serializers can reference them.
12−-keep,includedescriptorclasses class soy.iko.opencode.**$$serializer { *; }
13−-keepclassmembers class soy.iko.opencode.** {
14− *** Companion;
15−}
16−# Keep the serializable model classes (reflection-free serializer lookup needs the class).
17−# Covers ALL @Serializable classes in the app — not just data.model — because several
18−# classes used for persistent storage live elsewhere (OutboxMessage/PersistedAttachment in
19−# data/repo, StoredProfile in ProfileStore, Backup* in BackupManager, RecentSession, …)
20−# and R8 stripping/renaming their fields would break on-disk deserialization in release.
21−-keep @kotlinx.serialization.Serializable class soy.iko.opencode.** { *; }
22
4
23−# --- Ktor / OkHttp (HTTP client + SSE) ---
5+-keepclassmembers class **$$serializer { *; }
24−# Don't warn about missing optional dependencies; keep only the classes that are
6+-keepclasseswithmembers class * {
25−# accessed via reflection (Ktor engine registration, OkHttp internals that R8
7+ @kotlinx.serialization.Serializable <methods>;
26−# would otherwise strip). Narrow keeps instead of `-keep class io.ktor.** { *; }`
8+}
27−# so R8 can still eliminate dead code and shrink the APK.
9+-if @kotlinx.serialization.Serializable class **
28−-dontwarn io.ktor.**
10+-keep, allowobfuscation, allowshrinking class <1>
29−-dontwarn okhttp3.**
30−-dontwarn okio.**
31−-dontwarn org.slf4j.**
32−-dontwarn org.jetbrains.annotations.**
33−# Ktor loads engines and plugins via ServiceLoader — keep the service files.
34−-keep class io.ktor.client.engine.** { *; }
35−-keep class io.ktor.client.plugins.** { *; }
36−-keep class io.ktor.serialization.** { *; }
37−-keep class io.ktor.http.** { *; }
38−# OkHttp uses reflection for platform detection and internal classes.
39−-keep class okhttp3.internal.platform.** { *; }
40−-keep class okhttp3.** { *; }
41−-keep class okio.** { *; }
42−
43−# --- Coil (image loading) ---
44−# Coil uses reflection for loadable decoders and the Compose integration.
45−-keep class coil.** { *; }
46−-keep class coil3.** { *; }
47−-dontwarn coil.**
48
11
49−# --- androidx.security.crypto pulls in Tink, which references compile-only
12+# OkHttp / okio — platform-specific bits referenced reflectively.
50−# com.google.errorprone annotations. They aren't on the runtime classpath.
13+-dontwarn okhttp3.internal.platform.**
51−-dontwarn com.google.errorprone.annotations.**
14+-dontwarn org.conscrypt.**
15+-dontwarn org.bouncycastle.**
16+-dontwarn org.openjsse.**
app/src/androidTest/java/soy/iko/opencode/ApplicationBootstrapTest.ktdeleted−36
@@ -1,36 +0,0 @@
1−package soy.iko.opencode
2−
3−import androidx.test.core.app.ApplicationProvider
4−import androidx.test.ext.junit.runners.AndroidJUnit4
5−import org.junit.Assert.assertNotNull
6−import org.junit.Assert.assertTrue
7−import org.junit.Test
8−import org.junit.runner.RunWith
9−
10−/**
11− * Smoke test for the [OpencodeApp] Application bootstrap: the container and crash logger
12− * are initialized on startup, and the notification channels are created.
13− */
14−@RunWith(AndroidJUnit4::class)
15−class ApplicationBootstrapTest {
16−
17− @Test
18− fun containerIsInitialized() {
19− val app = ApplicationProvider.getApplicationContext<OpencodeApp>()
20− assertNotNull(app.container)
21− assertNotNull(app.container.settingsStore)
22− }
23−
24− @Test
25− fun notificationChannelsExist() {
26− if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) return
27− val context = ApplicationProvider.getApplicationContext<android.content.Context>()
28− // Touching the app instance runs Application.onCreate, which creates the channels.
29− ApplicationProvider.getApplicationContext<OpencodeApp>()
30− val nm = context.getSystemService(android.content.Context.NOTIFICATION_SERVICE)
31− as android.app.NotificationManager
32− val ids = nm.notificationChannels.map { it.id }
33− assertTrue("status channel should exist, got $ids", ids.contains("run_status"))
34− assertTrue("completed channel should exist, got $ids", ids.contains("session_completed"))
35− }
36−}
app/src/androidTest/java/soy/iko/opencode/data/repo/CrashLoggerTest.ktdeleted−67
@@ -1,67 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import androidx.test.core.app.ApplicationProvider
4−import androidx.test.ext.junit.runners.AndroidJUnit4
5−import org.junit.Assert.assertEquals
6−import org.junit.Assert.assertNotNull
7−import org.junit.Assert.assertNull
8−import org.junit.Assert.assertTrue
9−import org.junit.Test
10−import org.junit.runner.RunWith
11−
12−/**
13− * Instrumented test for [CrashLogger]. Runs on a device/emulator so it can exercise the
14− * real app-private filesystem: a simulated crash is written, then read back, listed, and
15− * deleted through the public API.
16− */
17−@RunWith(AndroidJUnit4::class)
18−class CrashLoggerTest {
19−
20− private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
21− private val logger = CrashLogger.get(context)
22−
23− @Test
24− fun writeReadDeleteRoundTrip() {
25− logger.clearAll()
26−
27− // Simulate an uncaught exception by invoking the report path directly.
28− val report = writeFakeReport()
29−
30− logger.refresh()
31− assertEquals(1, logger.reportCount())
32−
33− val content = logger.readReport(report)
34− assertNotNull(content)
35− assertTrue("report should contain the stack trace", content!!.contains("IllegalStateException"))
36− assertTrue("report should contain device metadata", content.contains("Android:"))
37−
38− logger.deleteReport(report)
39− assertEquals(0, logger.reportCount())
40− assertNull(logger.readReport(report))
41− }
42−
43− @Test
44− fun clearAllRemovesEveryReport() {
45− writeFakeReport("a")
46− writeFakeReport("b")
47− logger.refresh()
48− assertTrue(logger.reportCount() >= 2)
49−
50− logger.clearAll()
51− assertEquals(0, logger.reportCount())
52− }
53−
54− private fun writeFakeReport(tag: String = "test"): String {
55− val dir = java.io.File(context.filesDir, "crashes").apply { mkdirs() }
56− val name = "crash-test-${tag}-${System.nanoTime()}.txt"
57− java.io.File(dir, name).writeText(
58− """
59− opencode-android crash report
60− Android: test
61− java.lang.IllegalStateException: boom $tag
62− at Crasher.crash(Crasher.kt:1)
63− """.trimIndent(),
64− )
65− return name
66− }
67−}
app/src/androidTest/java/soy/iko/opencode/data/repo/DraftStoreTest.ktdeleted−59
@@ -1,59 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import androidx.test.core.app.ApplicationProvider
4−import androidx.test.ext.junit.runners.AndroidJUnit4
5−import kotlinx.coroutines.CoroutineScope
6−import kotlinx.coroutines.Dispatchers
7−import kotlinx.coroutines.SupervisorJob
8−import kotlinx.coroutines.cancel
9−import kotlinx.coroutines.runBlocking
10−import org.junit.Assert.assertEquals
11−import org.junit.Test
12−import org.junit.runner.RunWith
13−
14−@RunWith(AndroidJUnit4::class)
15−class DraftStoreTest {
16−
17− private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
18−
19− @Test
20− fun setGetRemoveRoundTrip() = runBlocking {
21− val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
22− val store = DraftStore(context, scope)
23−
24− // Use a unique session ID so it doesn't collide with other tests.
25− val sid = "test-${System.nanoTime()}"
26−
27− store.set(sid, "hello world")
28− assertEquals("hello world", store.get(sid))
29−
30− // Overwrite
31− store.set(sid, "updated")
32− assertEquals("updated", store.get(sid))
33−
34− // Blank clears the entry
35− store.set(sid, " ")
36− assertEquals("", store.get(sid))
37−
38− // Explicit remove
39− store.set(sid, "text")
40− store.remove(sid)
41− assertEquals("", store.get(sid))
42−
43− scope.cancel()
44− }
45−
46− @Test
47− fun getReturnsEmptyForUnknownSession() {
48− // Create the scope in a local val so it can be cancelled — DraftStore launches a
49− // debounced-persistence collector into the supplied scope that keeps running until
50− // cancelled, and an uncanceled scope leaks across test invocations on device.
51− val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
52− try {
53− val store = DraftStore(context, scope)
54− assertEquals("", store.get("never-set-${System.nanoTime()}"))
55− } finally {
56− scope.cancel()
57− }
58− }
59−}
app/src/main/AndroidManifest.xml+6−115
@@ -1,135 +1,26 @@
1<?xml version="1.0" encoding="utf-8"?>
1<?xml version="1.0" encoding="utf-8"?>
2−<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
3− xmlns:tools="http://schemas.android.com/tools">
4
3
5 <uses-permission android:name="android.permission.INTERNET" />
4 <uses-permission android:name="android.permission.INTERNET" />
6 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
5 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
7− <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
8− <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
9− <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
10−
11− <!-- Camera is used opportunistically for attachment capture via the system camera app
12− (ACTION_IMAGE_CAPTURE), so it's optional — devices without a camera still install. -->
13− <uses-feature android:name="android.hardware.camera.any" android:required="false" />
14
6
15 <application
7 <application
16− android:name=".OpencodeApp"
17− android:allowBackup="false"
8+ android:allowBackup="true"
18− android:dataExtractionRules="@xml/data_extraction_rules"
9+ android:icon="@android:drawable/sym_def_app_icon"
19− android:fullBackupContent="false"
20− android:icon="@mipmap/ic_launcher"
21 android:label="@string/app_name"
10 android:label="@string/app_name"
22− android:networkSecurityConfig="@xml/network_security_config"
23 android:supportsRtl="true"
11 android:supportsRtl="true"
24− android:theme="@style/Theme.OpencodeAndroid">
12+ android:theme="@style/Theme.OpencodeAndroid"
13+ android:usesCleartextTraffic="true">
25
14
26 <activity
15 <activity
27 android:name=".MainActivity"
16 android:name=".MainActivity"
28 android:exported="true"
17 android:exported="true"
29− android:launchMode="singleTop"
30− android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|uiMode|navigation"
31− android:enableOnBackInvokedCallback="true"
32 android:windowSoftInputMode="adjustResize"
18 android:windowSoftInputMode="adjustResize"
33− tools:targetApi="33"
34− android:theme="@style/Theme.OpencodeAndroid.Splash">
19+ android:theme="@style/Theme.OpencodeAndroid">
35 <intent-filter>
20 <intent-filter>
36 <action android:name="android.intent.action.MAIN" />
21 <action android:name="android.intent.action.MAIN" />
37 <category android:name="android.intent.category.LAUNCHER" />
22 <category android:name="android.intent.category.LAUNCHER" />
38 </intent-filter>
23 </intent-filter>
39− <intent-filter>
40− <action android:name="android.intent.action.SEND" />
41− <category android:name="android.intent.category.DEFAULT" />
42− <data android:mimeType="text/plain" />
43− </intent-filter>
44− <!-- Receive images shared from other apps (single or multiple) to attach to a prompt. -->
45− <intent-filter>
46− <action android:name="android.intent.action.SEND" />
47− <category android:name="android.intent.category.DEFAULT" />
48− <data android:mimeType="image/*" />
49− </intent-filter>
50− <intent-filter>
51− <action android:name="android.intent.action.SEND_MULTIPLE" />
52− <category android:name="android.intent.category.DEFAULT" />
53− <data android:mimeType="image/*" />
54− </intent-filter>
55− <!-- Deep link to a session: opencode://session/{sessionId} -->
56− <intent-filter>
57− <action android:name="android.intent.action.VIEW" />
58− <category android:name="android.intent.category.DEFAULT" />
59− <category android:name="android.intent.category.BROWSABLE" />
60− <data android:scheme="opencode" android:host="session" />
61− </intent-filter>
62− <!-- Deep links: opencode://file/{path} and opencode://new -->
63− <intent-filter>
64− <action android:name="android.intent.action.VIEW" />
65− <category android:name="android.intent.category.DEFAULT" />
66− <category android:name="android.intent.category.BROWSABLE" />
67− <data android:scheme="opencode" android:host="file" />
68− </intent-filter>
69− <intent-filter>
70− <action android:name="android.intent.action.VIEW" />
71− <category android:name="android.intent.category.DEFAULT" />
72− <category android:name="android.intent.category.BROWSABLE" />
73− <data android:scheme="opencode" android:host="new" />
74− </intent-filter>
75 </activity>
24 </activity>
76−
77− <service
78− android:name=".notification.RunForegroundService"
79− android:exported="false"
80− android:foregroundServiceType="dataSync" />
81−
82− <!-- Handles notification action buttons (permission responses, inline reply). Not
83− exported: only the app's own PendingIntents target it. -->
84− <receiver
85− android:name=".notification.NotificationActionReceiver"
86− android:exported="false" />
87−
88− <!-- Home-screen widget listing recent sessions. -->
89− <receiver
90− android:name=".platform.SessionsWidgetProvider"
91− android:exported="true">
92− <intent-filter>
93− <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
94− </intent-filter>
95− <meta-data
96− android:name="android.appwidget.provider"
97− android:resource="@xml/sessions_widget_info" />
98− </receiver>
99−
100− <!-- Serves the widget's session list rows. Bound by the system with BIND_REMOTEVIEWS.
101− exported="true" is required: the AppWidget host runs in the launcher/system process
102− (a different process from the app), so it can only bindService to a service that's
103− visible outside the app. The BIND_REMOTEVIEWS permission restricts *who* can bind to
104− the system; exported="false" would make the service invisible to the host and the
105− widget's RemoteViewsService adapter would never populate. -->
106− <service
107− android:name=".platform.SessionsWidgetService"
108− android:permission="android.permission.BIND_REMOTEVIEWS"
109− android:exported="true" />
110−
111− <!-- Quick-settings tile: start a new session. Bound by the system. -->
112− <service
113− android:name=".platform.NewSessionTileService"
114− android:icon="@drawable/ic_launcher_foreground"
115− android:label="@string/tile_new_session"
116− android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
117− android:exported="true">
118− <intent-filter>
119− <action android:name="android.service.quicksettings.action.QS_TILE" />
120− </intent-filter>
121− </service>
122−
123− <!-- Serves camera-capture temp files (cache/captures) to the system camera app. -->
124− <provider
125− android:name="androidx.core.content.FileProvider"
126− android:authorities="${applicationId}.fileprovider"
127− android:exported="false"
128− android:grantUriPermissions="true">
129− <meta-data
130− android:name="android.support.FILE_PROVIDER_PATHS"
131− android:resource="@xml/file_paths" />
132− </provider>
133 </application>
25 </application>
134−
135</manifest>
26</manifest>
app/src/main/java/soy/iko/opencode/CoreViewModel.ktnew file+66
@@ -0,0 +1,66 @@
1+package soy.iko.opencode
2+
3+import android.app.Application
4+import android.content.Context
5+import androidx.core.content.edit
6+import androidx.lifecycle.AndroidViewModel
7+import androidx.lifecycle.viewModelScope
8+import kotlinx.coroutines.flow.distinctUntilChangedBy
9+import kotlinx.coroutines.launch
10+import soy.iko.opencode.core.Event
11+import soy.iko.opencode.core.OpencodeCore
12+
13+/**
14+ * Lifecycle-scoped host for the [OpencodeCore] so a single core (and its SSE
15+ * connection) survives configuration changes. It also persists the last server
16+ * URL / username so reconnecting is one tap.
17+ */
18+class CoreViewModel(app: Application) : AndroidViewModel(app) {
19+ private val prefs = app.getSharedPreferences("opencode", Context.MODE_PRIVATE)
20+
21+ val core = OpencodeCore(viewModelScope)
22+
23+ init {
24+ prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
25+ prefs.getString(KEY_USER, null)?.let { core.dispatch(Event.UsernameChanged(it)) }
26+ // The password is stored in plain text in SharedPreferences — a deliberate
27+ // convenience trade-off for a local dev tool so reconnecting is one tap.
28+ prefs.getString(KEY_PASSWORD, null)?.let { core.dispatch(Event.PasswordChanged(it)) }
29+
30+ // On a fresh process after a configuration change, resume the SSE stream if
31+ // the core is already connected (no-op otherwise — it guards on `connected`).
32+ core.resumeStreamingIfConnected()
33+
34+ // Returning users shouldn't have to tap Connect: if a URL was restored and we
35+ // aren't already connected, kick off the connection attempt on launch. The core
36+ // handles an empty/invalid URL, so this only fires when there's something to try.
37+ core.view.value.let { restored ->
38+ if (restored.serverUrl.isNotEmpty() && !restored.connected) {
39+ core.dispatch(Event.Connect)
40+ }
41+ }
42+
43+ // Persist connection details once a connection succeeds.
44+ viewModelScope.launch {
45+ core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
46+ if (state.connected) {
47+ prefs.edit {
48+ putString(KEY_URL, state.serverUrl)
49+ putString(KEY_USER, state.username)
50+ putString(KEY_PASSWORD, state.password)
51+ }
52+ }
53+ }
54+ }
55+ }
56+
57+ override fun onCleared() {
58+ core.shutdown()
59+ }
60+
61+ private companion object {
62+ const val KEY_URL = "serverUrl"
63+ const val KEY_USER = "username"
64+ const val KEY_PASSWORD = "password"
65+ }
66+}
app/src/main/java/soy/iko/opencode/MainActivity.kt+15−434
@@ -1,450 +1,31 @@
1package soy.iko.opencode
1package soy.iko.opencode
2
2
3−import android.Manifest
4−import android.content.Intent
5−import android.content.pm.PackageManager
6−import android.net.Uri
7−import android.os.Build
8import android.os.Bundle
3import android.os.Bundle
9−import android.view.WindowManager
4+import androidx.activity.ComponentActivity
10−import androidx.core.content.IntentCompat
5+import androidx.activity.SystemBarStyle
11−import soy.iko.opencode.data.network.NetworkConfig
12−import soy.iko.opencode.notification.NotificationActionReceiver
13import androidx.activity.compose.setContent
6import androidx.activity.compose.setContent
14import androidx.activity.enableEdgeToEdge
7import androidx.activity.enableEdgeToEdge
15−import androidx.activity.result.contract.ActivityResultContracts
16−import androidx.compose.foundation.isSystemInDarkTheme
17−import androidx.compose.material3.AlertDialog
18−import androidx.compose.material3.Text
19−import androidx.compose.material3.TextButton
20−import androidx.compose.runtime.LaunchedEffect
21import androidx.compose.runtime.getValue
8import androidx.compose.runtime.getValue
22−import androidx.compose.runtime.mutableStateOf
23−import androidx.compose.runtime.remember
24−import androidx.compose.runtime.setValue
25−import androidx.compose.ui.res.stringResource
26−import kotlinx.coroutines.Dispatchers
27−import kotlinx.coroutines.flow.combine
28−import kotlinx.coroutines.launch
29−import kotlinx.coroutines.withContext
30−import androidx.core.content.ContextCompat
31−import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
32−import androidx.fragment.app.FragmentActivity
33import androidx.lifecycle.compose.collectAsStateWithLifecycle
9import androidx.lifecycle.compose.collectAsStateWithLifecycle
34−import androidx.lifecycle.lifecycleScope
10+import androidx.lifecycle.viewmodel.compose.viewModel
35−import soy.iko.opencode.data.repo.SettingsStore
36−import soy.iko.opencode.data.repo.ThemeMode
37−import soy.iko.opencode.ui.AppLockGate
38−import soy.iko.opencode.ui.OpencodeApp as OpencodeAppUi
11+import soy.iko.opencode.ui.OpencodeApp
39import soy.iko.opencode.ui.theme.OpencodeTheme
12import soy.iko.opencode.ui.theme.OpencodeTheme
40
13
41−// FragmentActivity (not ComponentActivity) so androidx.biometric BiometricPrompt can attach
42−// for the app-lock gate; FragmentActivity extends ComponentActivity, so Compose/edge-to-edge
43−// /activity-result APIs are unaffected.
44−class MainActivity : FragmentActivity() {
14+class MainActivity : ComponentActivity() {
45−
46− private val requestNotificationPermission = registerForActivityResult(
47− ActivityResultContracts.RequestPermission(),
48− ) { /* Result is best-effort; notifications are silently skipped if denied. */ }
49−
50− private var shareIntentHandled = false
51− private var openSessionHandled = false
52− private var newSessionHandled = false
53− private var openFileHandled = false
54− // Set when a deep link was present but failed validation (malformed id/path). Surfaced
55− // as a toast from onResume so the user knows the link was rejected, not silently ignored.
56− private var showInvalidLinkToast = false
57− // Cold-start prompts (crash report, notification rationale) rendered as Compose M3
58− // dialogs. Hoisted as Activity-level mutableState so the non-composable trigger logic
59− // (onCreate/onResume) can flip them and the Compose tree (inside OpencodeTheme) reads
60− // them and renders an M3 AlertDialog that picks up the app palette. The triggers
61− // themselves are idempotent per instance (crashes are acknowledged on first fire;
62− // notificationPermissionRequested is restored from saved state), so a plain
63− // mutableStateOf (not saveable) preserves the original dismissal semantics across
64− // config-change recreation: the prompt simply doesn't re-fire after a rotate.
65− private var showCrashPrompt by mutableStateOf(false)
66− private var showNotifRationale by mutableStateOf(false)
67− // Track whether the notification-permission prompt has been shown for this Activity
68− // instance. onCreate only requests when savedInstanceState == null (a fresh process),
69− // but an Activity recreated by a config change NOT listed in the manifest's configChanges
70− // (e.g. a locale change) has a non-null savedInstanceState and would otherwise skip the
71− // prompt forever. onResume re-requests once per instance when still ungranted so the user
72− // is never silently left without notifications after such a recreation.
73− private var notificationPermissionRequested = false
74−
75 override fun onCreate(savedInstanceState: Bundle?) {
15 override fun onCreate(savedInstanceState: Bundle?) {
76− val splash = installSplashScreen()
16+ enableEdgeToEdge(
17+ statusBarStyle = SystemBarStyle.auto(
18+ lightScrim = 0xFF0F1115.toInt(),
19+ darkScrim = 0xFF0F1115.toInt(),
20+ ),
21+ )
77 super.onCreate(savedInstanceState)
22 super.onCreate(savedInstanceState)
78− enableEdgeToEdge()
79− savedInstanceState?.let {
80− shareIntentHandled = it.getBoolean(KEY_SHARE_HANDLED, false)
81− openSessionHandled = it.getBoolean(KEY_OPEN_SESSION_HANDLED, false)
82− newSessionHandled = it.getBoolean(KEY_NEW_SESSION_HANDLED, false)
83− openFileHandled = it.getBoolean(KEY_OPEN_FILE_HANDLED, false)
84− }
85− val container = (application as OpencodeApp).container
86− handleIntent(intent)
87− if (savedInstanceState == null) {
88− maybeRequestNotificationPermission()
89− } else {
90− // Restored instance: the permission may have been requested pre-recreation, but
91− // we can't know the result from here. onResume will re-check and request if still
92− // ungranted (once per Activity instance).
93− notificationPermissionRequested = savedInstanceState.getBoolean(KEY_NOTIF_PERM_REQUESTED, false)
94− }
95− // Hold the splash until the persisted theme and app-lock settings load, so we never
96− // paint a frame with the defaults (dynamicColor=false / SYSTEM, app lock off) that then
97− // snap to the user's real choice — including a brief unlocked, un-FLAG_SECURE'd frame
98− // before app lock resolves. Mirrors the SettingsScreen's null-gate.
99− var settingsLoaded = false
100− splash.setKeepOnScreenCondition { !settingsLoaded }
101− // Custom splash exit: a quick fade-out instead of the system default's slide, so the
102− // hand-off to Compose reads as a branded dissolve. The listener must call
103− // splashScreenViewProvider.remove() to release the splash view; otherwise the system
104− // keeps it on screen for its default duration. Reduced-motion is respected via the
105− // animator's duration scale (the system zeroes it under reduced motion).
106− splash.setOnExitAnimationListener { splashScreenViewProvider ->
107− val view = splashScreenViewProvider.view
108− val fade = android.view.animation.AlphaAnimation(1f, 0f).apply {
109− duration = 180
110− fillAfter = true
111− }
112− fade.setAnimationListener(object : android.view.animation.Animation.AnimationListener {
113− override fun onAnimationStart(animation: android.view.animation.Animation?) {}
114− override fun onAnimationEnd(animation: android.view.animation.Animation?) {
115− splashScreenViewProvider.remove()
116− }
117− override fun onAnimationRepeat(animation: android.view.animation.Animation?) {}
118− })
119− view.startAnimation(fade)
120− }
121 setContent {
23 setContent {
122− val theme by remember(container) {
24+ OpencodeTheme {
123− container.settingsStore.themeMode
25+ val vm: CoreViewModel = viewModel()
124− .combine(container.settingsStore.dynamicColor, ::Pair)
26+ val state by vm.core.view.collectAsStateWithLifecycle()
125− }.collectAsStateWithLifecycle(initialValue = null)
27+ OpencodeApp(state = state, dispatch = vm.core::dispatch)
126− val appLock by container.settingsStore.appLock.collectAsStateWithLifecycle(initialValue = null)
127− val appLockReLockSeconds by container.settingsStore.appLockReLockSeconds
128− .collectAsStateWithLifecycle(initialValue = SettingsStore.DEFAULT_APP_LOCK_RELOCK_SECONDS)
129− LaunchedEffect(theme, appLock) { if (theme != null && appLock != null) settingsLoaded = true }
130− // Hide the app's content from screenshots / the recents thumbnail while app lock is
131− // enabled — and while its value is still unknown (null) at cold start, so a protected
132− // launch can't flash into the recents thumbnail before the setting resolves.
133− LaunchedEffect(appLock) {
134− if (appLock != false) window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
135− else window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
136− }
137− val themePair = theme
138− val locked = appLock
139− if (themePair != null && locked != null) {
140− val (themeMode, dynamicColor) = themePair
141− val amoled = themeMode == ThemeMode.AMOLED
142− val dark = when (themeMode) {
143− ThemeMode.SYSTEM -> isSystemInDarkTheme()
144− ThemeMode.LIGHT -> false
145− ThemeMode.DARK -> true
146− ThemeMode.AMOLED -> true
147− }
148− OpencodeTheme(darkTheme = dark, dynamicColor = dynamicColor, amoled = amoled) {
149− AppLockGate(enabled = locked, reLockDelaySeconds = appLockReLockSeconds) {
150− OpencodeAppUi(container = container)
151− }
152− // First-launch prompts as Compose M3 dialogs (siblings of AppLockGate so they
153− // still surface over the lock screen, matching the prior framework-dialog
154− // behavior) and inside OpencodeTheme so they use the app palette.
155− if (showCrashPrompt) {
156− AlertDialog(
157− onDismissRequest = { showCrashPrompt = false },
158− title = { Text(stringResource(R.string.crash_last_run_title)) },
159− text = { Text(stringResource(R.string.crash_last_run_text)) },
160− confirmButton = {
161− TextButton(onClick = {
162− showCrashPrompt = false
163− container.requestDiagnostics()
164− }) { Text(stringResource(R.string.crash_last_run_view)) }
165− },
166− dismissButton = {
167− TextButton(onClick = { showCrashPrompt = false }) {
168− Text(stringResource(R.string.crash_last_run_dismiss))
169− }
170− },
171− )
172− }
173− if (showNotifRationale) {
174− AlertDialog(
175− // Mirrors the original setCancelable(false): not dismissible by
176− // back/outside tap, only by the buttons below.
177− onDismissRequest = { },
178− title = { Text(stringResource(R.string.notif_rationale_title)) },
179− text = { Text(stringResource(R.string.notif_rationale_text)) },
180− confirmButton = {
181− TextButton(onClick = {
182− showNotifRationale = false
183− runCatching { requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS) }
184− }) { Text(stringResource(R.string.notif_rationale_allow)) }
185− },
186− dismissButton = {
187− TextButton(onClick = { showNotifRationale = false }) {
188− Text(stringResource(R.string.notif_rationale_skip))
189− }
190− },
191− )
192− }
193− }
194− }
195− }
196− // Surface a "crashed last time" prompt if a crash report from a previous run
197− // hasn't been acknowledged. Acknowledges immediately so it doesn't re-fire on
198− // every rotation/resume; the user can always find reports in Settings → Diagnostics.
199− maybeShowCrashPrompt()
200− }
201−
202− private fun maybeShowCrashPrompt() {
203− // The check does a directory scan + per-file stat (listFiles + lastModified), which
204− // is synchronous filesystem I/O. Run it off the main thread so the cold-start
205− // critical path (before setContent's first frame) isn't blocked by up to ~20 stat
206− // syscalls on slow storage. The prompt state flips on once the result arrives; the
207− // splash screen has already been dismissed by then, so the dialog appears a frame
208− // or two later than it would have synchronously — invisible to the user.
209− val crashLogger = soy.iko.opencode.data.repo.CrashLogger.get(this)
210− lifecycleScope.launch {
211− val hasUnacknowledged = withContext(Dispatchers.IO) {
212− crashLogger.hasUnacknowledgedCrash()
213 }
28 }
214− if (hasUnacknowledged) {
215− crashLogger.acknowledgeCrashes()
216− showCrashPrompt = true
217− }
218− }
219− }
220−
221− override fun onNewIntent(intent: Intent) {
222− super.onNewIntent(intent)
223− setIntent(intent)
224− shareIntentHandled = false
225− openSessionHandled = false
226− newSessionHandled = false
227− openFileHandled = false
228− handleIntent(intent)
229− }
230−
231− // Track real foreground state so background notifications (permission requests,
232− // completions, errors) still fire for a session the user "has open" but has walked
233− // away from — the chat screen isn't disposed when the phone is locked, so
234− // container.currentSession stays set and can't be used as a foreground signal.
235− override fun onStart() {
236− super.onStart()
237− (application as OpencodeApp).container.setForeground(true)
238− }
239−
240− override fun onStop() {
241− super.onStop()
242− (application as OpencodeApp).container.setForeground(false)
243− }
244−
245− override fun onResume() {
246− super.onResume()
247− // Re-check on resume: an Activity recreated by a config change not in configChanges
248− // (e.g. locale) has savedInstanceState != null, so onCreate skipped the request. This
249− // ensures the user is prompted once per Activity instance when still ungranted rather
250− // than silently losing all notifications.
251− maybeRequestNotificationPermission()
252− // Surface a rejected deep link once, so a malformed opencode:// link doesn't appear
253− // to be silently ignored. Cleared after firing so a rotation doesn't re-toast.
254− if (showInvalidLinkToast) {
255− showInvalidLinkToast = false
256− android.widget.Toast.makeText(this, R.string.deep_link_invalid, android.widget.Toast.LENGTH_SHORT).show()
257 }
29 }
258 }
30 }
259−
260− /** Capture text shared from another app so it can be prefilled into a session draft,
261− * and session ids from notification taps / deep links so we can open them. */
262− private fun handleIntent(intent: Intent?) {
263− val container = (application as OpencodeApp).container
264− val action = intent?.action
265− // "New session" from a launcher shortcut or the quick-settings tile. Guarded so a
266− // process-death restore (which re-delivers the intent) doesn't spawn a second session.
267− if (action == ACTION_NEW_SESSION && !newSessionHandled) {
268− container.requestNewSession()
269− newSessionHandled = true
270− }
271− if ((action == Intent.ACTION_SEND || action == Intent.ACTION_SEND_MULTIPLE) && !shareIntentHandled) {
272− val type = intent.type.orEmpty()
273− if (action == Intent.ACTION_SEND && type.startsWith("image/")) {
274− // A single shared image → stage as an attachment in the next opened session.
275− val uri = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)
276− if (uri != null) {
277− container.setPendingSharedMedia(listOf(uri.toString()))
278− shareIntentHandled = true
279− }
280− } else if (action == Intent.ACTION_SEND_MULTIPLE && type.startsWith("image/")) {
281− val uris = IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)
282− ?.take(NetworkConfig.maxAttachments)
283− .orEmpty()
284− if (uris.isNotEmpty()) {
285− container.setPendingSharedMedia(uris.map { it.toString() })
286− shareIntentHandled = true
287− }
288− } else if (action == Intent.ACTION_SEND) {
289− // A non-image file (e.g. a PDF or text file shared from another app): stage it
290− // as an attachment too, so the user can send it to the agent. The attachment
291− // pipeline handles non-image mimes with a generic file icon. Falls back to
292− // EXTRA_TEXT when no stream is present (a plain text share).
293− val uri = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)
294− if (uri != null) {
295− container.setPendingSharedMedia(listOf(uri.toString()))
296− shareIntentHandled = true
297− } else {
298− val text = intent.getStringExtra(Intent.EXTRA_TEXT)
299− ?.takeIf { it.isNotBlank() }
300− ?.take(10_000) // cap to prevent unbounded memory usage from malicious shares
301− if (text != null) {
302− container.setPendingShare(text)
303− shareIntentHandled = true
304− }
305− }
306− } else {
307− val text = intent.getStringExtra(Intent.EXTRA_TEXT)
308− ?.takeIf { it.isNotBlank() }
309− ?.take(10_000) // cap to prevent unbounded memory usage from malicious shares
310− if (text != null) {
311− container.setPendingShare(text)
312− shareIntentHandled = true
313− }
314− }
315− }
316− // Deep links under the opencode:// scheme. The manifest exposes several hosts:
317− // session/{id} → open (and switch to) that conversation
318− // file/{path} → open the file viewer at that workspace path
319− // new → start a fresh session
320− // The file path is percent-encoded by the link source; decode it here and validate the
321− // segment to keep path-traversal out of the REST path (mirroring the session guard).
322− val data = intent?.takeIf { it.action == Intent.ACTION_VIEW }?.data
323− when (data?.host) {
324− "session" -> {
325− val seg = data.lastPathSegment
326− if (!openSessionHandled) {
327− seg?.takeIf { it.isNotBlank() && it.matches(VALID_SESSION_ID) }?.let {
328− val profileId = intent.getStringExtra(NotificationActionReceiver.EXTRA_PROFILE_ID)
329− ?.takeIf { it.isNotBlank() }
330− container.requestOpenSession(it, profileId)
331− openSessionHandled = true
332− } ?: run {
333− // The link carried a session host but no valid id (or a blank/traversal
334− // attempt). Surface a toast so the user knows the link was rejected,
335− // rather than silently no-op'ing (which reads as "the app did nothing").
336− if (!seg.isNullOrBlank()) showInvalidLinkToast = true
337− // Mark the link handled even on rejection, so a process-death-and-restore
338− // (which re-delivers the same intent) doesn't re-fire the toast on every
339− // restore — the rejection is final, not a transient state to retry.
340− openSessionHandled = true
341− }
342− }
343− }
344− "file" -> {
345− // Reconstruct the path from the path segments after "file", preserving internal
346− // slashes. Decoded + validated against traversal/control characters.
347− val rawPath = data.path?.removePrefix("/file/")?.let { android.net.Uri.decode(it) }
348− if (!openFileHandled) {
349− rawPath?.takeIf { isValidFilePath(it) }
350− ?.let { container.requestOpenFile(it); openFileHandled = true } ?: run {
351− if (!rawPath.isNullOrBlank()) showInvalidLinkToast = true
352− // Mark handled on rejection too, mirroring the session branch —
353− // otherwise a process-death restore re-fires the invalid-link toast.
354− openFileHandled = true
355− }
356− }
357− }
358− "new" -> {
359− if (!newSessionHandled) {
360− container.requestNewSession()
361− newSessionHandled = true
362− }
363− }
364− }
365− // Fall back to the EXTRA_SESSION_ID extra (notifications / widget) when no deep link
366− // was present at all. A deep link that matched a host but failed validation (e.g. a
367− // malformed session id) does NOT fall through to the extra: the intent's primary
368− // routing signal was the URI, and the extra may carry a different (valid) id that
369− // would silently open the wrong session. Only when data?.host is null (a pure widget
370− // / notification intent with no URI) does the extra carry the routing intent.
371− if (data?.host == null && !openSessionHandled) {
372− intent?.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() && it.matches(VALID_SESSION_ID) }?.let {
373− val profileId = intent.getStringExtra(NotificationActionReceiver.EXTRA_PROFILE_ID)
374− ?.takeIf { it.isNotBlank() }
375− container.requestOpenSession(it, profileId)
376− openSessionHandled = true
377− }
378− }
379− }
380−
381− companion object {
382− /** Intent extra carrying a session id to open (notifications / deep links / widget). */
383− const val EXTRA_SESSION_ID = "soy.iko.opencode.extra.SESSION_ID"
384−
385− /** Action for the "New session" launcher shortcut and quick-settings tile. */
386− const val ACTION_NEW_SESSION = "soy.iko.opencode.action.NEW_SESSION"
387−
388− /** Session ids are alphanumeric with dashes/underscores. Reject path traversal. */
389− private val VALID_SESSION_ID = Regex("[A-Za-z0-9_-]+")
390−
391− /** A file path must not carry traversal segments or control characters. Looser than a
392− * positive allowlist: real workspace paths commonly contain `~`, `:`, `+`, `=`, `,`,
393− * parentheses, and non-ASCII unicode, all of which a tight `[A-Za-z0-9_\\-./ ]+`
394− * regex would reject. The server validates the path against the workspace root, so
395− * here we only reject what's unambiguously hostile (traversal) or non-printable. */
396− private fun isValidFilePath(path: String): Boolean {
397− if (path.isBlank()) return false
398− if (path.contains("..")) return false
399− if (path.any { it.isISOControl() }) return false
400− return true
401− }
402−
403− private const val KEY_SHARE_HANDLED = "shareIntentHandled"
404− private const val KEY_OPEN_SESSION_HANDLED = "openSessionHandled"
405− private const val KEY_NEW_SESSION_HANDLED = "newSessionHandled"
406− private const val KEY_OPEN_FILE_HANDLED = "openFileHandled"
407− private const val KEY_NOTIF_PERM_REQUESTED = "notificationPermissionRequested"
408− }
409−
410− override fun onSaveInstanceState(outState: Bundle) {
411− super.onSaveInstanceState(outState)
412− val container = (application as OpencodeApp).container
413− // Persist each intent-handled flag as "consumed", not merely "dispatched". The pending
414− // signals live only in the in-memory AppContainer, which is recreated EMPTY on process
415− // death. Persisting a plain "dispatched = true" would, after a kill *before* the UI
416− // consumed the signal, restore the flag as true so the fresh container never receives it —
417− // the deep-linked / new / shared session would silently never open. So AND each flag with
418− // "the container no longer holds the signal": still-pending at save time → persist false so
419− // the re-delivered intent re-dispatches it into the new container on restore; already
420− // consumed → persist true so we don't re-open it unexpectedly on every later restore.
421− val openConsumed = container.pendingOpenSession.value == null
422− val newConsumed = container.pendingNewSession.value == 0
423− val shareConsumed = container.pendingShare.value == null && container.pendingSharedMedia.value.isEmpty()
424− val fileConsumed = container.pendingOpenFile.value == null
425− outState.putBoolean(KEY_SHARE_HANDLED, shareIntentHandled && shareConsumed)
426− outState.putBoolean(KEY_OPEN_SESSION_HANDLED, openSessionHandled && openConsumed)
427− outState.putBoolean(KEY_NEW_SESSION_HANDLED, newSessionHandled && newConsumed)
428− outState.putBoolean(KEY_OPEN_FILE_HANDLED, openFileHandled && fileConsumed)
429− outState.putBoolean(KEY_NOTIF_PERM_REQUESTED, notificationPermissionRequested)
430− }
431−
432− /** Ask for POST_NOTIFICATIONS on Android 13+ so run/completion notifications show.
433− * Idempotent per Activity instance via [notificationPermissionRequested].
434− * Shows a rationale dialog first (explaining what the user gains) before the system
435− * permission prompt, so a user who denies understands what they're missing. */
436− private fun maybeRequestNotificationPermission() {
437− if (notificationPermissionRequested) return
438− if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
439− val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
440− PackageManager.PERMISSION_GRANTED
441− if (!granted) {
442− notificationPermissionRequested = true
443− showNotificationRationaleDialog()
444− }
445− }
446−
447− private fun showNotificationRationaleDialog() {
448− showNotifRationale = true
449− }
450}
31}
app/src/main/java/soy/iko/opencode/OpencodeApp.ktdeleted−130
@@ -1,130 +0,0 @@
1−package soy.iko.opencode
2−
3−import android.app.Application
4−import android.content.Context
5−import coil3.ImageLoader
6−import coil3.SingletonImageLoader
7−import coil3.disk.DiskCache
8−import coil3.memory.MemoryCache
9−import coil3.network.okhttp.OkHttpNetworkFetcherFactory
10−import okhttp3.Call
11−import okhttp3.CertificatePinner
12−import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
13−import okhttp3.OkHttpClient
14−import okhttp3.Request
15−import okio.Path.Companion.toOkioPath
16−import soy.iko.opencode.data.model.ServerProfile
17−import soy.iko.opencode.data.network.CertPinUtil
18−import soy.iko.opencode.data.repo.CrashLogger
19−import soy.iko.opencode.di.AppContainer
20−import java.util.concurrent.atomic.AtomicBoolean
21−
22−class OpencodeApp : Application(), SingletonImageLoader.Factory {
23− lateinit var container: AppContainer
24− private set
25−
26− private val shutdownCalled = AtomicBoolean(false)
27−
28− override fun onCreate() {
29− super.onCreate()
30− CrashLogger.get(this).install()
31− container = AppContainer(this)
32− // onTerminate() is only called in emulated process environments, not on real
33− // devices. Register a JVM shutdown hook so cleanup (network callback unregister,
34− // scope cancellation, connection close) runs when the process is actually killed.
35− Runtime.getRuntime().addShutdownHook(Thread {
36− shutdown()
37− })
38− }
39−
40− // Process-wide Coil singleton. The defaults are sane; the explicit factory adds a
41− // disk cache so scrolling back to an image-bearing message doesn't re-fetch it over
42− // the (auth-protected) network every time. Data-URI (base64) images skip the disk
43− // cache automatically; only resolved HTTP/S URLs are cached, keyed by URL.
44− //
45− // Route fetches through a Call.Factory that applies the SAME per-profile certificate
46− // pinning as the REST/SSE client (see HttpClientFactory). Server-hosted images carry the
47− // server's HTTP Basic auth header (see RemoteImage), so without this they would travel over
48− // an UNPINNED TLS connection, silently defeating the pin the user opted into for that host.
49− override fun newImageLoader(context: Context): ImageLoader = ImageLoader.Builder(context)
50− .memoryCache {
51− MemoryCache.Builder()
52− .maxSizePercent(context, 0.25)
53− .build()
54− }
55− .diskCache {
56− DiskCache.Builder()
57− .directory(cacheDir.resolve("image_cache").toOkioPath())
58− .maxSizeBytes(50L * 1024 * 1024)
59− .build()
60− }
61− .components {
62− // Route fetches through a Call.Factory that applies the SAME per-profile certificate
63− // pinning as the REST/SSE client (see HttpClientFactory). Server-hosted images carry
64− // the server's HTTP Basic auth header (see RemoteImage), so without this they would
65− // travel over an UNPINNED TLS connection, silently defeating the pin the user opted
66− // into for that host.
67− add(OkHttpNetworkFetcherFactory(callFactory = { PinnedImageCallFactory(container) }))
68− }
69− .build()
70−
71− override fun onTerminate() {
72− super.onTerminate()
73− shutdown()
74− }
75−
76− private fun shutdown() {
77− // Guard against double shutdown — onTerminate and the shutdown hook can both
78− // fire in emulated environments.
79− if (!shutdownCalled.compareAndSet(false, true)) return
80− container.shutdown()
81− }
82−}
83−
84−/**
85− * A Coil [Call.Factory] that pins image loads exactly like [HttpClientFactory] pins the
86− * REST/SSE channel. The [ImageLoader] is a process singleton built once, but the active
87− * [ServerProfile] — and therefore its pins — changes when the user switches servers, so the
88− * certificate pinner is resolved *per request* from [AppContainer.activeConnection] rather than
89− * baked in at build time. This fails closed: a profile that configures pins always gets a pinned
90− * connection for its images (an unparseable pinned host throws, matching HttpClientFactory), so
91− * image loads for a pinned host are never silently downgraded to an unpinned channel — and a
92− * later server switch is picked up immediately instead of retaining the first profile's pins.
93− */
94−private class PinnedImageCallFactory(private val container: AppContainer) : Call.Factory {
95− // A single shared base client; each derived pinned client reuses this one's connection pool
96− // and dispatcher via newBuilder(), so per-profile pinning doesn't spin up parallel resources.
97− private val base = OkHttpClient()
98−
99− // Cache the last derived client keyed by (host, pins) so we don't rebuild it on every request;
100− // a server switch changes the signature and triggers a rebuild. Guarded because Coil invokes
101− // newCall from arbitrary background threads, possibly concurrently.
102− private val lock = Any()
103− private var cachedSignature: String? = null
104− private var cachedClient: OkHttpClient = base
105−
106− override fun newCall(request: Request): Call =
107− clientFor(container.activeConnection.value?.profile).newCall(request)
108−
109− private fun clientFor(profile: ServerProfile?): OkHttpClient {
110− val pins = CertPinUtil.parseCertPins(profile?.certPin)
111− if (pins.isEmpty()) return base
112− // effectiveBaseUrl upgrades http->https when pinning is on, so the pinned host matches the
113− // https origin RemoteImage resolves image URLs against. Fail closed on an unparseable host
114− // (never fall back to an unpinned client), mirroring HttpClientFactory.create().
115− val effectiveUrl = CertPinUtil.effectiveBaseUrl(profile!!)
116− val host = effectiveUrl.toHttpUrlOrNull()?.host
117− ?: throw IllegalStateException(
118− "Certificate pinning is configured but the server host could not be parsed from $effectiveUrl",
119− )
120− val signature = "$host\n${pins.sorted().joinToString(" ")}"
121− synchronized(lock) {
122− if (signature != cachedSignature) {
123− val pinner = CertificatePinner.Builder().apply { pins.forEach { add(host, it) } }.build()
124− cachedClient = base.newBuilder().certificatePinner(pinner).build()
125− cachedSignature = signature
126− }
127− return cachedClient
128− }
129− }
130−}
app/src/main/java/soy/iko/opencode/core/HttpClient.ktnew file+75
@@ -0,0 +1,75 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.coroutines.Dispatchers
4+import kotlinx.coroutines.suspendCancellableCoroutine
5+import kotlinx.coroutines.withContext
6+import okhttp3.Call
7+import okhttp3.Callback
8+import okhttp3.MediaType.Companion.toMediaType
9+import okhttp3.OkHttpClient
10+import okhttp3.Request
11+import okhttp3.RequestBody.Companion.toRequestBody
12+import okhttp3.Response
13+import java.io.IOException
14+import java.util.concurrent.TimeUnit
15+import kotlin.coroutines.resume
16+import kotlin.coroutines.resumeWithException
17+
18+/** A completed HTTP response (any status code — non-2xx is not an error here). */
19+data class HttpResp(val code: Int, val body: String)
20+
21+/**
22+ * Thin OkHttp wrapper for the opencode REST calls. Transport failures surface as
23+ * [Result.failure]; every actual HTTP response (including 4xx/5xx) is a success
24+ * carrying its status code, matching the Rust core's `HttpResult` handling.
25+ */
26+class HttpClient(
27+ val okhttp: OkHttpClient = OkHttpClient.Builder()
28+ .connectTimeout(15, TimeUnit.SECONDS)
29+ .readTimeout(30, TimeUnit.SECONDS)
30+ .build(),
31+) {
32+ private val jsonMedia = "application/json".toMediaType()
33+
34+ suspend fun get(url: String, auth: String?): Result<HttpResp> =
35+ exec(url, auth) { get() }
36+
37+ suspend fun postJson(url: String, body: String, auth: String?): Result<HttpResp> =
38+ exec(url, auth) { post(body.toRequestBody(jsonMedia)) }
39+
40+ suspend fun delete(url: String, auth: String?): Result<HttpResp> =
41+ exec(url, auth) { delete() }
42+
43+ // Build and run the request off the main thread. Building it — parsing [url]
44+ // in particular — can throw (e.g. a URL with no scheme), so that happens
45+ // inside [runCatching] too: a bad URL then surfaces as [Result.failure]
46+ // instead of crashing the caller's coroutine.
47+ private suspend fun exec(
48+ url: String,
49+ auth: String?,
50+ method: Request.Builder.() -> Request.Builder,
51+ ): Result<HttpResp> = withContext(Dispatchers.IO) {
52+ runCatching {
53+ val builder = Request.Builder().url(url).method()
54+ builder.header("User-Agent", "opencode-android/1.0")
55+ if (auth != null) builder.header("Authorization", auth)
56+ await(okhttp.newCall(builder.build()))
57+ }
58+ }
59+
60+ private suspend fun await(call: Call): HttpResp = suspendCancellableCoroutine { cont ->
61+ cont.invokeOnCancellation { runCatching { call.cancel() } }
62+ call.enqueue(object : Callback {
63+ override fun onFailure(call: Call, e: IOException) {
64+ if (cont.isActive) cont.resumeWithException(e)
65+ }
66+
67+ override fun onResponse(call: Call, response: Response) {
68+ response.use {
69+ val body = runCatching { it.body?.string() }.getOrNull().orEmpty()
70+ if (cont.isActive) cont.resume(HttpResp(it.code, body))
71+ }
72+ }
73+ })
74+ }
75+}
app/src/main/java/soy/iko/opencode/core/OpencodeCore.ktnew file+668
@@ -0,0 +1,668 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.coroutines.CoroutineScope
4+import kotlinx.coroutines.Job
5+import kotlinx.coroutines.delay
6+import kotlinx.coroutines.flow.MutableStateFlow
7+import kotlinx.coroutines.flow.StateFlow
8+import kotlinx.coroutines.flow.asStateFlow
9+import kotlinx.coroutines.launch
10+import java.util.Base64
11+
12+/**
13+ * The application core: a Kotlin port of the Rust Crux core (`shared/`).
14+ *
15+ * It owns all state, turns [Event]s into state changes + effects, and exposes an
16+ * observable [view]. Effects are executed here in the shell: REST calls through
17+ * [HttpClient] and the long-lived `/event` stream through [SseClient]. Every
18+ * server-sent event is fed back in and applied incrementally, so assistant
19+ * replies stream in token-by-token.
20+ *
21+ * All state mutation happens on [scope]'s (main) dispatcher; only the blocking
22+ * network I/O hops to a background thread inside the clients.
23+ */
24+class OpencodeCore(
25+ private val scope: CoroutineScope,
26+ private val http: HttpClient = HttpClient(),
27+) {
28+ // ── Model ────────────────────────────────────────────────────────────────
29+ private var serverUrl = ""
30+ private var username = ""
31+ private var password = ""
32+ private var authRequired = false
33+ private var connected = false
34+ private var loading = false
35+ private var error: String? = null
36+ private var screen = Screen.Connect
37+ private val sessions = mutableListOf<SessionView>()
38+ private var currentSessionId: String? = null
39+ private var currentSessionTitle = ""
40+ private val messages = mutableListOf<MsgState>()
41+ private var draft = ""
42+ private var generating = false
43+ private var sseConnected = true
44+ private var localSeq = 0L
45+
46+ private val _view = MutableStateFlow(snapshot())
47+ val view: StateFlow<UiState> = _view.asStateFlow()
48+
49+ private var sse: SseClient? = null
50+ private var sseClosedIntentionally = false
51+ private var reconnectAttempts = 0
52+ private var reconnectJob: Job? = null
53+
54+ // Guards against overlapping session refreshes: rapid taps launch multiple
55+ // loadSessions coroutines and the slowest-to-return would otherwise win.
56+ private var loadSessionsJob: Job? = null
57+ // Tracks the in-flight createSession coroutine so navigating away can cancel it
58+ // before it dispatches SelectSession into a screen the user already left.
59+ private var createSessionJob: Job? = null
60+ // Tracks the in-flight loadMessages coroutine. Rapidly switching sessions launches
61+ // several; cancel the prior one so only the newest fetch runs (saves needless requests).
62+ private var loadMessagesJob: Job? = null
63+ // Tracks the in-flight probeHealth coroutine. Rapid double-taps on Connect would
64+ // otherwise launch two concurrent health probes; cancel the prior one first.
65+ private var connectJob: Job? = null
66+ // Tracks the in-flight DeleteSession coroutine so navigating away can cancel it
67+ // before its response handler mutates the sessions list / screen the user already left.
68+ private var deleteSessionJob: Job? = null
69+ // Tracks the in-flight sendMessage coroutine so navigating away or switching sessions
70+ // can cancel it before its response handler touches stale message state.
71+ private var sendMessageJob: Job? = null
72+ // Tracks the in-flight abort coroutine (CancelGeneration) so rapid cancel taps don't
73+ // fire multiple abort requests, and navigating away can cancel it.
74+ private var abortJob: Job? = null
75+ // Message IDs removed via SSE; a late MessageUpdated for one must not resurrect it.
76+ private val removedMessageIds = mutableSetOf<String>()
77+
78+ // ── Event entry point ──────────────────────────────────────────────────────
79+ fun dispatch(event: Event) {
80+ when (event) {
81+ // Store the field verbatim while typing; normalizing here would fight
82+ // the user's edits (e.g. eat the "://" as they type it). The URL is
83+ // normalized once, on Connect.
84+ // Clear any prior error as soon as the user edits a field, so a stale
85+ // message (e.g. "Invalid credentials") doesn't linger while they correct it.
86+ is Event.ServerUrlChanged -> { serverUrl = event.url; if (error != null) error = null; emit() }
87+ is Event.UsernameChanged -> { username = event.value; if (error != null) error = null; emit() }
88+ is Event.PasswordChanged -> { password = event.value; if (error != null) error = null; emit() }
89+
90+ Event.Connect -> {
91+ serverUrl = normalizeUrl(serverUrl)
92+ if (serverUrl.isEmpty()) { error = "Enter a server URL"; emit(); return }
93+ // The auth fields are showing but empty — sending the request now
94+ // would just 401 again in a loop. Prompt for credentials instead.
95+ if (authRequired && !hasCredentials()) { error = "Enter username and password"; emit(); return }
96+ // Leave authRequired as-is; probeHealth sets it from the response (true on
97+ // 401, false on success). Resetting it here just flickers the auth fields.
98+ loading = true; error = null; emit()
99+ connectJob?.cancel()
100+ connectJob = scope.launch { probeHealth() }
101+ }
102+
103+ Event.LoadSessions -> {
104+ if (!connected) { error = "Not connected"; emit(); return }
105+ loading = true; emit()
106+ loadSessionsJob?.cancel()
107+ loadSessionsJob = scope.launch { loadSessions() }
108+ }
109+
110+ is Event.SelectSession -> {
111+ // The session may have been deleted (e.g. via SSE) while the list was on
112+ // screen; opening it would only 404 on loadMessages. Bail with an error.
113+ val session = sessions.firstOrNull { it.id == event.id }
114+ if (session == null) { error = "Session no longer exists"; emit(); return }
115+ currentSessionTitle = session.title
116+ currentSessionId = event.id
117+ messages.clear()
118+ removedMessageIds.clear()
119+ screen = Screen.Chat
120+ loading = true
121+ generating = false
122+ error = null
123+ emit()
124+ connectJob?.cancel()
125+ abortJob?.cancel()
126+ sendMessageJob?.cancel()
127+ deleteSessionJob?.cancel()
128+ loadMessagesJob?.cancel()
129+ loadMessagesJob = scope.launch { loadMessages(event.id) }
130+ }
131+
132+ Event.CreateSession -> {
133+ if (!connected) { error = "Not connected"; emit(); return }
134+ loading = true; error = null; emit()
135+ createSessionJob?.cancel()
136+ createSessionJob = scope.launch { createSession() }
137+ }
138+
139+ is Event.DeleteSession -> {
140+ if (!connected) { error = "Not connected"; emit(); return }
141+ val id = event.id
142+ // Delete on the server first; only drop it from the UI once that
143+ // succeeds, so a failed request leaves the session recoverable.
144+ loading = true; error = null; emit()
145+ deleteSessionJob?.cancel()
146+ deleteSessionJob = scope.launch {
147+ http.delete("$serverUrl/session/$id", authHeader()).fold(
148+ onSuccess = { resp ->
149+ if (resp.code in 200..299) {
150+ sessions.removeAll { it.id == id }
151+ if (isCurrent(id)) {
152+ currentSessionId = null
153+ messages.clear()
154+ screen = Screen.Sessions
155+ }
156+ } else {
157+ error = "Failed to delete session"
158+ }
159+ loading = false
160+ },
161+ onFailure = {
162+ error = "Failed to delete session"
163+ loading = false
164+ },
165+ )
166+ emit()
167+ }
168+ }
169+
170+ is Event.DraftChanged -> { draft = event.text; emit() }
171+
172+ is Event.SendMessage -> sendMessage(event.text)
173+
174+ Event.CancelGeneration -> {
175+ generating = false
176+ messages.forEach { it.streaming = false }
177+ emit()
178+ val id = currentSessionId ?: return
179+ // Debounce rapid cancel taps: cancel any in-flight abort before firing
180+ // another so we don't stack duplicate abort requests.
181+ abortJob?.cancel()
182+ abortJob = scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
183+ }
184+
185+ Event.NavigateToSessions -> {
186+ screen = Screen.Sessions
187+ currentSessionId = null
188+ messages.clear()
189+ removedMessageIds.clear()
190+ draft = ""
191+ generating = false
192+ // Clear any error from the chat (e.g. a failed send) so it doesn't
193+ // linger on the sessions list after the user navigates back.
194+ error = null
195+ loading = true
196+ emit()
197+ connectJob?.cancel()
198+ abortJob?.cancel()
199+ createSessionJob?.cancel()
200+ deleteSessionJob?.cancel()
201+ sendMessageJob?.cancel()
202+ loadMessagesJob?.cancel()
203+ loadSessionsJob?.cancel()
204+ loadSessionsJob = scope.launch { loadSessions() }
205+ }
206+
207+ Event.NavigateToConnect -> {
208+ screen = Screen.Connect
209+ connected = false
210+ loading = false
211+ generating = false
212+ sessions.clear()
213+ messages.clear()
214+ removedMessageIds.clear()
215+ currentSessionId = null
216+ draft = ""
217+ // Reset to the default so a late-firing close callback from the old
218+ // SSE connection can't flash the reconnecting banner on the next connect.
219+ sseConnected = true
220+ connectJob?.cancel()
221+ abortJob?.cancel()
222+ createSessionJob?.cancel()
223+ deleteSessionJob?.cancel()
224+ sendMessageJob?.cancel()
225+ loadMessagesJob?.cancel()
226+ closeSse()
227+ emit()
228+ }
229+
230+ Event.DismissError -> { error = null; emit() }
231+ }
232+ }
233+
234+ /** Reconnect the stream on a fresh process (e.g. after rotation) if already connected. */
235+ fun resumeStreamingIfConnected() {
236+ if (connected && sse == null) startSse()
237+ }
238+
239+ fun shutdown() {
240+ // Cancel every tracked coroutine before tearing down the stream so none can
241+ // emit into a cancelled scope after the ViewModel is cleared.
242+ connectJob?.cancel()
243+ loadSessionsJob?.cancel()
244+ createSessionJob?.cancel()
245+ loadMessagesJob?.cancel()
246+ deleteSessionJob?.cancel()
247+ sendMessageJob?.cancel()
248+ abortJob?.cancel()
249+ closeSse()
250+ }
251+
252+ // ── Effects ────────────────────────────────────────────────────────────────
253+ private fun sendMessage(raw: String) {
254+ val text = raw.trim()
255+ val session = currentSessionId ?: return
256+ if (text.isEmpty()) return
257+ // Debounce rapid double-taps on send: a send is already in flight, so a second
258+ // tap would create a duplicate user message and fire a duplicate request.
259+ if (generating) return
260+ localSeq += 1
261+ val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
262+ status = MessageStatus.Pending
263+ textParts["local"] = text
264+ }
265+ messages.add(user)
266+ // Keep the draft text so we can restore it if the send fails; otherwise the
267+ // user's message is lost and they'd have to retype it.
268+ val savedDraft = draft
269+ draft = ""
270+ generating = true
271+ error = null
272+ emit()
273+
274+ val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
275+ sendMessageJob?.cancel()
276+ sendMessageJob = scope.launch {
277+ val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
278+ result.fold(
279+ onSuccess = { resp ->
280+ if (resp.code in 200..299) {
281+ messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Sent
282+ } else {
283+ messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
284+ generating = false
285+ messages.forEach { it.streaming = false }
286+ draft = savedDraft
287+ error = "Server returned status ${resp.code}"
288+ }
289+ },
290+ onFailure = { e ->
291+ messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
292+ generating = false
293+ messages.forEach { it.streaming = false }
294+ draft = savedDraft
295+ error = "Request failed: ${e.message}"
296+ },
297+ )
298+ emit()
299+ }
300+ }
301+
302+ private suspend fun probeHealth() {
303+ val hasCreds = hasCredentials()
304+ http.get("$serverUrl/global/health", authHeader()).fold(
305+ onSuccess = { resp ->
306+ when {
307+ resp.code == 401 -> {
308+ loading = false
309+ // A prior connection may have succeeded (connected = true); a
310+ // re-probe returning 401 (e.g. expired credentials) means we're
311+ // no longer authenticated, so drop the connected flag.
312+ connected = false
313+ // Always reveal the auth fields so the user can see/edit
314+ // their credentials — even when the ones supplied were wrong.
315+ authRequired = true
316+ if (hasCreds) error = "Invalid credentials"
317+ emit()
318+ }
319+ resp.code in 200..299 -> {
320+ connected = true
321+ authRequired = false
322+ error = null
323+ screen = Screen.Sessions
324+ loading = true
325+ emit()
326+ startSse()
327+ // Route through loadSessionsJob so a prior in-flight loadSessions
328+ // (e.g. from a rapid double-connect) is cancelled first.
329+ loadSessionsJob?.cancel()
330+ loadSessionsJob = scope.launch { loadSessions() }
331+ }
332+ else -> {
333+ loading = false
334+ connected = false
335+ error = "Server returned status ${resp.code}"
336+ emit()
337+ }
338+ }
339+ },
340+ onFailure = { e ->
341+ loading = false
342+ connected = false
343+ error = "Connection failed: ${e.message}"
344+ emit()
345+ },
346+ )
347+ }
348+
349+ private suspend fun loadSessions() {
350+ http.get("$serverUrl/session", authHeader()).fold(
351+ onSuccess = { resp ->
352+ if (resp.code in 200..299) {
353+ sessions.clear()
354+ sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
355+ // Impose a stable alphabetical order so the list doesn't shuffle with
356+ // whatever order the server happens to return sessions in.
357+ sessions.sortBy { it.title.lowercase() }
358+ } else {
359+ error = "Server returned status ${resp.code}"
360+ }
361+ },
362+ onFailure = { e -> error = "Request failed: ${e.message}" },
363+ )
364+ loading = false
365+ emit()
366+ }
367+
368+ private suspend fun createSession() {
369+ http.postJson("$serverUrl/session", "{}", authHeader()).fold(
370+ onSuccess = { resp ->
371+ val session = if (resp.code in 200..299) Protocol.parseSession(resp.body) else null
372+ if (session != null) {
373+ if (sessions.none { it.id == session.id }) {
374+ sessions.add(0, SessionView(session.id, displayTitle(session.title)))
375+ // Restore the alphabetical order immediately (matching loadSessions /
376+ // SessionUpserted) so the new session doesn't sit out-of-order at the
377+ // top until the SSE SessionUpserted event arrives to re-sort.
378+ sessions.sortBy { it.title.lowercase() }
379+ }
380+ emit()
381+ // SelectSession takes over the loading state (loads messages).
382+ dispatch(Event.SelectSession(session.id))
383+ return
384+ }
385+ error = "Server returned status ${resp.code}"
386+ },
387+ onFailure = { e -> error = "Request failed: ${e.message}" },
388+ )
389+ loading = false
390+ emit()
391+ }
392+
393+ private suspend fun loadMessages(sessionId: String) {
394+ http.get("$serverUrl/session/$sessionId/message", authHeader()).fold(
395+ onSuccess = { resp ->
396+ if (!isCurrent(sessionId)) { loading = false; return } // user navigated away while loading
397+ loading = false
398+ if (resp.code in 200..299) {
399+ messages.clear()
400+ removedMessageIds.clear()
401+ messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
402+ generating = messages.any { it.streaming }
403+ } else {
404+ error = "Server returned status ${resp.code}"
405+ }
406+ emit()
407+ },
408+ onFailure = { e ->
409+ if (!isCurrent(sessionId)) { loading = false; return }
410+ loading = false
411+ generating = false
412+ error = "Request failed: ${e.message}"
413+ emit()
414+ },
415+ )
416+ }
417+
418+ // ── SSE ─────────────────────────────────────────────────────────────────────
419+ private fun startSse() {
420+ closeSse()
421+ sseClosedIntentionally = false
422+ val client = SseClient(
423+ url = "$serverUrl/event",
424+ auth = authHeader(),
425+ onEvent = { json -> scope.launch { handleServerEvent(json) } },
426+ onStateChange = { open ->
427+ scope.launch {
428+ sseConnected = open
429+ if (open) reconnectAttempts = 0 else scheduleReconnect()
430+ emit()
431+ }
432+ },
433+ )
434+ sse = client
435+ client.connect()
436+ }
437+
438+ private fun closeSse() {
439+ sseClosedIntentionally = true
440+ reconnectJob?.cancel()
441+ reconnectJob = null
442+ sse?.close()
443+ sse = null
444+ }
445+
446+ private fun scheduleReconnect() {
447+ if (sseClosedIntentionally || !connected) return
448+ // Exponential backoff: 2s, 4s, 8s, 16s, capped at 30s. Reset to 0 once the
449+ // stream reconnects (onStateChange(true)) so a healthy server starts fresh.
450+ val delayMs = (2000L * (1L shl reconnectAttempts)).coerceAtMost(30_000L)
451+ if (delayMs < 30_000L) reconnectAttempts += 1
452+ // Cancel any pending reconnect so rapid network flapping can't stack multiple
453+ // coroutines that each open a new SSE connection.
454+ reconnectJob?.cancel()
455+ reconnectJob = scope.launch {
456+ delay(delayMs)
457+ if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
458+ }
459+ }
460+
461+ private fun handleServerEvent(json: String) {
462+ val event = Protocol.parseEvent(json) ?: return
463+ // Only re-render if the event actually changed our state; applyEvent returns
464+ // false for events that don't apply (other session, unknown message, …).
465+ if (applyEvent(event)) emit()
466+ }
467+
468+ /** Apply a server event to the model. Returns true iff any state actually changed. */
469+ private fun applyEvent(event: Protocol.Event): Boolean {
470+ when (event) {
471+ is Protocol.Event.MessageUpdated -> {
472+ val info = event.info
473+ if (info.role != "assistant" || !isCurrent(info.sessionId)) return false
474+ // A MessageRemoved may have arrived before this (late/out-of-order) update;
475+ // don't re-create a message the server has already deleted.
476+ if (info.id in removedMessageIds) return false
477+ val streaming = info.time.completed == null && info.error == null
478+ val existing = messages.firstOrNull { it.id == info.id }
479+ if (existing != null) {
480+ existing.streaming = streaming
481+ if (existing.time == 0L) existing.time = info.time.created
482+ } else {
483+ messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
484+ }
485+ info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
486+ return true
487+ }
488+
489+ is Protocol.Event.PartUpdated -> {
490+ val part = event.part
491+ val msg = messages.firstOrNull { it.id == part.messageId } ?: return false
492+ // Synthetic text parts are intentionally skipped; report no change so we
493+ // don't trigger a needless re-render/emit for them.
494+ return when (part) {
495+ is Protocol.Part.Text -> if (part.synthetic) {
496+ false
497+ } else {
498+ msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
499+ true
500+ }
501+ is Protocol.Part.Reasoning -> {
502+ msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
503+ true
504+ }
505+ is Protocol.Part.Tool -> {
506+ msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
507+ true
508+ }
509+ }
510+ }
511+
512+ is Protocol.Event.PartRemoved -> {
513+ val msg = messages.firstOrNull { it.id == event.messageId } ?: return false
514+ msg.remove(event.partId)
515+ return true
516+ }
517+
518+ is Protocol.Event.MessageRemoved -> {
519+ // Remember the ID so a late MessageUpdated can't resurrect the message.
520+ removedMessageIds.add(event.messageId)
521+ return messages.removeAll { it.id == event.messageId }
522+ }
523+
524+ is Protocol.Event.SessionIdle -> {
525+ if (!isCurrent(event.sessionId)) return false
526+ generating = false
527+ messages.forEach { it.streaming = false }
528+ return true
529+ }
530+
531+ is Protocol.Event.SessionError -> {
532+ val scoped = event.sessionId == null || isCurrent(event.sessionId)
533+ if (!scoped) return false
534+ event.error?.let { error = it.message() }
535+ generating = false
536+ messages.forEach { it.streaming = false }
537+ return true
538+ }
539+
540+ is Protocol.Event.SessionUpserted -> {
541+ val title = displayTitle(event.info.title)
542+ val existing = sessions.firstOrNull { it.id == event.info.id }
543+ if (existing != null) {
544+ sessions[sessions.indexOf(existing)] = SessionView(event.info.id, title)
545+ } else {
546+ sessions.add(0, SessionView(event.info.id, title))
547+ }
548+ // Keep the list alphabetically sorted (matching loadSessions) so an
549+ // upserted session doesn't jump to the top and break the ordering.
550+ sessions.sortBy { it.title.lowercase() }
551+ if (isCurrent(event.info.id)) currentSessionTitle = title
552+ return true
553+ }
554+
555+ is Protocol.Event.SessionDeleted -> {
556+ val id = event.sessionId ?: return false
557+ val removed = sessions.removeAll { it.id == id }
558+ if (isCurrent(id)) {
559+ currentSessionId = null
560+ messages.clear()
561+ screen = Screen.Sessions
562+ return true
563+ }
564+ return removed
565+ }
566+
567+ Protocol.Event.Other -> return false
568+ }
569+ }
570+
571+ // ── View / helpers ──────────────────────────────────────────────────────────
572+ private fun snapshot() = UiState(
573+ screen = screen,
574+ serverUrl = serverUrl,
575+ username = username,
576+ password = password,
577+ authRequired = authRequired,
578+ connected = connected,
579+ loading = loading,
580+ error = error,
581+ sessions = sessions.toList(),
582+ currentSessionId = currentSessionId,
583+ currentSessionTitle = currentSessionTitle,
584+ messages = messages.map { it.toView() },
585+ draft = draft,
586+ generating = generating,
587+ sseConnected = sseConnected,
588+ )
589+
590+ private fun emit() { _view.value = snapshot() }
591+
592+ private fun isCurrent(sessionId: String?) = sessionId != null && currentSessionId == sessionId
593+ private fun hasCredentials() = username.isNotEmpty() || password.isNotEmpty()
594+
595+ private fun authHeader(): String? {
596+ if (!hasCredentials()) return null
597+ val encoded = Base64.getEncoder().encodeToString("$username:$password".toByteArray())
598+ return "Basic $encoded"
599+ }
600+}
601+
602+// ── Internal message state (parts tracked by id for streaming) ─────────────────
603+private class MsgState(val id: String, val role: String, var time: Long) {
604+ var status = MessageStatus.Sent
605+ var streaming = false
606+ val textParts = LinkedHashMap<String, String>()
607+ val reasoningParts = LinkedHashMap<String, String>()
608+ val toolParts = LinkedHashMap<String, ToolView>()
609+
610+ fun remove(partId: String) {
611+ textParts.remove(partId)
612+ reasoningParts.remove(partId)
613+ toolParts.remove(partId)
614+ }
615+
616+ fun toView(): MessageView {
617+ val reasoning = reasoningParts.values.joinToString("")
618+ return MessageView(
619+ id = id,
620+ role = role,
621+ text = textParts.values.joinToString(""),
622+ reasoning = reasoning.ifEmpty { null },
623+ tools = toolParts.values.toList(),
624+ time = time,
625+ status = status,
626+ streaming = streaming,
627+ )
628+ }
629+}
630+
631+private fun messageFromWire(env: Protocol.WireMessageEnvelope): MsgState {
632+ val info = env.info
633+ val msg = MsgState(info.id, info.role, info.time.created)
634+ msg.streaming = info.role == "assistant" && info.time.completed == null && info.error == null
635+ for (raw in env.parts) {
636+ val obj = (raw as? kotlinx.serialization.json.JsonObject) ?: continue
637+ when (val part = Protocol.parsePart(obj)) {
638+ is Protocol.Part.Text -> if (!part.synthetic) msg.textParts[part.id] = part.text
639+ is Protocol.Part.Reasoning -> msg.reasoningParts[part.id] = part.text
640+ is Protocol.Part.Tool -> msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
641+ null -> Unit
642+ }
643+ }
644+ return msg
645+}
646+
647+private fun pickText(text: String, delta: String?, prior: String?): String =
648+ if (text.isNotEmpty()) text else (prior.orEmpty() + (delta ?: ""))
649+
650+private fun normalizeUrl(url: String): String {
651+ val trimmed = url.trim().trimEnd('/')
652+ // Default to http:// when the user didn't type a scheme (e.g. "192.168.1.10:4096").
653+ // Without a scheme OkHttp's URL parser throws and the connect attempt crashes.
654+ return when {
655+ trimmed.isEmpty() -> ""
656+ "://" in trimmed -> trimmed
657+ else -> "http://$trimmed"
658+ }
659+}
660+
661+private fun displayTitle(title: String): String = title.trim().ifEmpty { "Untitled" }
662+
663+// ── Prompt request body (POST /session/{id}/prompt_async) ──────────────────────
664+@kotlinx.serialization.Serializable
665+private data class PromptBody(val parts: List<TextInput>)
666+
667+@kotlinx.serialization.Serializable
668+private data class TextInput(val type: String = "text", val text: String)
app/src/main/java/soy/iko/opencode/core/Protocol.ktnew file+148
@@ -0,0 +1,148 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.serialization.SerialName
4+import kotlinx.serialization.Serializable
5+import kotlinx.serialization.json.Json
6+import kotlinx.serialization.json.JsonElement
7+import kotlinx.serialization.json.JsonObject
8+import kotlinx.serialization.json.JsonPrimitive
9+import kotlinx.serialization.json.booleanOrNull
10+import kotlinx.serialization.json.contentOrNull
11+import kotlinx.serialization.json.decodeFromJsonElement
12+import kotlinx.serialization.json.jsonObject
13+
14+/**
15+ * Wire types for the opencode HTTP + SSE API, and lenient parsers for them.
16+ *
17+ * This is the Kotlin counterpart of the Rust core's `protocol.rs`. It is
18+ * deliberately forgiving: unknown JSON fields are ignored and every union has a
19+ * catch-all so new server versions never break the stream parser.
20+ */
21+object Protocol {
22+ val json = Json {
23+ ignoreUnknownKeys = true
24+ isLenient = true
25+ coerceInputValues = true
26+ }
27+
28+ // ─── Sessions ────────────────────────────────────────────────────────────
29+
30+ @Serializable
31+ data class WireSession(val id: String, val title: String = "")
32+
33+ fun parseSessions(body: String): List<WireSession> =
34+ runCatching { json.decodeFromString<List<WireSession>>(body) }.getOrDefault(emptyList())
35+
36+ fun parseSession(body: String): WireSession? =
37+ runCatching { json.decodeFromString<WireSession>(body) }.getOrNull()
38+
39+ // ─── Messages ────────────────────────────────────────────────────────────
40+
41+ @Serializable
42+ data class WireTime(val created: Long = 0, val completed: Long? = null)
43+
44+ @Serializable
45+ data class WireError(val name: String = "", val data: JsonElement? = null) {
46+ fun message(): String {
47+ val msg = ((data as? JsonObject)?.get("message") as? JsonPrimitive)?.contentOrNull
48+ return when {
49+ !msg.isNullOrEmpty() -> msg
50+ name.isNotEmpty() -> name
51+ else -> "Unknown error"
52+ }
53+ }
54+ }
55+
56+ @Serializable
57+ data class WireMessageInfo(
58+ val id: String,
59+ val role: String = "",
60+ @SerialName("sessionID") val sessionId: String = "",
61+ val time: WireTime = WireTime(),
62+ val error: WireError? = null,
63+ )
64+
65+ @Serializable
66+ data class WireMessageEnvelope(
67+ val info: WireMessageInfo,
68+ val parts: List<JsonElement> = emptyList(),
69+ )
70+
71+ fun parseMessages(body: String): List<WireMessageEnvelope> =
72+ runCatching { json.decodeFromString<List<WireMessageEnvelope>>(body) }.getOrDefault(emptyList())
73+
74+ // ─── Parts (content union, parsed by hand for robustness) ─────────────────
75+
76+ sealed interface Part {
77+ val id: String
78+ val messageId: String
79+
80+ data class Text(override val id: String, override val messageId: String, val text: String, val synthetic: Boolean) : Part
81+ data class Reasoning(override val id: String, override val messageId: String, val text: String) : Part
82+ data class Tool(override val id: String, override val messageId: String, val tool: String, val status: String, val title: String?) : Part
83+ }
84+
85+ /** Parse a single part JSON object; returns null for kinds we don't render. */
86+ fun parsePart(obj: JsonObject): Part? {
87+ val id = obj.str("id")
88+ val messageId = obj.str("messageID")
89+ return when (obj.str("type")) {
90+ "text" -> Part.Text(id, messageId, obj.str("text"), obj.bool("synthetic"))
91+ "reasoning" -> Part.Reasoning(id, messageId, obj.str("text"))
92+ "tool" -> {
93+ val state = obj["state"] as? JsonObject
94+ val status = state?.str("status")?.ifEmpty { "pending" } ?: "pending"
95+ val title = state?.str("title")?.ifEmpty { null } ?: state?.str("error")?.ifEmpty { null }
96+ Part.Tool(id, messageId, obj.str("tool"), status, title)
97+ }
98+ else -> null
99+ }
100+ }
101+
102+ // ─── SSE `/event` stream ──────────────────────────────────────────────────
103+
104+ sealed interface Event {
105+ data class MessageUpdated(val info: WireMessageInfo) : Event
106+ data class PartUpdated(val part: Part, val delta: String?) : Event
107+ data class PartRemoved(val messageId: String, val partId: String) : Event
108+ data class MessageRemoved(val messageId: String) : Event
109+ data class SessionIdle(val sessionId: String) : Event
110+ data class SessionError(val sessionId: String?, val error: WireError?) : Event
111+ data class SessionUpserted(val info: WireSession) : Event
112+ data class SessionDeleted(val sessionId: String?) : Event
113+ data object Other : Event
114+ }
115+
116+ /** Parse one raw SSE `data:` payload into an [Event]; null if malformed. */
117+ fun parseEvent(raw: String): Event? {
118+ val root = runCatching { json.parseToJsonElement(raw).jsonObject }.getOrNull() ?: return null
119+ val props = root["properties"] as? JsonObject ?: JsonObject(emptyMap())
120+ return when (root.str("type")) {
121+ "message.updated" -> decode<WireMessageInfo>(props["info"])?.let { Event.MessageUpdated(it) }
122+ "message.part.updated" -> {
123+ val partObj = props["part"] as? JsonObject ?: return Event.Other
124+ parsePart(partObj)?.let { Event.PartUpdated(it, props.str("delta").ifEmpty { null }) } ?: Event.Other
125+ }
126+ "message.part.removed" -> Event.PartRemoved(props.str("messageID"), props.str("partID"))
127+ "message.removed" -> Event.MessageRemoved(props.str("messageID"))
128+ "session.idle" -> Event.SessionIdle(props.str("sessionID"))
129+ "session.error" -> Event.SessionError(props.str("sessionID").ifEmpty { null }, decode<WireError>(props["error"]))
130+ "session.created", "session.updated" -> decode<WireSession>(props["info"])?.let { Event.SessionUpserted(it) }
131+ "session.deleted" -> Event.SessionDeleted(
132+ props.str("sessionID").ifEmpty { null } ?: (props["info"] as? JsonObject)?.str("id")?.ifEmpty { null },
133+ )
134+ else -> Event.Other
135+ }
136+ }
137+
138+ private inline fun <reified T> decode(el: JsonElement?): T? =
139+ el?.let { runCatching { json.decodeFromJsonElement<T>(it) }.getOrNull() }
140+
141+ // ─── Small JSON helpers ───────────────────────────────────────────────────
142+
143+ private fun JsonObject.str(key: String): String =
144+ (this[key] as? JsonPrimitive)?.contentOrNull ?: ""
145+
146+ private fun JsonObject.bool(key: String): Boolean =
147+ (this[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.contentOrNull?.toBoolean() } ?: false
148+}
app/src/main/java/soy/iko/opencode/core/SseClient.ktnew file+63
@@ -0,0 +1,63 @@
1+package soy.iko.opencode.core
2+
3+import okhttp3.OkHttpClient
4+import okhttp3.Request
5+import okhttp3.Response
6+import okhttp3.sse.EventSource
7+import okhttp3.sse.EventSourceListener
8+import okhttp3.sse.EventSources
9+import java.util.concurrent.TimeUnit
10+
11+/**
12+ * Long-lived subscription to the opencode `/event` SSE stream.
13+ *
14+ * Crux only models request/response HTTP, so the streaming connection lives here
15+ * in the shell: each decoded event's `data` payload (a JSON object whose own
16+ * `type` field is the discriminant) is handed to [onEvent], which the core then
17+ * parses via [Protocol.parseEvent].
18+ */
19+class SseClient(
20+ private val url: String,
21+ private val auth: String?,
22+ private val onEvent: (String) -> Unit,
23+ private val onStateChange: (Boolean) -> Unit,
24+) {
25+ // A dedicated client with no read timeout — the stream is meant to stay open.
26+ private val client = OkHttpClient.Builder()
27+ .connectTimeout(15, TimeUnit.SECONDS)
28+ .readTimeout(0, TimeUnit.SECONDS)
29+ .retryOnConnectionFailure(true)
30+ .build()
31+
32+ private var source: EventSource? = null
33+
34+ fun connect() {
35+ val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
36+ builder.header("User-Agent", "opencode-android/1.0")
37+ if (auth != null) builder.header("Authorization", auth)
38+ source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
39+ }
40+
41+ fun close() {
42+ source?.cancel()
43+ source = null
44+ }
45+
46+ private val listener = object : EventSourceListener() {
47+ override fun onOpen(eventSource: EventSource, response: Response) {
48+ onStateChange(true)
49+ }
50+
51+ override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
52+ if (data.isNotBlank()) onEvent(data)
53+ }
54+
55+ override fun onClosed(eventSource: EventSource) {
56+ onStateChange(false)
57+ }
58+
59+ override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
60+ onStateChange(false)
61+ }
62+ }
63+}
app/src/main/java/soy/iko/opencode/core/ViewModel.ktnew file+77
@@ -0,0 +1,77 @@
1+package soy.iko.opencode.core
2+
3+/**
4+ * Immutable snapshot the UI renders. Mirrors the Rust core's `ViewModel`, so
5+ * the two implementations stay behaviourally identical.
6+ */
7+
8+enum class Screen { Connect, Sessions, Chat }
9+
10+enum class MessageStatus { Sent, Pending, Failed }
11+
12+data class SessionView(
13+ val id: String,
14+ val title: String,
15+)
16+
17+data class ToolView(
18+ val name: String,
19+ val status: String,
20+ val title: String?,
21+)
22+
23+data class MessageView(
24+ val id: String,
25+ val role: String,
26+ val text: String,
27+ val reasoning: String?,
28+ val tools: List<ToolView>,
29+ val time: Long,
30+ val status: MessageStatus,
31+ val streaming: Boolean,
32+) {
33+ val isUser: Boolean get() = role == "user"
34+}
35+
36+data class UiState(
37+ val screen: Screen = Screen.Connect,
38+ val serverUrl: String = "",
39+ val username: String = "",
40+ val password: String = "",
41+ val authRequired: Boolean = false,
42+ val connected: Boolean = false,
43+ val loading: Boolean = false,
44+ val error: String? = null,
45+ val sessions: List<SessionView> = emptyList(),
46+ val currentSessionId: String? = null,
47+ val currentSessionTitle: String = "",
48+ val messages: List<MessageView> = emptyList(),
49+ val draft: String = "",
50+ val generating: Boolean = false,
51+ val sseConnected: Boolean = true,
52+)
53+
54+/**
55+ * Everything the shell can ask the core to do. Internal HTTP results are not
56+ * events here (unlike the Rust core, which routes them through `then_send`);
57+ * the Kotlin driver awaits them inline in coroutines instead.
58+ */
59+sealed interface Event {
60+ data class ServerUrlChanged(val url: String) : Event
61+ data class UsernameChanged(val value: String) : Event
62+ data class PasswordChanged(val value: String) : Event
63+ data object Connect : Event
64+
65+ data object LoadSessions : Event
66+ data class SelectSession(val id: String) : Event
67+ data object CreateSession : Event
68+ data class DeleteSession(val id: String) : Event
69+
70+ data class DraftChanged(val text: String) : Event
71+ data class SendMessage(val text: String) : Event
72+ data object CancelGeneration : Event
73+
74+ data object NavigateToSessions : Event
75+ data object NavigateToConnect : Event
76+ data object DismissError : Event
77+}
app/src/main/java/soy/iko/opencode/data/model/Agent.ktdeleted−37
@@ -1,37 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** Entry from `GET /agent`. */
7−@Immutable
8−@Serializable
9−data class Agent(
10− // Defaulted so one name-less element in GET /agent doesn't fail the whole list decode
11− // (emptying the agent picker) — matches the resilient-decoding philosophy. A blank name is
12− // degraded but recoverable; a thrown decode is not.
13− val name: String = "",
14− val description: String? = null,
15− val mode: String? = null,
16− val builtIn: Boolean = false,
17− val prompt: String? = null,
18−) {
19− val isPrimary: Boolean get() = mode == "primary"
20− val displayDescription: String get() = description?.takeIf { it.isNotBlank() } ?: "Custom agent"
21−}
22−
23−/** Entry from `GET /command`. */
24−@Immutable
25−@Serializable
26−data class Command(
27− // Defaulted so one name-less element in GET /command doesn't fail the whole list decode
28− // (emptying the command picker) — matches the resilient-decoding philosophy.
29− val name: String = "",
30− val description: String? = null,
31− val agent: String? = null,
32− val model: String? = null,
33− val template: String = "",
34− val subtask: Boolean = false,
35−) {
36− val displayDescription: String get() = description?.takeIf { it.isNotBlank() } ?: template.take(80)
37−}
app/src/main/java/soy/iko/opencode/data/model/BusEvent.ktdeleted−109
@@ -1,109 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import kotlinx.serialization.SerialName
4−import kotlinx.serialization.Serializable
5−
6−/**
7− * The SSE envelope from `GET /event`: `{ "type": "<event>", "properties": { ... } }`.
8− * Discriminated on `type` (the global discriminator). Unknown events decode to
9− * [UnknownEvent] so the stream never dies on a new event type.
10− *
11− * Property shapes are kept lenient (nullable fields + ignoreUnknownKeys) because they
12− * drift across opencode versions; the reducer only reads the fields it needs.
13− */
14−@Serializable
15−sealed interface BusEvent
16−
17−@Serializable
18−@SerialName("server.connected")
19−data object ServerConnected : BusEvent
20−
21−@Serializable
22−@SerialName("message.updated")
23−data class MessageUpdated(val properties: Props) : BusEvent {
24− @Serializable
25− data class Props(val info: MessageInfo)
26−}
27−
28−@Serializable
29−@SerialName("message.part.updated")
30−data class MessagePartUpdated(val properties: Props) : BusEvent {
31− @Serializable
32− data class Props(
33− val part: Part,
34− val sessionID: String? = null,
35− val messageID: String? = null,
36− )
37−}
38−
39−@Serializable
40−@SerialName("message.part.removed")
41−data class MessagePartRemoved(val properties: Props) : BusEvent {
42− @Serializable
43− data class Props(
44− val sessionID: String? = null,
45− val messageID: String? = null,
46− val partID: String? = null,
47− )
48−}
49−
50−@Serializable
51−@SerialName("message.removed")
52−data class MessageRemoved(val properties: Props) : BusEvent {
53− @Serializable
54− data class Props(
55− val sessionID: String? = null,
56− val messageID: String? = null,
57− )
58−}
59−
60−@Serializable
61−@SerialName("session.idle")
62−data class SessionIdle(val properties: Props) : BusEvent {
63− @Serializable
64− data class Props(val sessionID: String? = null)
65−}
66−
67−@Serializable
68−@SerialName("session.error")
69−data class SessionError(val properties: Props) : BusEvent {
70− @Serializable
71− data class Props(
72− val sessionID: String? = null,
73− val error: kotlinx.serialization.json.JsonElement? = null,
74− )
75−}
76−
77−@Serializable
78−@SerialName("session.updated")
79−data class SessionUpdated(val properties: Props) : BusEvent {
80− @Serializable
81− data class Props(val info: Session)
82−}
83−
84−@Serializable
85−@SerialName("session.deleted")
86−data class SessionDeleted(val properties: Props) : BusEvent {
87− @Serializable
88− data class Props(val info: Session? = null, val sessionID: String? = null)
89−}
90−
91−@Serializable
92−@SerialName("permission.updated")
93−data class PermissionUpdated(val properties: Permission) : BusEvent
94−
95−@Serializable
96−@SerialName("permission.replied")
97−data class PermissionReplied(val properties: Props) : BusEvent {
98− @Serializable
99− data class Props(
100− val sessionID: String? = null,
101− val permissionID: String? = null,
102− val response: String? = null,
103− )
104−}
105−
106−/** Fallback for any event type we don't model. */
107−@Serializable
108−@SerialName("__unknown")
109−data object UnknownEvent : BusEvent
app/src/main/java/soy/iko/opencode/data/model/Common.ktdeleted−41
@@ -1,41 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−@Immutable
7−@Serializable
8−data class TimeInfo(
9− val created: Long? = null,
10− val updated: Long? = null,
11− val completed: Long? = null,
12−)
13−
14−/** Timing carried by message parts and tool states. The opencode server sends `time: { start,
15− * end?, compacted? }` for these (unlike Session/MessageInfo/Permission, which use the
16− * created/updated/completed shape of [TimeInfo]). With `ignoreUnknownKeys`, modelling these
17− * fields with [TimeInfo] would silently discard start/end/compacted — every part/tool time
18− * would decode to all-nulls — so this separate shape exists for them. */
19−@Immutable
20−@Serializable
21−data class PartTimeInfo(
22− val start: Long? = null,
23− val end: Long? = null,
24− val compacted: Long? = null,
25−)
26−
27−@Immutable
28−@Serializable
29−data class Tokens(
30− val input: Long = 0,
31− val output: Long = 0,
32− val reasoning: Long = 0,
33− val cache: Cache = Cache(),
34−) {
35− @Serializable
36− @Immutable
37− data class Cache(
38− val read: Long = 0,
39− val write: Long = 0,
40− )
41−}
app/src/main/java/soy/iko/opencode/data/model/Files.ktdeleted−44
@@ -1,44 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** Entry from `GET /file?path=` (directory listing). */
7−@Immutable
8−@Serializable
9−data class FileNode(
10− val name: String = "",
11− val path: String = "",
12− val type: String? = null,
13− // Size in bytes and last-modified epoch-ms. The server doesn't currently emit these, so
14− // they default to null and the browser renders nothing extra; optional + defaulted keeps
15− // the client forward-compatible (resilient decoding) so the moment the server adds them
16− // the listing shows size/date with no client change.
17− val size: Long? = null,
18− val mtime: Long? = null,
19−) {
20− val isDirectory: Boolean get() = type == "directory"
21−}
22−
23−/** Response of `GET /file/content?path=`. */
24−@Immutable
25−@Serializable
26−data class FileContent(
27− val type: String? = null, // "text" | "binary"
28− val content: String = "",
29− val diff: String? = null,
30− val mimeType: String? = null,
31− val encoding: String? = null,
32−) {
33− val isBinary: Boolean get() = type == "binary" || encoding == "base64"
34−}
35−
36−/** Entry from `GET /file/status` (VCS status). */
37−@Immutable
38−@Serializable
39−data class FileStatusEntry(
40− val path: String = "",
41− val added: Int = 0,
42− val removed: Int = 0,
43− val status: String? = null, // "added" | "deleted" | "modified"
44−)
app/src/main/java/soy/iko/opencode/data/model/Message.ktdeleted−69
@@ -1,69 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−import kotlinx.serialization.json.JsonElement
7−import kotlinx.serialization.json.JsonClassDiscriminator
8−
9−/**
10− * The `info` object of a message. Discriminated on `role`, which differs from the
11− * global `type` discriminator used by [Part], so this hierarchy overrides it.
12− */
13−@OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)
14−@Serializable
15−@JsonClassDiscriminator("role")
16−sealed interface MessageInfo {
17− val id: String
18− val sessionID: String
19− val time: TimeInfo?
20−}
21−
22−@Immutable
23−@Serializable
24−@SerialName("user")
25−data class UserMessage(
26− override val id: String = "",
27− override val sessionID: String = "",
28− override val time: TimeInfo? = null,
29−) : MessageInfo
30−
31−@Immutable
32−@Serializable
33−@SerialName("assistant")
34−data class AssistantMessage(
35− override val id: String = "",
36− override val sessionID: String = "",
37− val parentID: String? = null,
38− val providerID: String? = null,
39− val modelID: String? = null,
40− val cost: Double? = null,
41− val tokens: Tokens? = null,
42− // JsonElement (not JsonObject) so a server that sends `error` as a bare string/array — or any
43− // non-object shape — decodes instead of throwing mid-AssistantMessage (the MessageInfo
44− // polymorphic fallback can't catch that, since `role` already matched). Mirrors
45− // SessionError.error. Not currently read by the UI, but kept tolerant for forward-compat.
46− val error: JsonElement? = null,
47− override val time: TimeInfo? = null,
48−) : MessageInfo {
49− /** A run is complete once the server stamps a completion time. */
50− val isComplete: Boolean get() = time?.completed != null
51−}
52−
53−/** Fallback for an unrecognized `role`, so new server roles never crash decoding. */
54−@Immutable
55−@Serializable
56−@SerialName("__unknown")
57−data class UnknownMessage(
58− override val id: String = "",
59− override val sessionID: String = "",
60− override val time: TimeInfo? = null,
61−) : MessageInfo
62−
63−/** A message together with its parts — the shape returned by message endpoints and the prompt response. */
64−@Immutable
65−@Serializable
66−data class MessageWithParts(
67− val info: MessageInfo,
68− val parts: List<Part> = emptyList(),
69−)
app/src/main/java/soy/iko/opencode/data/model/Part.ktdeleted−127
@@ -1,127 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−import kotlinx.serialization.json.JsonElement
7−import kotlinx.serialization.json.JsonObject
8−import kotlinx.serialization.json.JsonPrimitive
9−
10−/**
11− * A message part — a discriminated union on `type` (the global class discriminator).
12− * Unknown types decode to [UnknownPart] via the registered polymorphic default,
13− * so the stream survives server additions.
14− *
15− * Every part carries [id] plus its parent [messageID]/[sessionID], which the reducer
16− * uses to attach streamed parts to the right message.
17− */
18−@Serializable
19−sealed interface Part {
20− val id: String
21− val messageID: String?
22− val sessionID: String?
23−}
24−
25−@Immutable
26−@Serializable
27−@SerialName("text")
28−data class TextPart(
29− override val id: String = "",
30− override val messageID: String? = null,
31− override val sessionID: String? = null,
32− val text: String = "",
33− val synthetic: Boolean = false,
34− val ignored: Boolean = false,
35− val time: PartTimeInfo? = null,
36−) : Part
37−
38−@Immutable
39−@Serializable
40−@SerialName("reasoning")
41−data class ReasoningPart(
42− override val id: String = "",
43− override val messageID: String? = null,
44− override val sessionID: String? = null,
45− val text: String = "",
46− val time: PartTimeInfo? = null,
47−) : Part
48−
49−@Immutable
50−@Serializable
51−@SerialName("tool")
52−data class ToolPart(
53− override val id: String = "",
54− override val messageID: String? = null,
55− override val sessionID: String? = null,
56− val callID: String = "",
57− val tool: String = "",
58− val state: ToolState = ToolPending,
59−) : Part
60−
61−@Immutable
62−@Serializable
63−@SerialName("file")
64−data class FilePart(
65− override val id: String = "",
66− override val messageID: String? = null,
67− override val sessionID: String? = null,
68− val mime: String? = null,
69− val filename: String? = null,
70− val url: String? = null,
71− // opencode's message-v2 schema sends `source` as a structured FilePartSource OBJECT
72− // ({ type, path, text, ... }), not a string, for @-file mentions. Typing it as String
73− // threw a SerializationException on decode — which the SSE path silently swallows, so the
74− // whole part vanished. Keep it as a tolerant JsonElement (mirroring Permission.pattern) and
75− // read the path via [sourcePath]; a bare-string source is still tolerated.
76− val source: JsonElement? = null,
77−) : Part
78−
79−/** The file path referenced by a [FilePart.source]. opencode sends `source` as a FilePartSource
80− * object whose `path` field holds the file path; older/other shapes may send a bare string.
81− * Returns null when there's no usable path. */
82−val FilePart.sourcePath: String?
83− get() = when (val s = source) {
84− is JsonPrimitive -> if (s.isString) s.content else null
85− is JsonObject -> (s["path"] as? JsonPrimitive)?.let { if (it.isString) it.content else null }
86− else -> null
87− }
88−
89−@Immutable
90−@Serializable
91−@SerialName("step-start")
92−data class StepStartPart(
93− override val id: String = "",
94− override val messageID: String? = null,
95− override val sessionID: String? = null,
96−) : Part
97−
98−@Immutable
99−@Serializable
100−@SerialName("agent")
101−data class AgentPart(
102− override val id: String = "",
103− override val messageID: String? = null,
104− override val sessionID: String? = null,
105− val name: String = "",
106−) : Part
107−
108−@Immutable
109−@Serializable
110−@SerialName("step-finish")
111−data class StepFinishPart(
112− override val id: String = "",
113− override val messageID: String? = null,
114− override val sessionID: String? = null,
115− val cost: Double? = null,
116− val tokens: Tokens? = null,
117−) : Part
118−
119−/** Fallback for an unrecognized `type`. */
120−@Immutable
121−@Serializable
122−@SerialName("__unknown")
123−data class UnknownPart(
124− override val id: String = "",
125− override val messageID: String? = null,
126− override val sessionID: String? = null,
127−) : Part
app/src/main/java/soy/iko/opencode/data/model/Permission.ktdeleted−58
@@ -1,58 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−import kotlinx.serialization.json.JsonElement
6−import kotlinx.serialization.json.JsonArray
7−import kotlinx.serialization.json.JsonPrimitive
8−
9−/**
10− * A permission request from `permission.updated`. The tool detail lives in [type] +
11− * [pattern] + [metadata]; [pattern] is a string or array of strings on the wire, so
12− * it's kept as a [JsonElement] and flattened for display.
13− */
14−@Immutable
15−@Serializable
16−data class Permission(
17− val id: String = "",
18− val sessionID: String = "",
19− val type: String? = null,
20− val pattern: JsonElement? = null,
21− val messageID: String? = null,
22− val callID: String? = null,
23− val title: String? = null,
24− // JsonElement (not JsonObject) so a non-object `metadata` shape decodes instead of throwing,
25− // matching [pattern]. Not read by the UI today, but kept tolerant for forward-compat.
26− val metadata: JsonElement? = null,
27− val time: TimeInfo? = null,
28−) {
29− val patternText: String?
30− get() = when (val p = pattern) {
31− null -> null
32− is JsonPrimitive -> p.content
33− // Only a JSON array is flattened; any other shape (e.g. an object) would make
34− // the previous unguarded `p.jsonArray` throw during composition, so treat it
35− // as "no displayable pattern" instead.
36− is JsonArray -> p.mapNotNull { (it as? JsonPrimitive)?.content }.joinToString(", ").ifEmpty { null }
37− else -> null
38− }
39−}
40−
41−/** Allowed values for the permission response body.
42− *
43− * [SESSION] is a client-side scope: it auto-responds [ONCE] to subsequent permission requests
44− * whose (type, pattern) match a remembered set, without showing the dialog. The set lives in
45− * [soy.iko.opencode.ui.chat.ChatViewModel] and is cleared on connection change. It is NOT sent
46− * to the server (the server only knows `once`/`always`/`reject`); the VM maps it to [ONCE] on
47− * the wire and tracks the grant locally. This gives users a middle ground between "allow once"
48− * (re-prompts on every file read) and "always" (persists in the server config outliving the app). */
49−enum class PermissionResponse(val wire: String) {
50− ONCE("once"),
51− ALWAYS("always"),
52− REJECT("reject"),
53− SESSION("once"),
54−}
55−
56−/** Body for `POST /session/:id/permissions/:permissionID`. */
57−@Serializable
58−data class PermissionReplyBody(val response: String)
app/src/main/java/soy/iko/opencode/data/model/Project.ktdeleted−32
@@ -1,32 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/**
7− * A project known to the server, from `GET /project`. A project corresponds to a git
8− * worktree root; [worktree] is the absolute path the agent can run in. Used to populate
9− * the directory picker when creating a session in a specific directory.
10− */
11−@Immutable
12−@Serializable
13−data class Project(
14− val id: String = "",
15− val worktree: String = "",
16− val vcs: String? = null,
17− val time: TimeInfo? = null,
18−)
19−
20−/**
21− * The server's current path info, from `GET /path`. [directory] is the working directory
22− * a request with no `directory` override resolves to (the server's launch cwd), shown in
23− * the picker as the "server default" option.
24− */
25−@Immutable
26−@Serializable
27−data class PathInfo(
28− val directory: String? = null,
29− val worktree: String? = null,
30− val state: String? = null,
31− val config: String? = null,
32−)
app/src/main/java/soy/iko/opencode/data/model/Prompt.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import kotlinx.serialization.SerialName
4−import kotlinx.serialization.Serializable
5−
6−/** Body for `POST /session/:id/message`. */
7−@Serializable
8−data class PromptRequest(
9− val parts: List<PromptPart>,
10− val model: ModelRef? = null,
11− val agent: String? = null,
12−)
13−
14−/**
15− * An input part for a prompt — a discriminated union on `type` (the global class
16− * discriminator). We compose text and file (image/document attachment) parts; the server
17− * models more (agent, subtask) that this client doesn't send.
18− */
19−@Serializable
20−sealed interface PromptPart
21−
22−@Serializable
23−@SerialName("text")
24−data class TextPromptPart(val text: String) : PromptPart
25−
26−/**
27− * A file/image attachment. [url] must be a data URL carrying the base64 payload —
28− * `data:<mime>;base64,<bytes>` — which is how the server embeds media for the model to
29− * see (see opencode's message-v2.ts). [mime] must match the payload; the server forwards
30− * it as the model's mediaType.
31− */
32−@Serializable
33−@SerialName("file")
34−data class FilePromptPart(
35− val mime: String,
36− val url: String,
37− val filename: String? = null,
38−) : PromptPart
39−
40−/** Body for `POST /session/:id/command`. */
41−@Serializable
42−data class CommandRequest(
43− val command: String,
44− val arguments: String = "",
45− val agent: String? = null,
46−)
47−
48−/** Body for `POST /session/:id/revert`. */
49−@Serializable
50−data class RevertRequest(
51− val messageID: String,
52− val partID: String? = null,
53−)
54−
55−/** Body for `POST /session/:id/summarize`. */
56−@Serializable
57−data class SummarizeRequest(
58− val providerID: String,
59− val modelID: String,
60−)
61−
62−/** Body for `POST /session/:id/shell`. */
63−@Serializable
64−data class ShellRequest(
65− val agent: String,
66− val command: String,
67− val model: ModelRef? = null,
68−)
app/src/main/java/soy/iko/opencode/data/model/Provider.ktdeleted−84
@@ -1,84 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** Response of `GET /config/providers`. */
7−@Immutable
8−@Serializable
9−data class ProvidersResponse(
10− val providers: List<Provider> = emptyList(),
11− val default: Map<String, String> = emptyMap(),
12−)
13−
14−@Immutable
15−@Serializable
16−data class Provider(
17− // Defaulted so one id-less element in GET /config/providers doesn't fail the whole list decode
18− // (emptying the model picker) — matches MessageInfo's defaulted id and the resilient-decoding
19− // philosophy. A blank id is degraded but recoverable; a thrown decode is not.
20− val id: String = "",
21− val name: String? = null,
22− val models: Map<String, ModelInfo> = emptyMap(),
23−) {
24− val displayName: String get() = name?.takeIf { it.isNotBlank() } ?: id
25−}
26−
27−@Immutable
28−@Serializable
29−data class ModelInfo(
30− val id: String? = null,
31− val name: String? = null,
32−) {
33− fun displayName(modelKey: String): String =
34− name?.takeIf { it.isNotBlank() } ?: id ?: modelKey
35−}
36−
37−/** A flattened provider/model selection used by the prompt body and the model picker. */
38−@Immutable
39−@Serializable
40−data class ModelRef(
41− val providerID: String,
42− val modelID: String,
43−)
44−
45−/** A single selectable entry in the model picker, flattened from [ProvidersResponse]. */
46−@Immutable
47−data class ModelOption(
48− val providerID: String,
49− val modelID: String,
50− val providerLabel: String,
51− val modelLabel: String,
52−) {
53− val ref: ModelRef get() = ModelRef(providerID, modelID)
54−}
55−
56−/** Flatten providers into a sorted list of pickable options. */
57−fun ProvidersResponse.toOptions(): List<ModelOption> =
58− providers.flatMap { provider ->
59− provider.models.map { (modelKey, info) ->
60− ModelOption(
61− providerID = provider.id,
62− modelID = info.id ?: modelKey,
63− providerLabel = provider.displayName,
64− modelLabel = info.displayName(modelKey),
65− )
66− }
67− }.sortedWith(
68− // CASE_INSENSITIVE_ORDER compares in place; compareBy { it.x.lowercase() } would
69− // allocate a fresh lowercased string on every comparison (O(N log N) allocations).
70− compareBy<ModelOption, String>(String.CASE_INSENSITIVE_ORDER) { it.providerLabel }
71− .thenBy(String.CASE_INSENSITIVE_ORDER) { it.modelLabel },
72− )
73−
74−/** The default option to preselect: the server's default for some provider, else the first model. */
75−fun ProvidersResponse.defaultOption(options: List<ModelOption> = toOptions()): ModelOption? {
76− // Try each configured provider default in turn and take the first whose model actually
77− // survives in `options` (the list may be filtered). Checking only the first `default` entry
78− // would mispreselect an arbitrary first option whenever that one provider's default model
79− // isn't present, ignoring the other configured defaults.
80− for ((providerID, modelID) in default) {
81− options.firstOrNull { it.providerID == providerID && it.modelID == modelID }?.let { return it }
82− }
83− return options.firstOrNull()
84−}
app/src/main/java/soy/iko/opencode/data/model/Search.ktdeleted−101
@@ -1,101 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−
7−/**
8− * One ripgrep match from `GET /find?pattern=` (content search). [path] and [lines] are
9− * wrapped `{ text }` objects on the wire; [submatches] carry the column offsets of each
10− * hit within the line so the UI can highlight them.
11− */
12−@Immutable
13−@Serializable
14−data class FindMatch(
15− val path: TextField = TextField(),
16− val lines: TextField = TextField(),
17− @SerialName("line_number") val lineNumber: Int = 0,
18− @SerialName("absolute_offset") val absoluteOffset: Long = 0,
19− val submatches: List<SubMatch> = emptyList(),
20−) {
21− @Immutable
22− @Serializable
23− data class TextField(val text: String = "")
24−
25− @Immutable
26− @Serializable
27− data class SubMatch(
28− val start: Int = 0,
29− val end: Int = 0,
30− )
31−
32− /** The matched file's path (relative to the search root). */
33− val filePath: String get() = path.text
34−
35− /** The matching line's text, trimmed of a trailing newline for display. */
36− val lineText: String get() = lines.text.trimEnd('\n', '\r')
37−}
38−
39−/**
40− * One workspace symbol from `GET /find/symbol?query=`. [kind] is the LSP `SymbolKind`
41− * integer; [location.uri] is a file URI and [location.range] the symbol's span.
42− */
43−@Immutable
44−@Serializable
45−data class SymbolResult(
46− val name: String = "",
47− val kind: Int = 0,
48− val location: Location = Location(),
49−) {
50− @Immutable
51− @Serializable
52− data class Location(
53− val uri: String = "",
54− val range: Range = Range(),
55− )
56−
57− @Immutable
58− @Serializable
59− data class Range(
60− val start: Pos = Pos(),
61− val end: Pos = Pos(),
62− )
63−
64− @Immutable
65− @Serializable
66− data class Pos(
67− val line: Int = 0,
68− val character: Int = 0,
69− )
70−
71− /** The file path portion of [Location.uri], stripping a `file://` scheme when present.
72− * Handles both empty-authority (`file:///abs/path`) and non-empty-authority
73− * (`file://host/abs/path`) URIs by parsing the URI and taking its path component,
74− * rather than a prefix strip that would leave the authority glued to the path. */
75− val filePath: String
76− get() {
77− val uri = location.uri
78− // Only parse file: URIs; for anything else, return as-is.
79− if (!uri.startsWith("file:")) return uri
80− return runCatching { java.net.URI(uri).path }
81− .getOrNull()
82− ?.takeIf { it.isNotBlank() }
83− ?: uri.removePrefix("file://").ifBlank { uri }
84− }
85−
86− /** 1-based line for display; the wire range is 0-based. */
87− val displayLine: Int get() = location.range.start.line + 1
88−}
89−
90−// LSP SymbolKind → label. A map lookup (rather than a large `when`) keeps the accessor
91−// trivial. Indices follow the LSP SymbolKind enum.
92−private val symbolKindLabels = mapOf(
93− 1 to "file", 2 to "module", 3 to "namespace", 4 to "package", 5 to "class",
94− 6 to "method", 7 to "property", 8 to "field", 9 to "constructor", 10 to "enum",
95− 11 to "interface", 12 to "function", 13 to "variable", 14 to "constant", 15 to "string",
96− 16 to "number", 17 to "boolean", 18 to "array", 19 to "object", 20 to "key",
97− 22 to "enum member", 23 to "struct", 26 to "type",
98−)
99−
100−/** Human-readable label for an LSP [SymbolResult.kind]. */
101−fun symbolKindLabel(kind: Int): String = symbolKindLabels[kind] ?: "symbol"
app/src/main/java/soy/iko/opencode/data/model/ServerProfile.ktdeleted−27
@@ -1,27 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−
5−/**
6− * A saved opencode server connection. The [password] for HTTP Basic auth is resolved
7− * separately from EncryptedSharedPreferences and is null when not loaded/needed.
8− */
9−@Immutable
10−data class ServerProfile(
11− val id: String,
12− val label: String,
13− val baseUrl: String,
14− val username: String? = null,
15− val password: String? = null,
16− val lastUsed: Long = 0,
17− // When true, the client upgrades a cleartext http:// URL to https:// so credentials and
18− // traffic are never sent over the wire in the clear for this server.
19− val requireHttps: Boolean = false,
20− // Optional OkHttp certificate pin(s) ("sha256/<base64>", whitespace/comma-separated for
21− // multiple) applied to this server's TLS connection for defense against a rogue CA.
22− val certPin: String? = null,
23−) {
24− val hasAuth: Boolean get() = !username.isNullOrBlank()
25−
26− val displayLabel: String get() = label.takeIf { it.isNotBlank() } ?: baseUrl
27−}
app/src/main/java/soy/iko/opencode/data/model/Session.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** A session as returned by `GET /session` and `POST /session`. */
7−@Immutable
8−@Serializable
9−data class Session(
10− // Defaulted so one id-less element in GET /session doesn't fail the whole list decode
11− // (emptying the session list) — matches MessageInfo's defaulted id and the resilient-decoding
12− // philosophy. A blank id is degraded but recoverable; a thrown decode is not.
13− val id: String = "",
14− val parentID: String? = null,
15− val title: String? = null,
16− val version: String? = null,
17− val time: TimeInfo? = null,
18− // The absolute worktree/directory the agent runs in for this session. Set server-side
19− // from the `directory` query param at creation; persisted per session so the client
20− // needn't re-send it on follow-up calls (see OpencodeApiClient.createSession).
21− val directory: String? = null,
22− val projectID: String? = null,
23− // Present only while the session is shared (POST /session/:id/share); cleared on unshare.
24− val share: Share? = null,
25− // Present only while a revert checkpoint is active (POST /session/:id/revert); cleared on unrevert.
26− val revert: Revert? = null,
27−) {
28− val displayTitle: String get() = title?.takeIf { it.isNotBlank() } ?: "Untitled session"
29−
30− /** A compact form of [directory] for list/subtitle display: the last path segment,
31− * or the full path when it has no separators. Null/blank when no directory is set. */
32− val displayDirectory: String?
33− get() = directory?.takeIf { it.isNotBlank() }?.trimEnd('/')?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
34−
35− /** True while the session has an active public share link. */
36− val isShared: Boolean get() = !share?.url.isNullOrBlank()
37−
38− /** True while a revert checkpoint is active (messages after it are hidden server-side). */
39− val isReverted: Boolean get() = revert != null
40−
41− /** Public share link for the session, from `POST /session/:id/share`. */
42− @Immutable
43− @Serializable
44− data class Share(val url: String = "")
45−
46− /** The active revert checkpoint, from `POST /session/:id/revert`. */
47− @Immutable
48− @Serializable
49− data class Revert(
50− val messageID: String = "",
51− val partID: String? = null,
52− val snapshot: String? = null,
53− val diff: String? = null,
54− )
55−}
56−
57−/** Body for `POST /session`. */
58−@Serializable
59−data class CreateSessionRequest(
60− val parentID: String? = null,
61− val title: String? = null,
62−)
63−
64−/** Body for `PATCH /session/:id`. */
65−@Serializable
66−data class UpdateSessionRequest(
67− val title: String? = null,
68−)
app/src/main/java/soy/iko/opencode/data/model/Todo.ktdeleted−125
@@ -1,125 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−import kotlinx.serialization.builtins.ListSerializer
6−import kotlinx.serialization.json.Json
7−import kotlinx.serialization.json.JsonElement
8−
9−/** The tool name opencode uses to write the agent's task plan. */
10−const val TODO_WRITE_TOOL = "todowrite"
11−
12−/**
13− * A single entry in an agent's task plan, as written by opencode's `todowrite` tool.
14− * Every field is defaulted and decoding ignores unknown keys (see [parseTodos]) so a
15− * change to the tool's payload shape degrades to a best-effort render instead of
16− * dropping the whole plan.
17− */
18−@Immutable
19−@Serializable
20−data class TodoItem(
21− val id: String = "",
22− val content: String = "",
23− val status: String = "pending",
24− val priority: String? = null,
25−)
26−
27−/** Normalized lifecycle of a [TodoItem]; [UNKNOWN] covers any status the client doesn't model. */
28−enum class TodoStatus { PENDING, IN_PROGRESS, COMPLETED, CANCELLED, UNKNOWN }
29−
30−/** Normalized priority of a [TodoItem]; [NONE] covers null/unmodelled priorities. The order
31− * matters: HIGH > MEDIUM > LOW, used by [TodoPlan] tinting and a11y labels. */
32−enum class TodoPriority { HIGH, MEDIUM, LOW, NONE }
33−
34−fun TodoItem.priorityEnum(): TodoPriority = when ((priority ?: "").trim().lowercase()) {
35− "high", "h", "1", "urgent", "critical" -> TodoPriority.HIGH
36− "medium", "med", "m", "normal", "2" -> TodoPriority.MEDIUM
37− "low", "l", "3", "minor", "backlog" -> TodoPriority.LOW
38− else -> TodoPriority.NONE
39−}
40−
41−fun TodoItem.statusEnum(): TodoStatus = when (status.trim().lowercase()) {
42− "pending", "todo", "" -> TodoStatus.PENDING
43− "in_progress", "in-progress", "inprogress", "running", "active" -> TodoStatus.IN_PROGRESS
44− "completed", "complete", "done" -> TodoStatus.COMPLETED
45− "cancelled", "canceled", "skipped" -> TodoStatus.CANCELLED
46− else -> TodoStatus.UNKNOWN
47−}
48−
49−@Serializable
50−private data class TodoWriteInput(val todos: List<TodoItem> = emptyList())
51−
52−// A lenient decoder mirroring OpencodeJson's resilience (unknown keys ignored, nulls
53−// coerced to defaults) without pulling the network layer into data/model.
54−private val todoJson = Json {
55− ignoreUnknownKeys = true
56− isLenient = true
57− coerceInputValues = true
58− explicitNulls = false
59−}
60−
61−/**
62− * Extract the todo list from a `todowrite` tool call's input JSON. The tool sends the
63− * full list on every write, so a single call's input is a complete plan snapshot.
64− * Accepts either the documented `{ "todos": [...] }` object or a bare array, and returns
65− * an empty list on anything unparseable.
66− */
67−fun parseTodos(input: JsonElement?): List<TodoItem> {
68− if (input == null) return emptyList()
69− return runCatching {
70− todoJson.decodeFromJsonElement(TodoWriteInput.serializer(), input).todos
71− }.recoverCatching {
72− todoJson.decodeFromJsonElement(ListSerializer(TodoItem.serializer()), input)
73− }.getOrDefault(emptyList())
74−}
75−
76−/**
77− * The current task plan for a conversation: the todos of the most recent `todowrite`
78− * tool call that carries a non-empty, parseable list. opencode rewrites the whole list
79− * on every write, so a single call is a complete snapshot; scanning newest-first and
80− * skipping empties avoids a mid-stream write (input not yet arrived) briefly blanking a
81− * plan that's still valid.
82− *
83− * A caller-side cache ([TodoPlanCache]) memoizes the result against the input list's
84− * identity so a back-to-back emission of the same list instance (e.g. a `combine` that
85− * re-evaluates without a real upstream change) skips the O(messages×parts) scan. The
86− * scan still runs whenever the list instance changes (every streamed snapshot), but
87− * `distinctUntilChanged` downstream dedupes the *result* so the UI doesn't recompose.
88− */
89−fun currentTodoPlan(messages: List<MessageWithParts>): List<TodoItem> {
90− for (mi in messages.indices.reversed()) {
91− val parts = messages[mi].parts
92− for (pi in parts.indices.reversed()) {
93− val part = parts[pi]
94− if (part is ToolPart && part.tool.equals(TODO_WRITE_TOOL, ignoreCase = true)) {
95− val todos = parseTodos(part.state.inputElement())
96− if (todos.isNotEmpty()) return todos
97− }
98− }
99− }
100− return emptyList()
101−}
102−
103−/**
104− * A tiny memoization layer for [currentTodoPlan]: if the same list instance is passed
105− * twice in a row, the cached result is returned without re-scanning. The [ChatViewModel]
106− * `todoPlan` flow's `combine` can re-emit the same list instance when an unrelated input
107− * (e.g. the optimistic-messages StateFlow) updates without the SSE stream having changed;
108− * without this cache, every such re-emit re-scans every part of every message off-main.
109− *
110− * Not thread-safe by design — it's only read from the `flowOn(Dispatchers.Default)`
111− * operator's coroutine, which is single-threaded per emission. The cache holds a single
112− * `(ref, result)` pair; a different list instance replaces it.
113− */
114−class TodoPlanCache {
115− private var lastRef: List<MessageWithParts>? = null
116− private var lastResult: List<TodoItem> = emptyList()
117−
118− fun plan(messages: List<MessageWithParts>): List<TodoItem> {
119− if (messages === lastRef) return lastResult
120− val result = currentTodoPlan(messages)
121− lastRef = messages
122− lastResult = result
123− return result
124− }
125−}
app/src/main/java/soy/iko/opencode/data/model/ToolState.ktdeleted−62
@@ -1,62 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−import kotlinx.serialization.json.JsonElement
7−import kotlinx.serialization.json.JsonClassDiscriminator
8−
9−/**
10− * The state machine of a tool call, discriminated on `status`.
11− * pending -> running -> completed | error
12− */
13−@OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)
14−@Serializable
15−@JsonClassDiscriminator("status")
16−sealed interface ToolState
17−
18−@Serializable
19−@SerialName("pending")
20−data object ToolPending : ToolState
21−
22−@Immutable
23−@Serializable
24−@SerialName("running")
25−data class ToolRunning(
26− val input: JsonElement? = null,
27− val title: String? = null,
28− val time: PartTimeInfo? = null,
29−) : ToolState
30−
31−@Immutable
32−@Serializable
33−@SerialName("completed")
34−data class ToolCompleted(
35− val input: JsonElement? = null,
36− val output: String? = null,
37− val title: String? = null,
38− val time: PartTimeInfo? = null,
39−) : ToolState
40−
41−@Immutable
42−@Serializable
43−@SerialName("error")
44−data class ToolError(
45− val input: JsonElement? = null,
46− val error: String? = null,
47− val time: PartTimeInfo? = null,
48−) : ToolState
49−
50−/** Fallback for an unrecognized `status`. */
51−@Serializable
52−@SerialName("__unknown")
53−data object ToolUnknown : ToolState
54−
55−/** The raw input arguments carried by a tool call, present on the running/completed/error
56− * states (pending/unknown carry none). */
57−fun ToolState.inputElement(): JsonElement? = when (this) {
58− is ToolRunning -> input
59− is ToolCompleted -> input
60− is ToolError -> input
61− else -> null
62−}
app/src/main/java/soy/iko/opencode/data/network/CertPinUtil.ktdeleted−35
@@ -1,35 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.ServerProfile
4−
5−/**
6− * Shared helpers for resolving a [ServerProfile]'s certificate-pin field and the
7− * http→https upgrade it implies. The logic is used in three places that must agree:
8− * [HttpClientFactory] (the REST/SSE channel), [soy.iko.opencode.OpencodeApp]'s
9− * PinnedImageCallFactory (the image-loading channel), and [soy.iko.opencode.ui.components.RemoteImage]
10− * (resolving image base URLs). Previously each call site carried its own private copy
11− * with a "must be kept in sync" comment; the helpers here are the single source of truth.
12− */
13−internal object CertPinUtil {
14−
15− /** Split a certificate-pin field into individual OkHttp pins. Accepts whitespace- or
16− * comma-separated "sha256/<base64>" entries; blank entries are dropped. */
17− fun parseCertPins(raw: String?): List<String> =
18− raw?.split(Regex("[\\s,]+"))?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()
19−
20− /** The base URL after applying [ServerProfile.requireHttps]: a cleartext http:// URL is
21− * upgraded to https:// so the "Require HTTPS" choice is enforced at the transport layer.
22− * A configured certificate pin also forces TLS: a pin is meaningless over cleartext and
23− * would otherwise be silently dropped, so we honor the opt-in security control by upgrading
24− * rather than connecting unpinned in the clear. Relies on [HttpClientFactory.normalizeBaseUrl]
25− * for scheme/trailing-slash normalization. */
26− fun effectiveBaseUrl(profile: ServerProfile): String {
27− val normalized = HttpClientFactory.normalizeBaseUrl(profile.baseUrl)
28− val forceHttps = profile.requireHttps || parseCertPins(profile.certPin).isNotEmpty()
29− return if (forceHttps && normalized.lowercase().startsWith("http://")) {
30− "https://" + normalized.substring("http://".length)
31− } else {
32− normalized
33− }
34− }
35−}
app/src/main/java/soy/iko/opencode/data/network/EventStreamClient.ktdeleted−335
@@ -1,335 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.BusEvent
4−import soy.iko.opencode.util.safeExceptionSummary
5−import android.util.Log
6−import io.ktor.client.HttpClient
7−import io.ktor.client.plugins.timeout
8−import io.ktor.client.plugins.sse.sse
9−import io.ktor.sse.ServerSentEvent
10−import kotlinx.coroutines.CancellationException
11−import kotlinx.coroutines.CoroutineScope
12−import kotlin.coroutines.EmptyCoroutineContext
13−import kotlinx.coroutines.channels.BufferOverflow
14−import kotlinx.coroutines.channels.Channel
15−import kotlinx.coroutines.channels.ChannelResult
16−import kotlinx.coroutines.flow.Flow
17−import kotlinx.coroutines.flow.MutableStateFlow
18−import kotlinx.coroutines.flow.SharedFlow
19−import kotlinx.coroutines.flow.StateFlow
20−import kotlinx.coroutines.flow.SharingStarted
21−import kotlinx.coroutines.flow.asStateFlow
22−import kotlinx.coroutines.flow.buffer
23−import kotlinx.coroutines.flow.channelFlow
24−import kotlinx.coroutines.flow.shareIn
25−import kotlinx.coroutines.isActive
26−import kotlinx.coroutines.launch
27−import kotlinx.coroutines.selects.onTimeout
28−import kotlinx.coroutines.selects.select
29−import java.io.IOException
30−import kotlin.random.Random
31−
32−/**
33− * Owns the single long-lived `GET /event` SSE subscription and exposes it as a hot
34− * [SharedFlow] of [BusEvent]. The connection is opened when the first collector
35− * subscribes (WhileSubscribed) and reconnects with backoff on drop.
36− *
37− * Ordering contract: callers that send a prompt must already be collecting [events]
38− * (directly or via the repository) so early `message.part.updated` deltas aren't missed.
39− */
40−@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
41−open class EventStreamClient(
42− private val client: HttpClient,
43− private val scope: CoroutineScope,
44− private val idleTimeoutMs: Long = NetworkConfig.sseIdleTimeoutMs,
45− private val initialBackoffMs: Long = NetworkConfig.sseInitialBackoffMs,
46− private val maxBackoffMs: Long = NetworkConfig.sseMaxBackoffMs,
47− private val bufferCapacity: Int = NetworkConfig.sseEventBufferCapacity,
48−) {
49− protected constructor() : this(
50− HttpClient(io.ktor.client.engine.okhttp.OkHttp) {},
51− CoroutineScope(EmptyCoroutineContext),
52− )
53− enum class ConnectionState { Disconnected, Connecting, Connected, Failed, AuthFailed }
54−
55− private val _state = MutableStateFlow(ConnectionState.Disconnected)
56− open val state: StateFlow<ConnectionState> = _state.asStateFlow()
57−
58− /** Number of reconnect attempts made since the last successful [ConnectionState.Connected]
59− * period. Incremented each time the stream loop begins a new connection attempt after a
60− * drop, and reset to 0 on a successful connect. Surfaced so the UI can show "Reconnecting
61− * (attempt N)…" during a sustained outage, giving the user confidence the system is
62− * actively retrying rather than stuck. */
63− private val _reconnectAttempts = MutableStateFlow(0)
64− open val reconnectAttempts: StateFlow<Int> = _reconnectAttempts.asStateFlow()
65−
66− open val events: SharedFlow<BusEvent> by lazy {
67− stream()
68− .buffer(bufferCapacity, BufferOverflow.DROP_OLDEST)
69− .shareIn(
70− scope = scope,
71− started = SharingStarted.WhileSubscribed(stopTimeoutMillis = NetworkConfig.stateFlowSubscriptionTimeoutMs),
72− replay = 0,
73− )
74− }
75−
76− /** Conflated channel used to cut the reconnect backoff short when network returns. */
77− private val reconnectSignal = Channel<Unit>(Channel.CONFLATED)
78−
79− /** Classifies a non-retryable SSE failure so the UI can show the right recovery hint:
80− * an auth failure (401/403) reads "check credentials", while other 4xx (400/404/405…)
81− * reads "check the server URL and version". Returns null for transient/retryable errors. */
82− private enum class SseFailureKind { Auth, Other }
83−
84− private fun classifyNonRetryableSseFailure(e: Throwable): SseFailureKind? =
85− generateSequence(e as Throwable?) { it.cause.takeIf { c -> c !== it } }
86− .take(16)
87− .mapNotNull { t ->
88− when (t) {
89− is io.ktor.client.plugins.sse.SSEClientException -> t.response?.status?.value
90− is io.ktor.client.plugins.ClientRequestException -> t.response.status.value
91− else -> null
92− }
93− }
94− // Non-408/429 4xx = permanent; 408 and 429 stay in the transient retry path.
95− .map { code -> when {
96− code in 400..499 && code != 408 && code != 429 ->
97− if (code == 401 || code == 403) SseFailureKind.Auth else SseFailureKind.Other
98− else -> null
99− } }
100− .firstOrNull { it != null }
101−
102− /** Request an immediate reconnect, skipping any in-progress backoff. */
103− open fun triggerReconnect() { reconnectSignal.trySend(Unit) }
104−
105− /**
106− * Read SSE events from [events], racing each read against an idle-timeout watchdog.
107− * Throws [IOException] on idle timeout so the outer reconnect loop fires; breaks on
108− * clean stream close or scope cancellation.
109− *
110− * If the idle watchdog tripped because a [triggerReconnect] signal was consumed
111− * (rather than a genuine idle timeout), [onReconnectConsumed] is invoked so the outer
112− * reconnect loop can reconnect immediately instead of waiting out the backoff — the
113− * signal is already consumed, so the backoff `select` couldn't be cut short.
114− */
115− private suspend fun readSseEvents(
116− scope: CoroutineScope,
117− events: kotlinx.coroutines.channels.ReceiveChannel<ServerSentEvent>,
118− onReconnectConsumed: () -> Unit,
119− send: suspend (BusEvent) -> Unit,
120− ) {
121− while (scope.isActive) {
122− // The OkHttp engine has readTimeout=0 (the SSE stream must never time out on
123− // read), so a socket the peer never closed would otherwise hang until OS TCP
124− // keepalive kicks in — minutes to hours on stock Linux. If nothing arrives
125− // within the idle timeout, treat the connection as half-open and drop it.
126− var consumedReconnectSignal = false
127− val result: ChannelResult<ServerSentEvent>? = select {
128− events.onReceiveCatching { it }
129− onTimeout(idleTimeoutMs) { null }
130− // A triggerReconnect() issued while a read is active must interrupt it now:
131− // return the same null sentinel as the idle timeout so a half-open socket
132− // (no TCP RST) is dropped and reconnected promptly instead of waiting out
133− // idleTimeoutMs (~90s).
134− reconnectSignal.onReceive { consumedReconnectSignal = true; null }
135− }
136− if (result == null) {
137− if (consumedReconnectSignal) onReconnectConsumed()
138− throw IOException("SSE read dropped (idle timeout or reconnect requested), reconnecting")
139− }
140− val sse = result.getOrNull()
141− if (sse == null) {
142− // The producer channel is closed. A non-null cause means `incoming`
143− // failed (e.g. a socket reset bridged from the producer) — rethrow it so
144− // the outer loop logs and retries with backoff. A clean close (null
145− // cause) just ends this attempt and lets the loop reconnect.
146− result.exceptionOrNull()?.let { throw it }
147− break
148− }
149− val data = sse.data
150− if (data == null) {
151− // A comment or keep-alive event (no data field) resets the idle watchdog
152− // — servers send `: ping` comments to keep the connection alive through
153− // proxies. Without this, a server that only sends comments would still
154− // hit the idle timeout and reconnect unnecessarily.
155− continue
156− }
157− val event = try {
158− OpencodeJson.decodeFromString(BusEvent.serializer(), data)
159− } catch (e: kotlinx.serialization.SerializationException) {
160− Log.d("EventStream", "Skipping unparseable SSE event", e)
161− continue
162− }
163− if (_state.value != ConnectionState.Connected) {
164− _state.value = ConnectionState.Connected
165− }
166− send(event)
167− }
168− }
169−
170− private fun stream(): Flow<BusEvent> = channelFlow {
171− val scope = this
172− // Drain any stale reconnect signal from a previous collection cycle so it
173− // doesn't spuriously reset the backoff on startup (WhileSubscribed may have
174− // stopped the upstream while triggerReconnect() queued a signal).
175− while (reconnectSignal.tryReceive().isSuccess) { /* drain */ }
176− var backoffMs = initialBackoffMs
177− // Tracks whether this is the first iteration (the initial connect) vs a reconnect,
178− // so the attempt counter is only incremented on reconnects (not the first connect).
179− var firstAttempt = true
180− while (isActive) {
181− // Increment the reconnect-attempt counter on every iteration except the initial
182− // connect, so the UI can show "Reconnecting (attempt N)…". Reset to 0 on success.
183− if (firstAttempt) firstAttempt = false else _reconnectAttempts.value++
184− _state.value = ConnectionState.Connecting
185− // Set by readSseEvents when a triggerReconnect() signal interrupted an active
186− // read. The signal is consumed to drop the socket, so the backoff select below
187− // can't also see it — without this flag the reconnect would wait the full
188− // backoff despite the caller asking for an immediate reconnect (network
189− // handoff, manual refresh, ...).
190− var reconnectConsumedDuringRead = false
191− try {
192− // The SSE stream is long-lived: disable the request-level and socket
193− // timeouts (the client default is 60s for REST) in the request config
194− // so the connection isn't killed mid-stream. The idle-timeout watchdog
195− // below handles half-open connections instead.
196− client.sse(
197− "event",
198− request = {
199− timeout {
200− requestTimeoutMillis = Long.MAX_VALUE
201− // Disable the socket (read) timeout entirely for the SSE stream.
202− // A finite value would kill the connection whenever the server
203− // is quiet for longer than that (idle sessions, slow agent runs),
204− // causing a reconnect storm. Half-open detection is handled by
205− // the idle-timeout watchdog below plus OkHttp's pingInterval on
206− // HTTP/2 connections.
207− socketTimeoutMillis = Long.MAX_VALUE
208− }
209− },
210− ) {
211− // The SSE block is open — the connection is established. Mark as
212− // Connected immediately so downstream re-seed logic fires even when
213− // the server only sends keep-alive comments (no data events).
214− if (_state.value != ConnectionState.Connected) {
215− _state.value = ConnectionState.Connected
216− }
217− // Clear any stale reconnect signal from a triggerReconnect() call
218− // made while the previous stream was healthy, so it doesn't suppress
219− // the next legitimate backoff.
220− while (reconnectSignal.tryReceive().isSuccess) { /* drain */ }
221− // Bridge ktor's `incoming` flow to a channel so each element can be
222− // raced against the idle-timeout watchdog via select. We collect it
223− // ourselves instead of `incoming.produceIn(scope)`: produceIn launches
224− // the collector as a child of this channelFlow, so when `incoming`
225− // throws on an abnormal socket close — a TCP reset, i.e. the common
226− // mobile case: Wi-Fi⇄cellular handoff, server or proxy RST — the child's
227− // failure cancels the whole channelFlow and bypasses the retry `catch`
228− // below. That killed reconnect outright and surfaced the IOException as
229− // an uncaught crash through the (handler-less) shareIn scope. Collecting
230− // into our own channel and closing it with the cause keeps the failure
231− // local: readSseEvents sees the closed channel, rethrows the cause, and
232− // the normal retry/backoff path handles it. (A clean EOF closes the
233− // channel with no cause → readSseEvents breaks and reconnects as before.)
234− val events = Channel<ServerSentEvent>(Channel.BUFFERED)
235− val producer = scope.launch {
236− try {
237− incoming.collect { events.send(it) }
238− events.close()
239− } catch (c: CancellationException) {
240− events.close(c)
241− throw c
242− } catch (t: Throwable) {
243− // Deliver the failure via the channel rather than letting it
244− // propagate up and cancel the parent channelFlow.
245− events.close(t)
246− }
247− }
248− // Reset the backoff only once real data actually arrives, not on
249− // block entry: a server that accepts the connection then immediately
250− // drops it would otherwise loop forever at the initial backoff and
251− // never escalate the exponential ramp.
252− var receivedAny = false
253− try {
254− readSseEvents(scope, events, { reconnectConsumedDuringRead = true }) {
255− if (!receivedAny) {
256− receivedAny = true
257− backoffMs = initialBackoffMs
258− // A genuine event confirms the connection is healthy, so reset
259− // the reconnect-attempt counter for the next outage's count.
260− _reconnectAttempts.value = 0
261− }
262− send(it)
263− }
264− } finally {
265− producer.cancel()
266− events.cancel()
267− }
268− }
269− } catch (c: CancellationException) {
270− _state.value = ConnectionState.Disconnected
271− throw c
272− } catch (e: Exception) {
273− // If the scope was cancelled (e.g. connection close), the closed-client
274− // exception is expected — don't log a spurious "stream error" warning.
275− val failureKind = classifyNonRetryableSseFailure(e)
276− if (failureKind != null) {
277− // The server rejected the request with a non-retryable 4xx (bad
278− // credentials, missing endpoint, ...) — retrying won't help. Log a
279− // scrubbed summary (class + status) instead of the full exception, whose
280− // message carries the request URL and may include auth or paths.
281− Log.w("EventStream", "SSE non-retryable 4xx (${if (failureKind == SseFailureKind.Auth) "auth" else "endpoint"}), awaiting explicit reconnect: ${safeExceptionSummary(e)}")
282− _state.value = if (failureKind == SseFailureKind.Auth) ConnectionState.AuthFailed else ConnectionState.Failed
283− if (!isActive) {
284− // Final teardown (last subscriber left) while a 4xx surfaced: end in
285− // Disconnected like every other loop-exit path. Failed must stay
286− // observable only while the flow is live/retrying, not after teardown.
287− _state.value = ConnectionState.Disconnected
288− break
289− }
290− // Don't complete the flow: a subscriber may fix the profile and call
291− // triggerReconnect(). Suspend until an explicit reconnect signal
292− // arrives (no backoff delay), then re-attempt the connection. This receive
293− // is outside the try above, so reset state to Disconnected if the last
294− // subscriber leaves (cancellation) while we're parked here — otherwise the
295− // stream would be torn down with state stuck at Failed.
296− try {
297− reconnectSignal.receive()
298− } catch (c: CancellationException) {
299− _state.value = ConnectionState.Disconnected
300− throw c
301− }
302− continue
303− } else if (isActive) {
304− Log.w("EventStream", "SSE stream error, will retry: ${safeExceptionSummary(e)}")
305− }
306− }
307− _state.value = ConnectionState.Disconnected
308− if (!isActive) break
309− // Wait for the backoff, but allow a reconnect signal to cut it short. When
310− // readSseEvents consumed a triggerReconnect() signal to drop an active read,
311− // the signal is already spent so the select below can't receive it — pass a
312− // zero backoff in that case so the reconnect is immediate (the whole point of
313− // triggerReconnect: network handoff, manual refresh, ...).
314− val signaled = waitForBackoffOrSignal(reconnectConsumedDuringRead, backoffMs)
315− backoffMs = if (signaled) initialBackoffMs else (backoffMs * 2).coerceAtMost(maxBackoffMs)
316− }
317− }
318−
319− /** Suspend for the backoff unless [reconnectConsumedDuringRead] (immediate) or a new
320− * [triggerReconnect] arrives during the wait. Returns true when the reconnect should
321− * skip the backoff ramp (signal-driven), false when the full backoff elapsed. */
322− private suspend fun waitForBackoffOrSignal(
323− reconnectConsumedDuringRead: Boolean,
324− backoffMs: Long,
325− ): Boolean {
326− if (reconnectConsumedDuringRead) return true
327− var signaled = false
328− val jitter = ((backoffMs * NetworkConfig.retryJitterFactor) * (Random.nextDouble() * 2 - 1)).toLong()
329− select {
330− reconnectSignal.onReceive { signaled = true }
331− onTimeout((backoffMs + jitter).coerceAtLeast(0)) { /* normal backoff elapsed */ }
332− }
333− return signaled
334− }
335−}
app/src/main/java/soy/iko/opencode/data/network/HttpClientFactory.ktdeleted−178
@@ -1,178 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.ServerProfile
4−import io.ktor.client.HttpClient
5−import io.ktor.client.engine.okhttp.OkHttp
6−import io.ktor.client.plugins.HttpTimeout
7−import io.ktor.client.plugins.api.Send
8−import io.ktor.client.plugins.api.createClientPlugin
9−import io.ktor.client.plugins.auth.Auth
10−import io.ktor.client.plugins.auth.providers.BasicAuthCredentials
11−import io.ktor.client.plugins.auth.providers.basic
12−import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
13−import io.ktor.client.plugins.defaultRequest
14−import io.ktor.client.plugins.sse.SSE
15−import io.ktor.http.HttpHeaders
16−import io.ktor.http.URLBuilder
17−import io.ktor.http.takeFrom
18−import io.ktor.serialization.kotlinx.json.json
19−import okhttp3.CertificatePinner
20−import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
21−import java.util.concurrent.TimeUnit
22−
23−/**
24− * Builds a Ktor client bound to a single [ServerProfile]. One client per active
25− * profile: it carries the base URL, optional Basic auth, JSON negotiation, and the
26− * SSE plugin used for `GET /event`.
27− */
28−object HttpClientFactory {
29−
30− fun create(profile: ServerProfile): HttpClient {
31− val normalizedUrl = CertPinUtil.effectiveBaseUrl(profile)
32− val isHttps = normalizedUrl.lowercase().startsWith("https://")
33− // Parse the host with OkHttp's own parser (not java.net.URI, which rejects hosts OkHttp
34− // accepts, e.g. underscores in "my_server.local"). If pinning is configured over HTTPS
35− // but the host can't be parsed, fail closed: never build an unpinned client — that would
36− // be a silent security downgrade for a user who opted into pinning.
37− val pinHost = normalizedUrl.toHttpUrlOrNull()?.host
38− val pins = CertPinUtil.parseCertPins(profile.certPin)
39− if (pins.isNotEmpty() && isHttps && pinHost == null) {
40− throw IllegalStateException(
41− "Certificate pinning is configured but the server host could not be parsed from $normalizedUrl",
42− )
43− }
44− // Fail closed for HTTP+auth with an unparseable host too: otherwise neither the HTTPS Auth
45− // plugin nor the HTTP host-scoped header plugin is installed (the HTTP branch below is
46− // gated on pinHost != null), so credentials would be configured but never transmitted —
47− // hasAuth reads true in the UI while every request goes out unauthenticated. An unparseable
48− // host generally can't connect anyway, but failing here surfaces a clear error instead of a
49− // silent auth bypass.
50− if (profile.hasAuth && !isHttps && pinHost == null) {
51− throw IllegalStateException(
52− "Auth is configured but the server host could not be parsed from $normalizedUrl",
53− )
54− }
55−
56− return HttpClient(OkHttp) {
57− expectSuccess = true
58−
59− engine {
60− config {
61− // A normal read timeout for REST calls. The SSE stream overrides this
62− // to infinite inside the sse {} request block (see EventStreamClient),
63− // so the long-lived event connection is never killed mid-stream.
64− readTimeout(NetworkConfig.readTimeoutSeconds, TimeUnit.SECONDS)
65− connectTimeout(NetworkConfig.connectTimeoutSeconds, TimeUnit.SECONDS)
66− retryOnConnectionFailure(true)
67− pingInterval(NetworkConfig.pingIntervalSeconds, TimeUnit.SECONDS)
68− // Pin the server certificate(s) when configured and connecting over TLS.
69− // A malformed pin throws here (surfaced as a connection failure), which is
70− // the right fail-closed behavior for a security control the user opted into.
71− if (pins.isNotEmpty() && pinHost != null && isHttps) {
72− certificatePinner(
73− CertificatePinner.Builder().apply { pins.forEach { add(pinHost, it) } }.build(),
74− )
75− }
76− }
77− }
78−
79− install(ContentNegotiation) {
80− json(OpencodeJson)
81− }
82−
83− install(SSE)
84−
85− // Request-level timeout for REST calls. The SSE stream overrides this to
86− // infinite inside the sse {} request block (see EventStreamClient) so the
87− // long-lived /event connection isn't killed after 60s. The engine's connect
88− // timeout and the SSE idle-timeout watchdog handle stuck SSE connections.
89− install(HttpTimeout) {
90− requestTimeoutMillis = NetworkConfig.restRequestTimeoutMs
91− }
92−
93− if (profile.hasAuth) {
94− if (isHttps) {
95− install(Auth) {
96− basic {
97− credentials {
98− BasicAuthCredentials(
99− username = profile.username.orEmpty(),
100− password = profile.password.orEmpty(),
101− )
102− }
103− // Send eagerly so opencode doesn't need a 401 challenge round-trip, but
104− // only to the configured host: a cross-host redirect must not carry the
105− // credentials off-origin (the plugin would still answer a genuine 401 from
106− // the real host reactively). The Auth plugin is only installed for HTTPS
107− // profiles — over HTTP, even reactive credential sending would leak
108− // passwords in cleartext, so we don't install it at all.
109− sendWithoutRequest { request ->
110− pinHost != null && request.url.host.equals(pinHost, ignoreCase = true)
111− }
112− }
113− }
114− // Defense in depth mirroring the HTTP branch below: sendWithoutRequest only gates
115− // *eager* attachment on the outgoing request — it neither strips an Authorization
116− // header that HttpRedirect copies from the original (configured-host) request onto
117− // a cross-origin redirect target, nor stops the reactive Basic provider answering a
118− // 401 from such a target. followRedirects is enabled by default, so re-check the
119− // host on every physical send and remove the header whenever it isn't the pinned
120− // host, guaranteeing credentials never leave the configured origin.
121− install(
122− createClientPlugin("HttpsBasicAuthHostScoped") {
123− on(Send) { request ->
124− if (pinHost == null || !request.url.host.equals(pinHost, ignoreCase = true)) {
125− request.headers.remove(HttpHeaders.Authorization)
126− }
127− proceed(request)
128− }
129− },
130− )
131− } else if (pinHost != null) {
132− // For HTTP profiles with auth, attach the Basic header proactively (the reactive
133− // Auth plugin is skipped for non-HTTPS so a 401 can't silently re-send credentials
134− // in cleartext), but scope it to the configured host and re-check on EVERY physical
135− // send. Redirects matter: Ktor builds the redirect request by copying the original
136− // headers, so an unconditional header would carry the cleartext credentials to a
137− // cross-host redirect target. Setting it here (and stripping it off-host) mirrors
138− // the HTTPS path's sendWithoutRequest host guard so credentials never go off-origin.
139− val credentials = java.util.Base64.getEncoder().encodeToString(
140− "${profile.username.orEmpty()}:${profile.password.orEmpty()}".toByteArray(),
141− )
142− install(
143− createClientPlugin("HttpBasicAuthHostScoped") {
144− on(Send) { request ->
145− if (request.url.host.equals(pinHost, ignoreCase = true)) {
146− request.headers[HttpHeaders.Authorization] = "Basic $credentials"
147− } else {
148− request.headers.remove(HttpHeaders.Authorization)
149− }
150− proceed(request)
151− }
152− },
153− )
154− }
155− }
156−
157− defaultRequest {
158− url.takeFrom(URLBuilder().takeFrom(normalizedUrl))
159− }
160− }
161− }
162−
163− /** Ensure a scheme and a single trailing slash so relative paths resolve correctly.
164− * Defaults to [https] when no scheme is given so credentials aren't accidentally
165− * sent over cleartext. Users who need plain HTTP must type the scheme explicitly. */
166− fun normalizeBaseUrl(raw: String): String {
167− val trimmed = raw.trim()
168− // Compare the scheme prefix case-insensitively (a lowercased copy) while
169− // preserving the original casing of the rest of the URL in the output.
170− val lowerTrimmed = trimmed.lowercase()
171− val withScheme = if (lowerTrimmed.startsWith("http://") || lowerTrimmed.startsWith("https://")) {
172− trimmed
173− } else {
174− "https://$trimmed"
175− }
176− return if (withScheme.endsWith("/")) withScheme else "$withScheme/"
177− }
178−}
app/src/main/java/soy/iko/opencode/data/network/NetworkConfig.ktdeleted−442
@@ -1,442 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−/**
4− * Centralized tuning parameters for the network and presentation layers. Keeping these
5− * in one place makes them easy to find and adjust without hunting through source files,
6− * and makes the intent of each value explicit rather than a bare magic number.
7− */
8−object NetworkConfig {
9−
10− // --- OkHttp engine timeouts (HttpClientFactory) ---
11−
12− /** Socket connect timeout for all HTTP calls, including the SSE handshake. */
13− const val connectTimeoutSeconds = 30L
14− /** Socket read timeout for ordinary REST calls. The SSE stream overrides this to INFINITE. */
15− const val readTimeoutSeconds = 60L
16− /** OkHttp WebSocket/interval ping, keeping the SSE socket alive through proxies. */
17− const val pingIntervalSeconds = 20L
18− /** Request-level timeout for REST calls (covers connect + headers + body). The SSE stream overrides this to INFINITE. */
19− const val restRequestTimeoutMs = 60_000L
20−
21− // --- REST retry (OpencodeApiClient.withRetry) ---
22−
23− /** Maximum number of attempts for a retriable REST call. */
24− const val retryMaxAttempts = 3
25− /** Initial backoff delay; doubles on each successive failure (exponential backoff). */
26− const val retryInitialDelayMs = 500L
27− /** Cap on a single retry backoff delay, guarding against overflow at high attempt counts. */
28− const val retryMaxDelayMs = 30_000L
29− /** Jitter factor for retry backoff (0.2 = ±20% symmetric random jitter on each delay). */
30− const val retryJitterFactor = 0.2
31−
32− // --- SSE stream (EventStreamClient) ---
33−
34− /** Initial reconnect backoff after an SSE stream drop; doubles up to [sseMaxBackoffMs]. */
35− const val sseInitialBackoffMs = 500L
36− /** Cap on the SSE reconnect backoff. */
37− const val sseMaxBackoffMs = 10_000L
38− /** Reconnect-attempt count at which the connection banner switches from "Reconnecting…"
39− * to "Reconnecting (attempt N)…" — after a few retries the user benefits from seeing the
40− * system is actively retrying rather than stuck. Below this the plain label is calmer. */
41− const val sseReconnectAttemptLabelThreshold = 3
42− /** Max gap between events before a silent/half-open SSE connection is dropped and reconnected. */
43− const val sseIdleTimeoutMs = 90_000L
44− /** Buffer capacity for the SSE events SharedFlow; prevents a slow subscriber stalling the read loop. */
45− const val sseEventBufferCapacity = 64
46−
47− // --- Connectivity monitor (AppContainer) ---
48−
49− /** Grace period after a network is lost before reporting offline. Absorbs the transient
50− * window during a Wi-Fi→cellular handoff where onLost(WiFi) fires before the replacement
51− * network becomes active (cm.activeNetwork is briefly null), so a handoff doesn't flash
52− * offline while a genuine loss (no active network after the grace) is still caught. */
53− const val networkOfflineGraceMs = 2_000L
54−
55− // --- Catalog cache (OpencodeApiClient) ---
56−
57− /** How long cached catalog responses (providers/agents/commands) are considered fresh. */
58− const val catalogCacheTtlMs = 60_000L
59−
60− /** TTL for files written to the cache dir to hand to external apps via FileProvider
61− * (open-externally). Stale files past this age are pruned on the next open so repeated
62− * opens of large files don't accumulate unbounded. 24h covers a typical session. */
63− const val externalCacheTtlMs = 24L * 60 * 60 * 1000
64−
65− // --- Session list (SessionListViewModel) ---
66−
67− /** Max sessions to fetch previews for in one batch. */
68− const val maxPreviewSessions = 50
69− /** Initial render window for the session list — the number of rows composed before the
70− * user scrolls to reveal more. Grows by [sessionListPageStep] as the user nears the
71− * bottom, bounding the sort/filter work on a huge list while keeping scrolling seamless. */
72− const val sessionListInitialPage = 60
73− /** How many additional rows to reveal when the session list render window is exhausted. */
74− const val sessionListPageStep = 60
75− /** Initial render window for the file-browser directory listing. A huge directory
76− * (10k+ entries) sorts/filters in full on each recomposition; windowing the render
77− * bounds the composed-row count while the sort still runs over the full list (so the
78− * order is correct, just the visible slice is capped). Grows as the user scrolls. */
79− const val fileListInitialPage = 100
80− /** How many additional file rows to reveal when the render window is exhausted. */
81− const val fileListPageStep = 100
82− /** Max concurrent preview fetches (prevents flooding the server with parallel requests). */
83− const val maxConcurrentPreviews = 8
84− /** Max characters of a session's last message to keep as a list preview. */
85− const val previewTextMaxLength = 200
86− /** Debounce delay before fetching a session preview after an SSE update, so a burst
87− * of SessionUpdated events (e.g. during active streaming) coalesces into one fetch
88− * instead of launching one per event (each downloading the full message history). */
89− const val previewDebounceMs = 500L
90− /** Debounce for applying SessionUpdated SSE events to the session list state. During
91− * active streaming the server emits these frequently; without debouncing each one
92− * triggers a full list filter + sort + recomposition, causing scroll jank. */
93− const val sessionUpdateDebounceMs = 300L
94−
95− // --- Global search (GlobalSearchViewModel) ---
96−
97− /** Max sessions whose message history is scanned in one global-search pass. Global
98− * search downloads each session's messages, so this bounds the work; if there are more
99− * sessions, the result set notes that the search was truncated. */
100− const val maxSearchSessions = 50
101− /** Debounce before a global search fires, so typing doesn't launch a fetch per keystroke. */
102− const val searchDebounceMs = 350L
103− /** Minimum query length before a global search runs (shorter queries match too much). */
104− const val minSearchQueryLength = 2
105− /** Characters of context to show around a global-search match. */
106− const val searchSnippetLength = 160
107−
108− // --- Message cache (MessageCacheStore) ---
109−
110− /** Minimum interval between on-disk writes of a session's message snapshot, so a fast
111− * token stream doesn't hammer the disk. The cache only needs to be recent enough for an
112− * instant/offline first paint; the network corrects it on the next open. */
113− const val messageCacheWriteThrottleMs = 2_000L
114−
115− /** Grace period before a deferred session delete actually fires, during which an
116− * Undo snackbar lets the user cancel it. */
117− const val undoDeleteDelayMs = 5_000L
118−
119− /** Grace period before a deferred server-profile delete actually fires, during which
120− * an Undo snackbar lets the user cancel it. Same UX rationale as [undoDeleteDelayMs]. */
121− const val undoServerDeleteDelayMs = 5_000L
122−
123− /** Grace period before a deferred crash-report delete actually fires, during which
124− * an Undo snackbar lets the user cancel it. */
125− const val undoReportDeleteDelayMs = 5_000L
126−
127− // --- In-memory message store (SessionRepository.MessageStore) ---
128−
129− /** Max messages to keep in memory per observed session; oldest are evicted beyond this. */
130− const val maxInMemoryMessages = 500
131−
132− // --- File viewer (FileViewScreen) ---
133−
134− /** Cap on how many lines the raw viewer renders and searches. A multi-megabyte file is
135− * split once (not twice) into this many lines at most, so it can't hold two full line
136− * lists in memory or stall the LazyColumn; beyond the cap a truncation banner is shown. */
137− const val maxRenderedFileLines = 5000
138−
139− // --- File browser (FileBrowserViewModel) ---
140−
141− /** Debounce delay before firing a file-search request after the user stops typing. */
142− const val fileSearchDebounceMs = 250L
143−
144− /** Debounce delay before re-running the in-conversation message search after the user
145− * stops typing. The search walks every part of every message (including stringifying
146− * tool state), so debouncing avoids jank on long conversations. The filter itself runs
147− * off the main thread; this delay coalesces rapid keystrokes. */
148− const val chatSearchDebounceMs = 200L
149−
150− // --- Attachments (chat composer) ---
151−
152− /** Max size of a single attachment (image/file) before it's rejected. Base64 inflates
153− * the payload ~33%, and the whole prompt body is held in memory, so cap generously but
154− * finitely to avoid OOM / oversized requests. */
155− const val maxAttachmentBytes = 10L * 1024 * 1024
156−
157− /** Max number of attachments staged for one prompt, to bound memory and request size. */
158− const val maxAttachments = 8
159−
160− /** Max cumulative size of all attachments staged for one prompt. The per-file
161− * [maxAttachmentBytes] cap alone allows [maxAttachments] max-size files (~80MB raw,
162− * ~106MB as base64) to pile up in memory and be re-serialized on every add/remove and
163− * again when the request body is built — a realistic OOM. This bounds the whole set. */
164− const val maxTotalAttachmentBytes = 25L * 1024 * 1024
165−
166− // --- StateFlow sharing (WhileSubscribed) ---
167−
168− /** Grace period before a cold StateFlow is stopped after its last subscriber leaves. */
169− const val stateFlowSubscriptionTimeoutMs = 5_000L
170−
171− /** Maximum time a notification action BroadcastReceiver may hold its goAsync()
172− * PendingResult open. The system ANRs a receiver that doesn't call finish() within
173− * ~10s, so this must stay below that; a slow permission-respond retry (withRetry
174− * exponential backoff up to ~90s) or a blocked outbox enqueue could otherwise blow
175− * past the window. The watchdog finishes the PendingResult at this deadline so the
176− * receiver never ANRs; the underlying network call keeps running on the app scope. */
177− const val notificationReceiverTimeoutMs = 8_000L
178−
179− // --- Draft persistence (ChatViewModel) ---
180−
181− /** Debounce delay before persisting a draft to disk after the user stops typing. */
182− const val draftDebounceMs = 500L
183−
184− /** Maximum characters allowed in the chat input field. A generous cap that prevents
185− * a huge paste from stalling the UI (the field would otherwise buffer and lay out
186− * an unbounded string) while leaving plenty of room for long prompts. */
187− const val maxDraftLengthChars = 32_000
188−
189− /** Show the "remaining characters" supportingText under the chat input once the
190− * draft length crosses this fraction of [maxDraftLengthChars], so the cap is
191− * visible before it silently kicks in but doesn't clutter a normal short prompt. */
192− const val draftCountdownThresholdFraction = 0.8f
193−
194− /** Maximum characters allowed in a session title (rename dialog). Prevents the
195− * server from rejecting an overly long title and keeps list rows readable. */
196− const val maxSessionTitleChars = 200
197−
198− // --- Profile store (ServerEditViewModel) ---
199−
200− /** Timeout for loading a profile from DataStore before giving up. */
201− const val profileLoadTimeoutMs = 5_000L
202−
203− /** Timeout for a credential test (probe) before giving up, so a hung/unresponsive server
204− * doesn't leave the "Testing…" spinner spinning indefinitely. */
205− const val testCredentialsTimeoutMs = 15_000L
206−
207− // --- SSE stream (EventStreamClient, AppContainer) ---
208−
209− /** Delay before retrying the message-activity observer after a failure. */
210− const val observerRetryDelayMs = 5_000L
211− /** Debounce before the run foreground-service is started/stopped in response to
212− * run-activity changes. A run that starts and then fails/idles almost immediately
213− * would otherwise dispatch startForegroundService() then stopService() back-to-back;
214− * if the stop wins the race before startForeground() runs, Android raises the
215− * "did not then call startForeground()" crash. Debouncing collapses that window.
216− * Also serves as a minimum-run-duration gate: a run shorter than this (a quick abort,
217− * a one-token reply) clears [anyRunActive] before the FGS ever posts, so the shade
218− * stays clean of non-dismissable notifications for trivially short runs. The Doze-
219− * resilience benefit only matters for long runs, so a few seconds of gate preserves
220− * the core benefit. */
221− const val runForegroundDebounceMs = 3_000L
222−
223− // --- Markdown rendering (MarkdownText) ---
224−
225− /** Throttle delay to coalesce streaming tokens into one re-parse. The markdown
226− * library re-parses the full AST on every content change, so during a long streaming
227− * response this is O(n²) work. 50ms (~20fps) is smooth for progressively appearing
228− * text while cutting parse work ~3x versus a per-frame (16ms) throttle. */
229− const val streamingThrottleMs = 50L
230−
231− // --- Snackbar one-shot events (ViewModels) ---
232−
233− /** Buffer capacity for transient error SharedFlows that drive snackbars. */
234− const val snackbarEventBufferCapacity = 16
235−
236− /** How long the chat top-bar refresh icon stays in its "refreshing" spinner state
237− * after a tap, giving immediate feedback that the refresh was triggered even when
238− * the connection state is already Connected (so the ConnectionBanner doesn't change). */
239− const val refreshFeedbackMs = 1_200L
240−
241− // --- UI layout constants ---
242−
243− /** Minimum window width (dp) for two-pane layout on tablets / unfolded foldables. */
244− const val twoPaneWidthThresholdDp = 840
245− /** Maximum width fraction a user message bubble can occupy (keeps it readable). */
246− const val userBubbleWidthFraction = 0.85f
247− /** Minimum number of options in a picker sheet (model/agent/command) before its search
248− * field auto-focuses and raises the keyboard on open. A tiny catalog is faster to scan by
249− * eye, so popping the keyboard for it is just friction. */
250− const val pickerSearchAutofocusThreshold = 8
251−
252− /** Minimum number of saved server profiles before the server list shows its search/filter
253− * field. A typical user has one or two servers, where scanning by eye beats typing; power
254− * users juggling many profiles get the filter once it earns its space. */
255− const val serverListSearchThreshold = 5
256−
257− /** Minimum number of crash reports before the diagnostics list shows its search field. */
258− const val diagnosticsSearchThreshold = 8
259−
260− /** Initial render window for the diagnostics crash-report list — the number of rows
261− * composed before the user scrolls to reveal more. Bounds composition work on a device
262− * that has accumulated many crash reports. Grows by [diagnosticsListPageStep] as the
263− * user nears the bottom. */
264− const val diagnosticsListInitialPage = 60
265− /** How many additional crash-report rows to reveal when the render window is exhausted. */
266− const val diagnosticsListPageStep = 60
267−
268− /** Minimum number of sessions in the usage report before the per-session list shows its
269− * filter field. A short history is faster to scan than type into. */
270− const val usageSessionSearchThreshold = 8
271−
272− /** Minimum number of sessions before the session list shows its search/filter field.
273− * Matches the sibling screens' convention: a short list is faster to scan by eye than
274− * type into, so the field earns its vertical space only once the list grows. */
275− const val sessionListSearchThreshold = 5
276− /** Extra bottom content padding (dp) for the chat message list, reserving room for the
277− * jump-to-latest FAB so it never floats over the last message. */
278− const val chatListFabInsetDp = 80
279−
280− /** Extra bottom content padding (dp) for single-pane list screens that host a FAB
281− * (session list, server list, MCP), reserving room so the FAB never floats over the
282− * last row. Unified across screens so the inset doesn't drift (the session list
283− * previously hardcoded 96dp while the chat list used [chatListFabInsetDp]). */
284− const val listFabInsetDp = 96
285− /** Left pane weight in the two-pane layout (session list). */
286− const val twoPaneLeftWeight = 0.38f
287− /** Right pane weight in the two-pane layout (chat detail). */
288− const val twoPaneRightWeight = 0.62f
289−
290− /** Maximum width (dp) for the left (session-list) pane in the two-pane layout. On a wide
291− * tablet the list pane would otherwise stretch too wide for a readable row density; capping
292− * it keeps the list compact and gives the chat detail pane the remaining space. */
293− const val twoPaneLeftMaxWidthDp = 460
294−
295− /** Minimum window width (dp) at which a NavigationRail is shown alongside the
296− * two-pane layout for top-level destination discoverability on large screens. Sits below
297− * [twoPaneWidthThresholdDp] (M3's WindowWidthSizeClass.Medium breakpoint ~600dp) so a
298− * tablet or landscape phone gets the rail while staying single-pane until 840dp, where the
299− * two-pane master/detail split takes over. */
300− const val navigationRailThresholdDp = 600
301−
302− /** Maximum width (dp) for the chat message list on large screens. On a tablet or
303− * unfolded foldable, full-width message bubbles stretch edge-to-edge, hurting
304− * readability — capping and centering the list (like Gmail/Telegram on tablets)
305− * keeps line lengths comfortable. Applied only above [twoPaneWidthThresholdDp]. */
306− const val chatContentMaxWidthDp = 800
307−
308− /** Maximum width (dp) for a single-pane list/form screen on large screens (Diagnostics,
309− * MCP, Usage, Global Search, File Browser). Mirrors [chatContentMaxWidthDp]'s rationale
310− * at a tighter width suited to dense list rows and form fields. Settings and ServerEdit
311− * use 600dp directly; this constant centralizes the same value for the screens that
312− * previously stretched edge-to-edge on tablets. */
313− const val listContentMaxWidthDp = 600
314−
315− /** Maximum width (dp) for the full-screen chat composer dialog on large screens, so
316− * the editor doesn't stretch edge-to-edge on a tablet (matching [chatContentMaxWidthDp]'s
317− * readability rationale for the message list). */
318− const val composerDialogMaxWidthDp = 800
319−
320− /** Maximum height (dp) for a modal bottom sheet's list area. Resolved against the screen
321− * (not the partial sheet) so a sheet that starts fully expanded shows a predictable list
322− * height regardless of the sheet's drag position. */
323− const val pickerSheetMaxHeightDp = 560
324−
325− /** Maximum inline height (dp) for an image attachment in the chat list. A tall image
326− * caps at this so it doesn't dominate the bubble; tapping opens the fullscreen viewer. */
327− const val inlineImageMaxHeightDp = 320
328−
329− /** Minimum inline height (dp) reserved for an image placeholder (loading/error/resolving),
330− * so the layout doesn't jump when the load completes and the image's intrinsic size is known. */
331− const val inlineImageMinHeightDp = 120
332−
333− /** Lines of a code fence rendered before collapsing to a head with a "show more" affordance.
334− * Capped low for mobile: a 200-line block rendered at once can jank a low-end phone, so the
335− * initial render is bounded and a "show more" reveals the rest in place. */
336− const val collapsedCodeLineThreshold = 80
337−
338− /** Lines of a unified diff rendered before collapsing to a head with a "show more" affordance.
339− * Same mobile-performance rationale as [collapsedCodeLineThreshold]. */
340− const val collapsedDiffLineThreshold = 80
341−
342− /** Lines of tool output rendered before collapsing to a head with a "show more" affordance. */
343− const val toolOutputCollapsedLimitChars = 4000
344−
345− /** Lines of tool output rendered before collapsing to a head with a "show more" affordance.
346− * A line-based threshold (rather than the char-based [toolOutputCollapsedLimitChars]) keeps
347− * the collapsed preview a predictable height on mobile — a 4000-char block of short lines
348− * can be 60+ lines and fill the whole screen, defeating the purpose of collapsing. The
349− * char cap still applies as a hard upper bound; this line cap kicks in first for typical
350− * multi-line output. */
351− const val toolOutputCollapsedLimitLines = 30
352−
353− /** Tool input (pretty-printed JSON) shorter than this many lines is shown expanded by
354− * default — for tools like bash/write/edit the command is the most important info and
355− * hiding it behind a tap inverts the priority. Longer inputs stay collapsed to avoid
356− * dominating the bubble. */
357− const val toolInputAutoExpandLineThreshold = 10
358−
359− /** Tool durations below this many ms are hidden from the tool-name row (sub-second runs
360− * are instant and the ms figure is noise). Set to 1000 to hide all sub-second durations,
361− * or 0 to always show. */
362− const val toolDurationHideBelowMs = 1_000L
363−
364− /** Characters of tool output included in a shared/exported transcript before truncation. */
365− const val exportToolOutputLimitChars = 2000
366−
367− /** Maximum zoom factor applied by pinch or double-tap in the fullscreen image viewer. */
368− const val imageViewerMaxZoom = 5f
369−
370− /** Zoom factor a double-tap jumps to when starting from 1× in the fullscreen image viewer. */
371− const val imageViewerDoubleTapZoom = 2.5f
372−
373− /** Duration (ms) of the animated double-tap zoom transition in the fullscreen image viewer. */
374− const val imageViewerZoomAnimMs = 220
375−
376− /** Vertical drag distance (px) in the fullscreen image viewer that triggers swipe-to-dismiss. */
377− const val imageViewerSwipeDismissThreshold = 200f
378−
379− /** Blink period (ms) of the streaming caret at the tail of a live assistant reply. */
380− const val streamingCaretPeriodMs = 500
381−
382− /** Target maximum length (chars) of a single TTS chunk. Android's TextToSpeech enforces a
383− * hard limit (getMaxSpeechInputLength, ~4000 chars) — this is a tighter cap so pause/
384− * resume restarts at a finer granularity. Without it, a pause mid-chunk restarts the
385− * whole chunk from its start; smaller chunks mean less replay on resume. Sentence
386− * boundaries are still preferred, so short sentences pack up to this cap. */
387− const val ttsChunkTargetMaxChars = 200
388−
389− /** Auto-reject a tool-permission prompt after this many ms if the user hasn't responded,
390− * so a forgotten prompt doesn't block the run indefinitely. The foreground service keeps
391− * the process alive, so without a timeout a prompt that the user walked away from holds
392− * the run open forever. The timeout is long (10 minutes) so a deliberate pause to read
393− * the prompt doesn't trip it; a reminder toast-style line appears in the dialog after
394− * [permissionReminderThresholdMs] to surface that the run is waiting. Set to 0 to disable. */
395− const val permissionAutoRejectMs = 10L * 60 * 1000
396−
397− /** Show a "still waiting" reminder in the permission dialog after this many ms. */
398− const val permissionReminderThresholdMs = 60L * 1000
399−
400− /** Duration (ms) the copy button shows its checkmark confirmation before reverting. */
401− const val copyFeedbackMs = 1200
402−
403− /** Gutter width (dp) for each side (old/new) of a unified-diff line-number column. */
404− const val diffGutterWidthDp = 36
405−
406− /** Width (dp) of the +/- prefix column in a unified-diff row. */
407− const val diffPrefixWidthDp = 16
408−
409− /** Maximum width (dp) of a breadcrumb segment in the file browser (non-last segments). */
410− const val breadcrumbSegmentMaxWidthDp = 120
411−
412− /** Maximum width (dp) of the last (current) breadcrumb segment in the file browser. */
413− const val breadcrumbLastSegmentMaxWidthDp = 220
414−
415− /** Vertical scroll threshold beyond which the chat "scroll to top" FAB appears. */
416− const val chatScrollToTopFabThreshold = 200
417−
418− /** Maximum width (dp) for an attachment chip's filename text before it truncates. */
419− const val attachmentChipNameMaxWidthDp = 120
420−
421− /** Maximum height (dp) for the expanded todo-plan checklist in a message bubble. */
422− const val todoPlanMaxHeightDp = 240
423−
424− /** Fallback height (dp) for the connection banner when no text is available (e.g. exit fade). */
425− const val connectionBannerFallbackHeightDp = 44
426−
427− // --- Motion tokens (shared across screens) ---
428−
429− /** Duration (ms) for horizontal slide push/pop nav transitions. M3 spec recommends 200ms
430− * for medium-duration container transitions. */
431− const val motionSlideDurationMs = 200
432− /** Duration (ms) for fade in/out nav and content transitions. */
433− const val motionFadeDurationMs = 180
434−
435− // --- Font scaling ---
436−
437− /** Upper bound on the *combined* app×OS font scale. The chat text-size preference
438− * multiplies on top of the system font scale, so a user at a large system size and
439− * a large app size can reach ~2× and break tight layouts. The provided app scale is
440− * clamped so the product with the OS fontScale never exceeds this. */
441− const val maxCombinedFontScale = 1.8f
442−}
app/src/main/java/soy/iko/opencode/data/network/OpencodeApiClient.ktdeleted−540
@@ -1,540 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.Agent
4−import soy.iko.opencode.data.model.Command
5−import soy.iko.opencode.data.model.CommandRequest
6−import soy.iko.opencode.data.model.CreateSessionRequest
7−import soy.iko.opencode.data.model.FileContent
8−import soy.iko.opencode.data.model.FileNode
9−import soy.iko.opencode.data.model.FileStatusEntry
10−import soy.iko.opencode.data.model.MessageWithParts
11−import soy.iko.opencode.data.model.ModelRef
12−import soy.iko.opencode.data.model.PathInfo
13−import soy.iko.opencode.data.model.FilePromptPart
14−import soy.iko.opencode.data.model.FindMatch
15−import soy.iko.opencode.data.model.PermissionReplyBody
16−import soy.iko.opencode.data.model.PermissionResponse
17−import soy.iko.opencode.data.model.Project
18−import soy.iko.opencode.data.model.PromptPart
19−import soy.iko.opencode.data.model.PromptRequest
20−import soy.iko.opencode.data.model.ProvidersResponse
21−import soy.iko.opencode.data.model.RevertRequest
22−import soy.iko.opencode.data.model.Session
23−import soy.iko.opencode.data.model.ShellRequest
24−import soy.iko.opencode.data.model.SummarizeRequest
25−import soy.iko.opencode.data.model.SymbolResult
26−import soy.iko.opencode.data.model.TextPromptPart
27−import soy.iko.opencode.data.model.UpdateSessionRequest
28−import io.ktor.client.HttpClient
29−import io.ktor.client.call.body
30−import io.ktor.client.plugins.ClientRequestException
31−import io.ktor.client.plugins.ResponseException
32−import io.ktor.client.plugins.ServerResponseException
33−import io.ktor.client.request.delete
34−import io.ktor.client.request.get
35−import io.ktor.client.request.header
36−import io.ktor.client.request.parameter
37−import io.ktor.client.request.patch
38−import io.ktor.client.request.post
39−import io.ktor.client.request.setBody
40−import io.ktor.http.ContentType
41−import io.ktor.http.contentType
42−import kotlinx.coroutines.delay
43−import kotlinx.coroutines.sync.Mutex
44−import kotlinx.coroutines.sync.withLock
45−import kotlinx.serialization.json.buildJsonObject
46−import kotlinx.serialization.json.put
47−import kotlin.random.Random
48−import java.net.URLEncoder
49−
50−/**
51− * Request/response wrapper over the opencode REST endpoints. The long-lived `/event`
52− * SSE stream lives in [EventStreamClient]; everything else is here.
53− */
54−open class OpencodeApiClient private constructor(
55− private val client: HttpClient?,
56− @Suppress("unused") private val testMode: Boolean,
57−) {
58− constructor(client: HttpClient) : this(client, false)
59− protected constructor() : this(null, true)
60−
61− // --- Catalog cache (providers/agents/commands) ---
62− // These change rarely, but the ChatViewModel re-fetches them on every creation.
63− // A short-lived in-memory cache avoids redundant network calls when navigating
64− // between sessions on the same server.
65− private data class CachedEntry<T>(val value: T, val fetchedAt: Long)
66− // Per-catalog mutexes so a slow fetch of one catalog doesn't block the others.
67− // The fetch runs OUTSIDE the lock (holding it across the network call would serialize
68− // all callers and stall invalidation). To keep that correct, each catalog carries a
69− // generation counter, bumped under the mutex by its invalidateXCache(): a fetch captures
70− // the generation before it starts and, when it completes, only writes its result back if
71− // the generation is unchanged — so an invalidation that raced the in-flight fetch is not
72− // defeated by the pre-invalidation result being stored afterwards.
73− private val providersMutex = Mutex()
74− private val agentsMutex = Mutex()
75− private val commandsMutex = Mutex()
76− private var cachedProviders: CachedEntry<ProvidersResponse>? = null
77− private var cachedAgents: CachedEntry<List<Agent>>? = null
78− private var cachedCommands: CachedEntry<List<Command>>? = null
79− // Generation counters (guarded by the matching mutex above) for the invalidation-race guard.
80− private var providersGeneration = 0
81− private var agentsGeneration = 0
82− private var commandsGeneration = 0
83−
84− /** Lightweight connectivity check. Throws on non-2xx / network failure. */
85− open suspend fun ping() {
86− withRetry { client!!.get("global/health").body<String>() }
87− }
88−
89− open suspend fun listSessions(): List<Session> = withRetry {
90− client!!.get("session").body()
91− }
92−
93− /**
94− * Create a session, optionally in a specific worktree [directory]. The directory is a
95− * query parameter (not a body field): the server records it on the session and resolves
96− * it by session id thereafter, so follow-up calls (messages, commands, abort, …) don't
97− * — and shouldn't — re-send it. A null/blank [directory] lets the server fall back to
98− * its own launch cwd, preserving the pre-directory behavior.
99− */
100− open suspend fun createSession(title: String? = null, directory: String? = null): Session {
101− // Generate the idempotency key before entering withRetry so every retry attempt
102− // shares it. Without this, a POST that reached the server but whose response was
103− // lost (reset/timeout) would be retried and create a second orphan session.
104− val idempotencyKey = java.util.UUID.randomUUID().toString()
105− val dir = directory?.takeIf { it.isNotBlank() }
106− return withRetry {
107− client!!.post("session") {
108− contentType(ContentType.Application.Json)
109− header("Idempotency-Key", idempotencyKey)
110− if (dir != null) parameter("directory", dir)
111− setBody(CreateSessionRequest(title = title))
112− }.body()
113− }
114− }
115−
116− /** List the projects (worktree roots) the server knows about, for the directory picker. */
117− open suspend fun listProjects(): List<Project> = withRetry {
118− client!!.get("project").body()
119− }
120−
121− /** The server's current path info; its [PathInfo.directory] is the default (cwd) a
122− * session with no directory override runs in. */
123− open suspend fun currentPath(): PathInfo = withRetry {
124− client!!.get("path").body()
125− }
126−
127− open suspend fun updateSession(id: String, title: String): Session = withRetry {
128− client!!.patch("session/${encode(id)}") {
129− contentType(ContentType.Application.Json)
130− setBody(UpdateSessionRequest(title = title))
131− }.body()
132− }
133−
134− open suspend fun deleteSession(id: String) {
135− try {
136− withRetry { client!!.delete("session/${encode(id)}").body<String>() }
137− } catch (t: ClientRequestException) {
138− // A DELETE that succeeded but whose response was lost gets retried; the retry
139− // hits an already-gone session and returns 404. Deleting a non-existent session
140− // is effectively success, so swallow 404 rather than surfacing a spurious failure.
141− if (t.response.status.value != 404) throw t
142− }
143− }
144−
145− open suspend fun listMessages(sessionId: String): List<MessageWithParts> = withRetry {
146− client!!.get("session/${encode(sessionId)}/message").body()
147− }
148−
149− open suspend fun sendPrompt(
150− sessionId: String,
151− text: String,
152− attachments: List<FilePromptPart> = emptyList(),
153− model: ModelRef? = null,
154− agent: String? = null,
155− // A caller-stable idempotency key. Callers that may re-invoke sendPrompt across
156− // *separate* calls for the same logical message (the offline outbox, which re-sends
157− // a message that stayed queued after an earlier flush failed) must pass a stable key
158− // derived from the persistent message id — otherwise each attempt mints a fresh key
159− // and a POST that reached the server but whose response was lost is re-created as a
160− // duplicate run. When null, a fresh key is generated (correct for one-shot sends).
161− idempotencyKey: String? = null,
162− ): MessageWithParts {
163− // Resolve the key *before* entering withRetry so all retry attempts share it. If the
164− // key were generated inside withRetry, each attempt would get a fresh UUID and the
165− // server couldn't deduplicate a request that reached it but whose response was lost.
166− val resolvedKey = idempotencyKey ?: java.util.UUID.randomUUID().toString()
167− // A text part is only included when there's actual text, so an image-only prompt
168− // (attachments, empty text) doesn't send an empty text part. Attachments follow
169− // the text so the model reads the instruction first.
170− val parts = buildList<PromptPart> {
171− if (text.isNotEmpty()) add(TextPromptPart(text))
172− addAll(attachments)
173− }
174− return withRetry {
175− client!!.post("session/${encode(sessionId)}/message") {
176− contentType(ContentType.Application.Json)
177− header("Idempotency-Key", resolvedKey)
178− setBody(
179− PromptRequest(
180− parts = parts,
181− model = model,
182− agent = agent,
183− ),
184− )
185− }.body()
186− }
187− }
188−
189− open suspend fun abort(sessionId: String) {
190− withRetry { client!!.post("session/${encode(sessionId)}/abort").body<String>() }
191− }
192−
193− /** Invoke a slash-command by name via `POST /session/:id/command`. */
194− open suspend fun runCommand(
195− sessionId: String,
196− command: String,
197− arguments: String = "",
198− agent: String? = null,
199− ): MessageWithParts {
200− // Generate the idempotency key before entering withRetry so all retry
201− // attempts share the same key, preventing duplicate command execution if
202− // the server processed the request but the response was lost.
203− val idempotencyKey = java.util.UUID.randomUUID().toString()
204− return withRetry {
205− client!!.post("session/${encode(sessionId)}/command") {
206− contentType(ContentType.Application.Json)
207− header("Idempotency-Key", idempotencyKey)
208− setBody(CommandRequest(command = command, arguments = arguments, agent = agent))
209− }.body()
210− }
211− }
212−
213− /** Revert the session to just before [messageId] (optionally part [partId]); the
214− * server hides everything after the checkpoint. Returns the updated session. Naturally
215− * idempotent (reverting to the same point twice yields the same state). */
216− open suspend fun revert(sessionId: String, messageId: String, partId: String? = null): Session = withRetry {
217− client!!.post("session/${encode(sessionId)}/revert") {
218− contentType(ContentType.Application.Json)
219− setBody(RevertRequest(messageID = messageId, partID = partId))
220− }.body()
221− }
222−
223− /** Undo the active revert checkpoint, restoring the hidden messages. */
224− open suspend fun unrevert(sessionId: String): Session = withRetry {
225− client!!.post("session/${encode(sessionId)}/unrevert").body()
226− }
227−
228− /** Create a public share link for the session. Returns the session with [Session.share] set.
229− * Mint the Idempotency-Key *before* withRetry so a retried POST (first request reached the
230− * server but its response was lost) doesn't create a second, orphaned, still-valid share. */
231− open suspend fun shareSession(sessionId: String): Session {
232− val idempotencyKey = java.util.UUID.randomUUID().toString()
233− return withRetry {
234− client!!.post("session/${encode(sessionId)}/share") {
235− header("Idempotency-Key", idempotencyKey)
236− }.body()
237− }
238− }
239−
240− /** Revoke the session's public share link. Returns the session with share cleared.
241− * Like [deleteSession], a retried DELETE (first reached the server but the response was
242− * lost) hits an already-unshared session and gets 404 — revoking a non-shared session is
243− * effectively success, so swallow 404 rather than surfacing a spurious failure. */
244− open suspend fun unshareSession(sessionId: String): Session {
245− return try {
246− withRetry { client!!.delete("session/${encode(sessionId)}/share").body() }
247− } catch (t: ClientRequestException) {
248− if (t.response.status.value != 404) throw t
249− withRetry { client!!.get("session/${encode(sessionId)}").body() }
250− }
251− }
252−
253− /** Ask the agent to summarize/compact the conversation to reclaim context. The compacted
254− * summary streams back via SSE like any run; this just triggers it. */
255− open suspend fun summarize(sessionId: String, model: ModelRef) {
256− val idempotencyKey = java.util.UUID.randomUUID().toString()
257− withRetry {
258− client!!.post("session/${encode(sessionId)}/summarize") {
259− contentType(ContentType.Application.Json)
260− header("Idempotency-Key", idempotencyKey)
261− setBody(SummarizeRequest(providerID = model.providerID, modelID = model.modelID))
262− }.body<String>()
263− }
264− }
265−
266− /** Analyze the project and (re)generate its AGENTS.md. The body is omitted so the server
267− * assigns the message id and uses its default model; the run streams back via SSE. */
268− open suspend fun initSession(sessionId: String) {
269− val idempotencyKey = java.util.UUID.randomUUID().toString()
270− withRetry {
271− client!!.post("session/${encode(sessionId)}/init") {
272− header("Idempotency-Key", idempotencyKey)
273− }.body<String>()
274− }
275− }
276−
277− /** Run a one-off shell [command] in the session's worktree. Output streams back via SSE.
278− * [agent] scopes the run (the server requires it). */
279− open suspend fun shell(sessionId: String, command: String, agent: String, model: ModelRef? = null) {
280− val idempotencyKey = java.util.UUID.randomUUID().toString()
281− withRetry {
282− client!!.post("session/${encode(sessionId)}/shell") {
283− contentType(ContentType.Application.Json)
284− header("Idempotency-Key", idempotencyKey)
285− setBody(ShellRequest(agent = agent, command = command, model = model))
286− }.body<String>()
287− }
288− }
289−
290− open suspend fun providers(): ProvidersResponse {
291− val generation: Int
292− providersMutex.withLock {
293− val cached = cachedProviders
294− if (cached != null && System.currentTimeMillis() - cached.fetchedAt < NetworkConfig.catalogCacheTtlMs) {
295− return cached.value
296− }
297− generation = providersGeneration
298− }
299− // Fetch outside the lock so a slow/retrying request (and its backoff) can't stall other
300− // callers or cache invalidation. Concurrent cold callers may double-fetch — acceptable
301− // for a rarely-fetched catalog — and the last store wins.
302− val value = withRetry { client!!.get("config/providers").body<ProvidersResponse>() }
303− providersMutex.withLock {
304− // FIX 15: skip the store if an invalidateProvidersCache() raced this fetch — the
305− // result predates the invalidation and would otherwise resurrect stale data.
306− if (providersGeneration == generation) cachedProviders = CachedEntry(value, System.currentTimeMillis())
307− }
308− return value
309− }
310−
311− /** The server's resolved configuration as a raw JSON object. Parsed loosely by callers
312− * (e.g. the MCP viewer) so a schema addition on the server never breaks decoding. */
313− open suspend fun config(): kotlinx.serialization.json.JsonObject = withRetry {
314− client!!.get("config").body()
315− }
316−
317− /** Live MCP server status (`GET /mcp`): a map of server name to its status (connected,
318− * available tools, any error). Decoded as a raw JSON object so a schema change on the
319− * server never breaks the viewer. */
320− open suspend fun mcpStatus(): kotlinx.serialization.json.JsonObject = withRetry {
321− client!!.get("mcp").body()
322− }
323−
324− /** Dynamically register an MCP server (`POST /mcp`). [config] is the server's config object
325− * (type/command-or-url/env…), sent as `{ "name": [name], "config": [config] }`. Mint the
326− * Idempotency-Key *before* withRetry so a retried POST (first reached the server but the
327− * response was lost) doesn't register a duplicate. */
328− open suspend fun addMcp(name: String, config: kotlinx.serialization.json.JsonObject): kotlinx.serialization.json.JsonObject {
329− val idempotencyKey = java.util.UUID.randomUUID().toString()
330− return withRetry {
331− client!!.post("mcp") {
332− contentType(ContentType.Application.Json)
333− header("Idempotency-Key", idempotencyKey)
334− setBody(
335− buildJsonObject {
336− put("name", name)
337− put("config", config)
338− },
339− )
340− }.body()
341− }
342− }
343−
344− open suspend fun agents(): List<Agent> {
345− val generation: Int
346− agentsMutex.withLock {
347− val cached = cachedAgents
348− if (cached != null && System.currentTimeMillis() - cached.fetchedAt < NetworkConfig.catalogCacheTtlMs) {
349− return cached.value
350− }
351− generation = agentsGeneration
352− }
353− // Fetch outside the lock (see providers()): a slow/retrying request can't stall other
354− // callers or cache invalidation; a rare concurrent double-fetch is acceptable here.
355− val value = withRetry { client!!.get("agent").body<List<Agent>>() }
356− agentsMutex.withLock {
357− // FIX 15: skip the store if an invalidateAgentsCache() raced this fetch (see providers()).
358− if (agentsGeneration == generation) cachedAgents = CachedEntry(value, System.currentTimeMillis())
359− }
360− return value
361− }
362−
363− open suspend fun commands(): List<Command> {
364− val generation: Int
365− commandsMutex.withLock {
366− val cached = cachedCommands
367− if (cached != null && System.currentTimeMillis() - cached.fetchedAt < NetworkConfig.catalogCacheTtlMs) {
368− return cached.value
369− }
370− generation = commandsGeneration
371− }
372− // Fetch outside the lock (see providers()): a slow/retrying request can't stall other
373− // callers or cache invalidation; a rare concurrent double-fetch is acceptable here.
374− val value = withRetry { client!!.get("command").body<List<Command>>() }
375− commandsMutex.withLock {
376− // FIX 15: skip the store if an invalidateCommandsCache() raced this fetch (see providers()).
377− if (commandsGeneration == generation) cachedCommands = CachedEntry(value, System.currentTimeMillis())
378− }
379− return value
380− }
381−
382− /** Invalidate the catalog cache (e.g. on server switch). */
383− open suspend fun invalidateCache() {
384− // FIX 15: bump each generation so an in-flight fetch drops its now-stale result.
385− providersMutex.withLock { cachedProviders = null; providersGeneration++ }
386− agentsMutex.withLock { cachedAgents = null; agentsGeneration++ }
387− commandsMutex.withLock { cachedCommands = null; commandsGeneration++ }
388− }
389−
390− open suspend fun invalidateProvidersCache() {
391− providersMutex.withLock { cachedProviders = null; providersGeneration++ }
392− }
393−
394− open suspend fun invalidateAgentsCache() {
395− agentsMutex.withLock { cachedAgents = null; agentsGeneration++ }
396− }
397−
398− open suspend fun invalidateCommandsCache() {
399− commandsMutex.withLock { cachedCommands = null; commandsGeneration++ }
400− }
401−
402− /** Respond to a permission request so a paused tool run can proceed. */
403− open suspend fun respondPermission(
404− sessionId: String,
405− permissionId: String,
406− response: PermissionResponse,
407− ): String = try {
408− withRetry {
409− client!!.post("session/${encode(sessionId)}/permissions/${encode(permissionId)}") {
410− contentType(ContentType.Application.Json)
411− setBody(PermissionReplyBody(response.wire))
412− }.body<String>()
413− }
414− } catch (t: ClientRequestException) {
415− // A response that reached the server but whose reply was lost gets retried; the
416− // retry finds the permission already resolved (404 gone / 409 conflict). Both mean
417− // the answer landed, so treat them as success instead of a spurious failure.
418− val code = t.response.status.value
419− if (code != 404 && code != 409) throw t
420− ""
421− }
422−
423− // --- Files ---
424−
425− open suspend fun findFiles(query: String): List<String> = withRetry {
426− client!!.get("find/file") { parameter("query", query) }.body()
427− }
428−
429− /** Ripgrep content search across the project (`GET /find?pattern=`). */
430− open suspend fun findText(pattern: String): List<FindMatch> = withRetry {
431− client!!.get("find") { parameter("pattern", pattern) }.body()
432− }
433−
434− /** LSP workspace symbol search (`GET /find/symbol?query=`). */
435− open suspend fun findSymbol(query: String): List<SymbolResult> = withRetry {
436− client!!.get("find/symbol") { parameter("query", query) }.body()
437− }
438−
439− open suspend fun listDirectory(path: String): List<FileNode> = withRetry {
440− client!!.get("file") { parameter("path", path) }.body()
441− }
442−
443− open suspend fun readFile(path: String): FileContent = withRetry {
444− client!!.get("file/content") { parameter("path", path) }.body()
445− }
446−
447− open suspend fun fileStatus(): List<FileStatusEntry> = withRetry {
448− client!!.get("file/status").body()
449− }
450−}
451−
452−private suspend fun <T> withRetry(
453− maxAttempts: Int = NetworkConfig.retryMaxAttempts,
454− initialDelayMs: Long = NetworkConfig.retryInitialDelayMs,
455− block: suspend () -> T,
456−): T = withRetryInternal(maxAttempts, initialDelayMs, jitterFactor = NetworkConfig.retryJitterFactor, block)
457−
458−/**
459− * Retry a suspending block up to [maxAttempts] times with exponential backoff.
460− * Cancellation exceptions are re-thrown immediately. Client errors (4xx) are
461− * non-retryable — a 401 or 404 won't succeed on retry, so they surface immediately
462− * instead of wasting up to 3.5 s of backoff. Network failures, timeouts, and 5xx
463− * server errors are retried. Exposed as `internal` so the retry/skip rules are
464− * unit-testable without an HTTP server.
465− */
466−internal suspend fun <T> withRetryInternal(
467− maxAttempts: Int = NetworkConfig.retryMaxAttempts,
468− initialDelayMs: Long = NetworkConfig.retryInitialDelayMs,
469− jitterFactor: Double = NetworkConfig.retryJitterFactor,
470− block: suspend () -> T,
471−): T {
472− var lastError: Throwable? = null
473− for (attempt in 1..maxAttempts) {
474− try {
475− return block()
476− } catch (c: kotlinx.coroutines.CancellationException) {
477− throw c
478− } catch (t: ClientRequestException) {
479− // 408 (Request Timeout) and 429 (Too Many Requests) are transient — retry with
480− // backoff. All other 4xx are non-retryable (a 401/404 won't succeed on retry).
481− val status = t.response.status.value
482− if (status != 408 && status != 429) throw t
483− lastError = t
484− if (attempt < maxAttempts) {
485− delay(jitteredBackoff(attempt, initialDelayMs, jitterFactor))
486− }
487− } catch (t: ServerResponseException) {
488− // 5xx server errors are retryable with backoff.
489− lastError = t
490− if (attempt < maxAttempts) {
491− delay(jitteredBackoff(attempt, initialDelayMs, jitterFactor))
492− }
493− } catch (t: ResponseException) {
494− // 3xx (redirect limit exceeded) is non-retryable.
495− throw t
496− } catch (t: io.ktor.serialization.ContentConvertException) {
497− // A malformed/unexpected response body (deserialization failure via content
498− // negotiation) is deterministic — it fails identically on every attempt — so
499− // retrying only burns the whole backoff budget re-parsing the same bytes. Fail
500− // fast instead.
501− throw t
502− } catch (t: IllegalArgumentException) {
503− // Also deterministic: a bad argument, or a raw kotlinx SerializationException
504− // (which extends IllegalArgumentException) thrown outside content negotiation.
505− throw t
506− } catch (t: Exception) {
507− lastError = t
508− if (attempt < maxAttempts) {
509− delay(jitteredBackoff(attempt, initialDelayMs, jitterFactor))
510− }
511− }
512− }
513− throw lastError ?: IllegalStateException("withRetry failed without error")
514−}
515−
516−/** Computes an exponential backoff delay with symmetric jitter. Exposed as `internal`
517− * so the backoff formula is unit-testable without an HTTP server. */
518−internal fun jitteredBackoff(
519− attempt: Int,
520− initialDelayMs: Long,
521− jitterFactor: Double,
522−): Long {
523− // Guard against Int overflow from the shift and Long overflow from
524− // the multiplication at high attempt counts.
525− val shift = (attempt - 1).coerceAtMost(30)
526− val baseDelay = (initialDelayMs * (1L shl shift)).coerceAtMost(NetworkConfig.retryMaxDelayMs)
527− // Symmetric jitter: vary by ±jitterFactor so the delay is sometimes
528− // shorter, sometimes longer — spreads concurrent client retries and
529− // prevents thundering-herd reconnection storms.
530− val jitter = ((baseDelay * jitterFactor) * (Random.nextDouble() * 2 - 1)).toLong()
531− return (baseDelay + jitter).coerceAtLeast(0)
532−}
533−
534−/** URL-encode a path segment, replacing + with %20 (URLEncoder uses query-param encoding).
535− * URLEncoder leaves '.' unencoded, so a "." or ".." segment would otherwise survive as a real
536− * path-traversal component; percent-encode a segment that is nothing but dots. */
537−private fun encode(segment: String): String {
538− val encoded = URLEncoder.encode(segment, "UTF-8").replace("+", "%20")
539− return if (encoded.isNotEmpty() && encoded.all { it == '.' }) encoded.replace(".", "%2E") else encoded
540−}
app/src/main/java/soy/iko/opencode/data/network/OpencodeJson.ktdeleted−37
@@ -1,37 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.BusEvent
4−import soy.iko.opencode.data.model.MessageInfo
5−import soy.iko.opencode.data.model.Part
6−import soy.iko.opencode.data.model.ToolState
7−import soy.iko.opencode.data.model.UnknownEvent
8−import soy.iko.opencode.data.model.UnknownMessage
9−import soy.iko.opencode.data.model.UnknownPart
10−import soy.iko.opencode.data.model.ToolUnknown
11−import kotlinx.serialization.ExperimentalSerializationApi
12−import kotlinx.serialization.json.Json
13−import kotlinx.serialization.modules.SerializersModule
14−
15−/**
16− * Single shared Json for the whole app.
17− *
18− * The polymorphic default deserializers are the resilience layer: when the server
19− * sends a `type` / `role` / `status` we don't model, decoding falls back to the
20− * Unknown variant instead of throwing — so a new opencode release can't break the
21− * event stream or message decoding.
22− */
23−@OptIn(ExperimentalSerializationApi::class)
24−val OpencodeJson: Json = Json {
25− ignoreUnknownKeys = true
26− isLenient = true
27− coerceInputValues = true
28− encodeDefaults = true
29− explicitNulls = false
30− classDiscriminator = "type"
31− serializersModule = SerializersModule {
32− polymorphicDefaultDeserializer(Part::class) { UnknownPart.serializer() }
33− polymorphicDefaultDeserializer(BusEvent::class) { UnknownEvent.serializer() }
34− polymorphicDefaultDeserializer(MessageInfo::class) { UnknownMessage.serializer() }
35− polymorphicDefaultDeserializer(ToolState::class) { ToolUnknown.serializer() }
36− }
37−}
app/src/main/java/soy/iko/opencode/data/repo/AttachmentDraftStore.ktdeleted−114
@@ -1,114 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.sync.Mutex
7−import kotlinx.coroutines.sync.withLock
8−import kotlinx.coroutines.withContext
9−import kotlinx.serialization.Serializable
10−import kotlinx.serialization.decodeFromString
11−import kotlinx.serialization.encodeToString
12−import kotlinx.serialization.json.Json
13−import soy.iko.opencode.util.runCatchingCancellable
14−import java.io.File
15−
16−/**
17− * One staged (not-yet-sent) attachment, in the minimal form needed to re-send and preview
18− * it after a process restart. Only the self-contained wire payload is kept — the base64
19− * `data:` [url] — because the original content Uri's read permission does NOT survive a
20− * process restart, whereas the data URL is self-sufficient (and Coil re-renders it as the
21− * thumbnail for images).
22− */
23−@Serializable
24−data class PersistedAttachment(
25− val id: String,
26− val name: String,
27− val mime: String,
28− val url: String,
29− val filename: String? = null,
30−)
31−
32−/**
33− * Persists attachments staged for each session so an interrupted compose survives process
34− * death, mirroring how [DraftStore] persists the text draft.
35− *
36− * Backed by one small JSON file per session under filesDir (not cacheDir, which the OS may
37− * evict) rather than SharedPreferences: a base64 payload can be several megabytes and
38− * SharedPreferences loads its whole file into memory on first access.
39− */
40−open class AttachmentDraftStore private constructor(
41− private val appContext: Context?,
42− @Suppress("unused") private val testMode: Boolean,
43−) {
44− constructor(context: Context) : this(context.applicationContext, false)
45− protected constructor() : this(null, true)
46−
47− private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
48−
49− /** Session ids are validated tokens upstream, but sanitize anyway so a stray id can't
50− * escape the directory. */
51− private val idRegex = Regex("[^A-Za-z0-9_-]")
52−
53− private val dir: File? by lazy {
54− appContext?.let { File(it.filesDir, "attachment_drafts").apply { mkdirs() } }
55− }
56−
57− private fun fileFor(sessionId: String): File? =
58− dir?.let { File(it, idRegex.replace(sessionId, "_") + ".json") }
59−
60− /** Per-session write lock so rapid add/remove/clear mutations (each launched as an
61− * independent coroutine by the ViewModel) serialize their writes to the same file
62− * instead of racing — otherwise an older snapshot could land last and overwrite the
63− * newer one on disk, or two writes could tear the file. */
64− private val locks = java.util.concurrent.ConcurrentHashMap<String, Mutex>()
65− private fun lockFor(sessionId: String): Mutex = locks.getOrPut(sessionId) { Mutex() }
66−
67− /** Load the staged attachments for [sessionId], or empty if none / unreadable. */
68− open suspend fun load(sessionId: String): List<PersistedAttachment> = lockFor(sessionId).withLock {
69− withContext(Dispatchers.IO) {
70− val file = fileFor(sessionId)?.takeIf { it.exists() } ?: return@withContext emptyList()
71− runCatchingCancellable { json.decodeFromString<List<PersistedAttachment>>(file.readText()) }
72− .getOrDefault(emptyList())
73− }
74− }
75−
76− /** Persist [attachments] for [sessionId] (an empty list deletes the file). */
77− open suspend fun save(sessionId: String, attachments: List<PersistedAttachment>): Unit = lockFor(sessionId).withLock {
78− withContext(Dispatchers.IO) {
79− val file = fileFor(sessionId) ?: return@withContext
80− runCatchingCancellable {
81− if (attachments.isEmpty()) file.delete()
82− else {
83− // FIX: write atomically (temp file + rename) like RecentSessionsStore so a
84− // process kill mid-write can't leave a truncated file that fails to decode
85− // and silently drops the staged attachments on reload.
86− val encoded = json.encodeToString(attachments)
87− val tmp = File(file.parentFile, file.name + ".tmp")
88− tmp.writeText(encoded)
89− if (!tmp.renameTo(file)) {
90− file.writeText(encoded)
91− tmp.delete()
92− }
93− }
94− }.onFailure { Log.w("AttachmentDraftStore", "Failed to persist attachments for $sessionId", it) }
95− Unit
96− }
97− }
98−
99− /** Remove staged attachments for a session (call on session deletion). */
100− open suspend fun remove(sessionId: String) {
101− // Keep the per-session Mutex in [locks] rather than evicting it: remove() is not always
102− // terminal — a concurrent teardown save() for the same session must serialize against this
103− // delete under the *same* Mutex instance. Evicting here would let that save() acquire a
104− // fresh Mutex, so the two operations no longer serialize (resurrecting an orphan file, or
105− // theoretically tearing a write). The bounded per-session map growth matches the other
106− // lock-keyed stores.
107− lockFor(sessionId).withLock {
108− withContext(Dispatchers.IO) {
109− runCatchingCancellable { fileFor(sessionId)?.delete() }
110− Unit
111− }
112− }
113− }
114−}
app/src/main/java/soy/iko/opencode/data/repo/BackupManager.ktdeleted−199
@@ -1,199 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import kotlinx.coroutines.flow.first
4−import kotlinx.serialization.Serializable
5−import kotlinx.serialization.decodeFromString
6−import kotlinx.serialization.encodeToString
7−import kotlinx.serialization.json.Json
8−import soy.iko.opencode.data.model.ServerProfile
9−
10−/** A server entry in a backup. [password] is present only when the user opted to include it. */
11−@Serializable
12−data class BackupServer(
13− val id: String,
14− val label: String,
15− val baseUrl: String,
16− val username: String? = null,
17− val password: String? = null,
18− val requireHttps: Boolean = false,
19− val certPin: String? = null,
20−)
21−
22−/** App preferences in a backup. */
23−@Serializable
24−data class BackupSettings(
25− // Every field is defaulted (to SettingsStore's own defaults) so a backup written by an older
26− // app version — one whose settings block predates a field added later — still decodes. Without
27− // defaults a missing field throws MissingFieldException in import() BEFORE the server-restore
28− // loop, aborting the ENTIRE restore (servers/pins/archives included) despite the best-effort
29− // contract. ignoreUnknownKeys only tolerates EXTRA keys, not missing required ones.
30− val themeMode: String = ThemeMode.SYSTEM.name,
31− val dynamicColor: Boolean = false,
32− val sendOnEnter: Boolean = true,
33− val appLock: Boolean = false,
34− val appLockReLockSeconds: Int = SettingsStore.DEFAULT_APP_LOCK_RELOCK_SECONDS,
35− val chatTextScale: Float = SettingsStore.DEFAULT_CHAT_TEXT_SCALE,
36− val codeWrap: Boolean = false,
37− val sessionSortMode: String = "RECENT",
38− val sessionSortDescending: Boolean = true,
39− val sessionShowArchived: Boolean = false,
40− val preferredModelId: String = "",
41− val preferredAgentName: String = "",
42− val compactMessageSpacing: Boolean = false,
43− val hapticsEnabled: Boolean = true,
44− val reducedMotion: Boolean = false,
45− val languageOverride: String = "",
46− val notifRunComplete: Boolean = true,
47− val notifPermission: Boolean = true,
48− val notifError: Boolean = true,
49− val swipeLeftAction: String = SwipeAction.DELETE.name,
50− val swipeRightAction: String = SwipeAction.ARCHIVE.name,
51−)
52−
53−/** The full backup document. [version] guards against future format changes. */
54−@Serializable
55−data class BackupData(
56− val version: Int = 1,
57− val servers: List<BackupServer> = emptyList(),
58− val settings: BackupSettings? = null,
59− val pinned: List<String> = emptyList(),
60− val archived: List<String> = emptyList(),
61−)
62−
63−/**
64− * Exports/imports the app's servers, settings, and per-session flags as a single JSON
65− * document (via the Storage Access Framework in the UI). Passwords are only written when the
66− * user explicitly opts in, since the exported file is plaintext and leaves the app's encrypted
67− * store.
68− */
69−class BackupManager(
70− private val profileStore: ProfileStore,
71− private val settingsStore: SettingsStore,
72− private val sessionPrefsStore: SessionPrefsStore,
73−) {
74− private val json = Json { prettyPrint = true; ignoreUnknownKeys = true; encodeDefaults = true }
75−
76− /** Build the backup JSON. Reads the current profiles/settings/flags. */
77− suspend fun export(includePasswords: Boolean): String {
78− val servers = profileStore.profiles.first().map {
79− BackupServer(
80− id = it.id,
81− label = it.label,
82− baseUrl = it.baseUrl,
83− username = it.username,
84− password = if (includePasswords) it.password else null,
85− requireHttps = it.requireHttps,
86− certPin = it.certPin,
87− )
88− }
89− val settings = BackupSettings(
90− themeMode = settingsStore.themeMode.first().name,
91− dynamicColor = settingsStore.dynamicColor.first(),
92− sendOnEnter = settingsStore.sendOnEnter.first(),
93− appLock = settingsStore.appLock.first(),
94− appLockReLockSeconds = settingsStore.appLockReLockSeconds.first(),
95− chatTextScale = settingsStore.chatTextScale.first(),
96− codeWrap = settingsStore.codeWrap.first(),
97− sessionSortMode = settingsStore.sessionSortMode.first(),
98− sessionSortDescending = settingsStore.sessionSortDescending.first(),
99− sessionShowArchived = settingsStore.sessionShowArchived.first(),
100− preferredModelId = settingsStore.preferredModelId.first(),
101− preferredAgentName = settingsStore.preferredAgentName.first(),
102− compactMessageSpacing = settingsStore.compactMessageSpacing.first(),
103− hapticsEnabled = settingsStore.hapticsEnabled.first(),
104− reducedMotion = settingsStore.reducedMotion.first(),
105− languageOverride = settingsStore.languageOverride.first(),
106− notifRunComplete = settingsStore.notifRunComplete.first(),
107− notifPermission = settingsStore.notifPermission.first(),
108− notifError = settingsStore.notifError.first(),
109− swipeLeftAction = settingsStore.swipeLeftAction.first(),
110− swipeRightAction = settingsStore.swipeRightAction.first(),
111− )
112− val data = BackupData(
113− servers = servers,
114− settings = settings,
115− pinned = sessionPrefsStore.pinned.first().toList(),
116− archived = sessionPrefsStore.archived.first().toList(),
117− )
118− return json.encodeToString(data)
119− }
120−
121− /** Apply a backup document. Throws on malformed JSON so the caller can report it. Servers
122− * are upserted (existing ids overwritten); settings and flags are restored best-effort. */
123− suspend fun import(text: String) {
124− val data = json.decodeFromString<BackupData>(text)
125− for (s in data.servers) {
126− val username = s.username?.takeIf { it.isNotBlank() }
127− val incomingPassword = s.password?.takeIf { it.isNotEmpty() }
128− // A backup exported *without* passwords carries null. This is an upsert, so don't let
129− // that null wipe a password already stored for this server id — preserve the existing
130− // secret when the backup didn't include one (only the backup explicitly carrying a
131− // password should overwrite it). Re-importing a password-less backup would otherwise
132− // silently break auth for every matching server.
133− val password = incomingPassword ?: username?.let {
134− profileStore.resolve(
135− ServerProfile(id = s.id, label = s.label, baseUrl = s.baseUrl, username = it),
136− ).password
137− }
138− profileStore.save(
139− ServerProfile(
140− id = s.id,
141− label = s.label,
142− baseUrl = s.baseUrl,
143− username = username,
144− password = password,
145− lastUsed = 0,
146− requireHttps = s.requireHttps,
147− certPin = s.certPin?.takeIf { it.isNotBlank() },
148− ),
149− )
150− }
151− data.settings?.let { settings ->
152− // Parse the enum defensively (a bad name from an edited backup shouldn't abort the
153− // import) WITHOUT wrapping the suspend setThemeMode call — wrapping it would swallow
154− // a CancellationException and break structured concurrency.
155− ThemeMode.entries.find { it.name == settings.themeMode }?.let { settingsStore.setThemeMode(it) }
156− settingsStore.setDynamicColor(settings.dynamicColor)
157− settingsStore.setSendOnEnter(settings.sendOnEnter)
158− settingsStore.setAppLock(settings.appLock)
159− settingsStore.setAppLockReLockSeconds(settings.appLockReLockSeconds)
160− settingsStore.setChatTextScale(settings.chatTextScale)
161− settingsStore.setCodeWrap(settings.codeWrap)
162− // sessionSortMode is written below, AFTER validation against the known enum
163− // entries — do NOT write it unconditionally here, or a garbage string from a
164− // hand-edited/malicious backup would persist with no in-app reset path (the
165− // validated write below only fires when the enum is found, so an earlier
166− // unconditional write would leave the corrupt value in place when it's not).
167− settingsStore.setSessionSortDescending(settings.sessionSortDescending)
168− settingsStore.setSessionShowArchived(settings.sessionShowArchived)
169− settingsStore.setPreferredModelId(settings.preferredModelId)
170− settingsStore.setPreferredAgentName(settings.preferredAgentName)
171− settingsStore.setCompactMessageSpacing(settings.compactMessageSpacing)
172− settingsStore.setHapticsEnabled(settings.hapticsEnabled)
173− settingsStore.setReducedMotion(settings.reducedMotion)
174− // Validate the sort mode against the known enum entries before persisting, so a
175− // garbage string from a hand-edited/malicious backup can't produce a broken sort
176− // with no in-app reset path (the picker writes known values, but a corrupt one
177− // would persist and leave the list in an undefined order). Mirrors the defensive
178− // enum parsing used for themeMode and swipe actions above.
179− soy.iko.opencode.ui.session.SessionSortMode.entries
180− .find { it.name == settings.sessionSortMode }
181− ?.let { settingsStore.setSessionSortMode(it.name) }
182− // Validate the language override is a plausible ISO 639-1 code (2–3 lowercase
183− // letters, optionally with a region/script subtag) before persisting, so a bad
184− // string doesn't reach AppCompat's per-app language API. Empty (system default)
185− // is always allowed.
186− val lang = settings.languageOverride
187− if (lang.isEmpty() || lang.matches(Regex("^[a-z]{2,3}(-[A-Za-z0-9]+)*$"))) {
188− settingsStore.setLanguageOverride(lang)
189− }
190− settingsStore.setNotifRunComplete(settings.notifRunComplete)
191− settingsStore.setNotifPermission(settings.notifPermission)
192− settingsStore.setNotifError(settings.notifError)
193− SwipeAction.entries.find { it.name == settings.swipeLeftAction }?.let { settingsStore.setSwipeLeftAction(it) }
194− SwipeAction.entries.find { it.name == settings.swipeRightAction }?.let { settingsStore.setSwipeRightAction(it) }
195− }
196− data.pinned.forEach { sessionPrefsStore.setPinned(it, true) }
197− data.archived.forEach { sessionPrefsStore.setArchived(it, true) }
198− }
199−}
app/src/main/java/soy/iko/opencode/data/repo/CrashLogger.ktdeleted−288
@@ -1,288 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.content.pm.PackageManager
5−import android.os.Build
6−import android.util.Log
7−import androidx.core.content.pm.PackageInfoCompat
8−import kotlinx.coroutines.CoroutineScope
9−import kotlinx.coroutines.Dispatchers
10−import kotlinx.coroutines.Job
11−import kotlinx.coroutines.SupervisorJob
12−import kotlinx.coroutines.cancel
13−import kotlinx.coroutines.delay
14−import kotlinx.coroutines.flow.MutableStateFlow
15−import kotlinx.coroutines.flow.StateFlow
16−import kotlinx.coroutines.flow.asStateFlow
17−import kotlinx.coroutines.launch
18−import java.io.File
19−import java.io.PrintWriter
20−import java.io.StringWriter
21−import java.text.SimpleDateFormat
22−import java.util.Date
23−import java.util.Locale
24−import soy.iko.opencode.util.runCatchingCancellable
25−
26−/**
27− * A self-contained crash reporter with no network or third-party backend. An uncaught
28− * exception is written to app-private storage ([Context.filesDir]/crashes) as a plain
29− * text report (timestamp, device/app metadata, and the full stack trace), then the
30− * previous handler is re-invoked so the process still dies normally.
31− *
32− * Reports are surfaced in the in-app Diagnostics screen, where they can be viewed,
33− * shared, or deleted. This closes the "no idea what's crashing in the field" gap
34− * without pulling in a hosted analytics SDK.
35− */
36−class CrashLogger private constructor(private val appContext: Context) {
37−
38− data class CrashReport(
39− val fileName: String,
40− val timestamp: Long,
41− val preview: String,
42− )
43−
44− private val crashDir = File(appContext.filesDir, "crashes").apply { mkdirs() }
45− private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
46− private val crashPrefs = appContext.getSharedPreferences("crash_logger", android.content.Context.MODE_PRIVATE)
47−
48− private val _reports = MutableStateFlow<List<CrashReport>>(emptyList())
49− val reports: StateFlow<List<CrashReport>> = _reports.asStateFlow()
50−
51− fun install() {
52− val previous = Thread.getDefaultUncaughtExceptionHandler()
53− Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
54− runCatching { writeReport(thread, throwable) }
55− .onFailure { Log.e("CrashLogger", "Failed to write crash report", it) }
56− previous?.uncaughtException(thread, throwable)
57− }
58− // Load crash reports off the main thread so startup isn't blocked by file I/O
59− // (listFiles + reading the first line of each report). The StateFlow updates
60− // whenever the scan completes, so the Diagnostics screen reflects the result.
61− scope.launch { runCatchingCancellable { refresh() } }
62− }
63−
64− /** Monotonic guard so a slower earlier scan can't overwrite a newer one's result.
65− * refresh() runs on the multi-threaded IO dispatcher from several call sites
66− * (install/deleteReport/scheduleDelete/clearAll), so two scans can overlap. */
67− private val refreshGeneration = java.util.concurrent.atomic.AtomicLong(0)
68−
69− fun refresh() {
70− val generation = refreshGeneration.incrementAndGet()
71− val scanned = crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }
72− ?.sortedByDescending { it.lastModified() }
73− ?.map { f ->
74− CrashReport(
75− fileName = f.name,
76− timestamp = f.lastModified(),
77− preview = runCatching { f.useLines { it.firstOrNull() ?: "" } }.getOrDefault(""),
78− )
79− }
80− .orEmpty()
81− // Publish only if no newer refresh has started meanwhile, so a stale scan (e.g. one
82− // that started before a delete) can't momentarily re-show a just-removed report.
83− if (generation == refreshGeneration.get()) _reports.value = scanned
84− }
85−
86− fun readReport(fileName: String): String? {
87− val file = File(crashDir, fileName).canonicalFile
88− if (!file.path.startsWith(crashDir.canonicalPath + File.separator) || !file.isFile) return null
89− return runCatching { file.readText() }.getOrNull()
90− }
91−
92− fun deleteReport(fileName: String) {
93− scope.launch {
94− val file = File(crashDir, fileName).canonicalFile
95− if (file.path.startsWith(crashDir.canonicalPath + File.separator)) {
96− file.delete()
97− }
98− refresh()
99− }
100− }
101−
102− /** Whether any crash report is newer than the last-acknowledged timestamp — i.e. a
103− * crash happened in a previous run that the user hasn't been prompted about yet.
104− * Called on cold start to surface a "crashed last time" dialog. */
105− fun hasUnacknowledgedCrash(): Boolean {
106− val acknowledgedAt = crashPrefs.getLong(KEY_ACKNOWLEDGED_AT, 0L)
107− return crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }
108− ?.any { it.lastModified() > acknowledgedAt } == true
109− }
110−
111− /** Mark all current crash reports as acknowledged so the cold-start prompt doesn't
112− * re-fire on the next launch. */
113− fun acknowledgeCrashes() {
114− crashPrefs.edit().putLong(KEY_ACKNOWLEDGED_AT, System.currentTimeMillis()).apply()
115− }
116−
117− /** Deferred deletions keyed by file name, so an Undo can cancel one before it fires. */
118− private val pendingDeletes = java.util.concurrent.ConcurrentHashMap<String, Job>()
119−
120− /**
121− * Schedule [fileName] for deletion after [delayMs], cancellable via
122− * [cancelScheduledDelete]. Runs on the logger's own long-lived scope — not the
123− * Diagnostics screen's composition scope — so navigating away during the undo window
124− * still commits the delete instead of silently dropping it. A repeated schedule for
125− * the same name replaces the prior timer.
126− */
127− fun scheduleDelete(fileName: String, delayMs: Long) {
128− val job = scope.launch {
129− delay(delayMs)
130− // Atomically claim the delete by removing our own map entry BEFORE deleting.
131− // The remove is the synchronization point with cancelScheduledDelete: whichever
132− // removes the entry first wins. If an undo raced the timer and removed it first,
133− // this returns false and we skip the delete — so the file survives, matching the
134− // `true` that cancel returned to the UI. Deleting first (then removing) would let
135− // a cancel land in the gap and falsely report "undo succeeded" for a gone file.
136− // remove(name, thisJob) also no-ops for a stale job after a reschedule.
137− val claimed = coroutineContext[Job]?.let { pendingDeletes.remove(fileName, it) } == true
138− if (!claimed) return@launch
139− val file = File(crashDir, fileName).canonicalFile
140− if (file.path.startsWith(crashDir.canonicalPath + File.separator)) {
141− file.delete()
142− }
143− refresh()
144− }
145− pendingDeletes.put(fileName, job)?.cancel()
146− }
147−
148− /** Cancel a pending deferred delete (the Undo action). Returns true if it was still
149− * pending (undo succeeded), false if the delete had already fired. */
150− fun cancelScheduledDelete(fileName: String): Boolean {
151− val job = pendingDeletes.remove(fileName) ?: return false
152− job.cancel()
153− return true
154− }
155−
156− fun clearAll() {
157− scope.launch {
158− crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }?.forEach { it.delete() }
159− refresh()
160− }
161− }
162−
163− /** Deferred whole-directory clear, cancellable via [cancelScheduledClearAll] so the bulk
164− * action gets the same undo window as a single-report delete. Runs on the logger's own
165− * scope so it commits even if the user leaves the Diagnostics screen. */
166− // @Volatile: the flag is read/written from both the UI thread (schedule/cancel calls
167− // from the Diagnostics screen) and the IO coroutine (which nulls it when the timer
168− // fires). Without @Volatile the IO write isn't guaranteed visible to the UI thread's
169− // cancel read — a data race that could let a cancel falsely report "already fired".
170− // The sibling pendingDeletes map uses ConcurrentHashMap for the same reason.
171− @Volatile
172− private var pendingClearAll: Job? = null
173−
174− fun scheduleClearAll(delayMs: Long) {
175− pendingClearAll?.cancel()
176− pendingClearAll = scope.launch {
177− delay(delayMs)
178− // Claim the clear by nulling our entry BEFORE deleting, mirroring
179− // scheduleDelete's claim pattern: whichever nulls first wins. A concurrent
180− // cancelScheduledClearAll that nulls first makes this a no-op.
181− pendingClearAll = null
182− crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }?.forEach { it.delete() }
183− refresh()
184− }
185− }
186−
187− /** Cancel a pending clear-all (the Undo action). Returns true if it was still pending. */
188− fun cancelScheduledClearAll(): Boolean {
189− // Read and null under the volatile read; cancel the captured job after. A
190− // compareAndSet loop would be ideal but Job identity is enough here: if we read
191− // non-null, null it, and cancel it, the launched coroutine's pendingClearAll =
192− // null is a no-op on an already-nulled field. If the coroutine already nulled it
193− // (timer fired) we read null and return false — the authoritative answer.
194− val job = pendingClearAll ?: return false
195− pendingClearAll = null
196− job.cancel()
197− return true
198− }
199−
200− fun reportCount(): Int = _reports.value.size
201−
202− /** Cancel the internal coroutine scope so background work doesn't outlive the
203− * process. Called from [AppContainer.shutdown]. The UncaughtExceptionHandler is
204− * intentionally left installed — a crash during shutdown still needs to be logged. */
205− fun shutdown() {
206− scope.cancel()
207− }
208−
209− private fun writeReport(thread: Thread, throwable: Throwable) {
210− val now = Date()
211− val stamp = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS", Locale.US).format(now)
212− // Append a short random suffix so two crashes in the same millisecond don't
213− // overwrite each other.
214− val suffix = java.lang.Long.toHexString(System.nanoTime())
215− val file = File(crashDir, "crash-$stamp-$suffix.txt")
216− val sw = StringWriter()
217− PrintWriter(sw).use { pw ->
218− pw.println("opencode-android crash report")
219− pw.println("Time: ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US).format(now)}")
220− pw.println("Thread: ${thread.name}")
221− pw.println("App version: ${appVersion()}")
222− pw.println("Device: ${Build.MANUFACTURER} ${Build.MODEL}")
223− pw.println("Android: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
224− pw.println("ABI: ${Build.SUPPORTED_ABIS.joinToString()}")
225− pw.println()
226− pw.println(throwable.javaClass.name + ": " + throwable.message)
227− throwable.printStackTrace(pw)
228− }
229− // Scrub URLs from the *entire* report. printStackTrace re-emits the exception
230− // message (and every "Caused by:" message) verbatim, so scrubbing only the
231− // top-level message above is futile — Ktor/OkHttp embed the full request URL
232− // in those messages, which may contain auth or internal paths. Scrubbing the
233− // assembled text guarantees no URL survives anywhere in the stored report.
234− file.writeText(scrubUrls(sw.toString()))
235− trimOldReports()
236− }
237−
238− /** Keep only the [MAX_REPORTS] most recent crash reports, deleting older ones. Runs inside
239− * the uncaught-exception handler (the whole call is wrapped in runCatching upstream), so it
240− * must not throw; each delete is guarded. */
241− private fun trimOldReports() {
242− val files = crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") } ?: return
243− if (files.size <= MAX_REPORTS) return
244− files.sortedByDescending { it.lastModified() }
245− .drop(MAX_REPORTS)
246− .forEach { runCatching { it.delete() } }
247− }
248−
249− private fun appVersion(): String = runCatching {
250− val pi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
251− appContext.packageManager.getPackageInfo(
252− appContext.packageName,
253− PackageManager.PackageInfoFlags.of(0),
254− )
255− } else {
256− @Suppress("DEPRECATION")
257− appContext.packageManager.getPackageInfo(appContext.packageName, 0)
258− }
259− "${pi.versionName} (${PackageInfoCompat.getLongVersionCode(pi)})"
260− }.getOrDefault("unknown")
261−
262− companion object {
263− /** Cap on retained crash report files. A deterministic crash-loop (e.g. a crash on
264− * startup) writes one report per crash with no other bound, so without this the
265− * crashes/ dir grows without limit until the user manually clears it. */
266− private const val MAX_REPORTS = 20
267−
268− private const val KEY_ACKNOWLEDGED_AT = "acknowledged_at"
269−
270− /** Regex matching http(s) URLs, shared by report writing and [scrubUrls]. */
271− internal val SCRUB_URL_REGEX = Regex("https?://[^\\s\"']+")
272−
273− /**
274− * Replace every http(s) URL in [text] with `[url]`. Exposed as `internal` so the
275− * redaction (used on the whole crash report, including exception messages and
276− * stack traces produced by printStackTrace) can be unit-tested in isolation.
277− */
278− internal fun scrubUrls(text: String): String = SCRUB_URL_REGEX.replace(text, "[url]")
279−
280− @Volatile
281− private var instance: CrashLogger? = null
282−
283− fun get(context: Context): CrashLogger =
284− instance ?: synchronized(this) {
285− instance ?: CrashLogger(context.applicationContext).also { instance = it }
286− }
287− }
288−}
app/src/main/java/soy/iko/opencode/data/repo/DraftStore.ktdeleted−266
@@ -1,266 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.CoroutineScope
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.flow.MutableStateFlow
7−import kotlinx.coroutines.flow.StateFlow
8−import kotlinx.coroutines.flow.asStateFlow
9−import kotlinx.coroutines.flow.update
10−import android.util.Log
11−import kotlinx.coroutines.launch
12−import soy.iko.opencode.util.runCatchingCancellable
13−import java.util.concurrent.Executors
14−
15−/**
16− * Persists the in-progress message draft for each session so it survives
17− * back-navigation and process death. Backed by SharedPreferences because the
18− * UI needs the initial value synchronously and drafts are low-stakes data.
19− *
20− * The prefs file is loaded on a background thread at construction time. Until
21− * the load completes, [drafts] reports an empty map and [get] returns "" rather
22− * than blocking the caller (previously a [CountDownLatch] could stall the main
23− * thread for up to 2 seconds on a slow disk).
24− */
25−open class DraftStore private constructor(
26− private val appContext: Context?,
27− private val scope: CoroutineScope?,
28− @Suppress("unused") private val testMode: Boolean,
29−) {
30− constructor(context: Context, scope: CoroutineScope) : this(context.applicationContext, scope, false)
31− protected constructor() : this(null, null, true)
32−
33− private val prefs by lazy {
34− appContext?.getSharedPreferences("drafts", Context.MODE_PRIVATE)
35− ?: error("No context — override methods in test subclass")
36− }
37−
38− /** Single-thread executor for flushDraft when prefs aren't initialized yet,
39− * so the main thread is never blocked on disk I/O. */
40− private val flushExecutor by lazy {
41− Executors.newSingleThreadExecutor { r ->
42− Thread(r, "DraftStore-flush").apply { isDaemon = true }
43− }
44− }
45−
46− private val _drafts = MutableStateFlow<Map<String, String>>(emptyMap())
47− /** The full in-memory snapshot of all drafts, updated when prefs finish loading. */
48− open val drafts: StateFlow<Map<String, String>> = _drafts.asStateFlow()
49−
50− /** Queued follow-up messages per session, persisted under a namespaced key so a
51− * follow-up queued mid-run survives process death (the in-memory-only StateFlow in
52− * ChatViewModel would otherwise lose it, along with the cleared draft). */
53− private val _followUps = MutableStateFlow<Map<String, String>>(emptyMap())
54−
55− private val _ready = MutableStateFlow(false)
56− /** True once the background prefs load has completed. */
57− open val ready: StateFlow<Boolean> = _ready.asStateFlow()
58−
59− /** Keys written in-memory (set / cleared / removed) *before* the async prefs load
60− * finished. For these the in-memory state is authoritative — the load must not
61− * resurrect a persisted value the user has since cleared, which a plain putAll(current)
62− * merge cannot express (it can add/override, but not delete). Consulted once, in the
63− * init merge. Separate sets because drafts and follow-ups share the session-id key space
64− * but live under different prefs keys. */
65− // ConcurrentHashMap-backed sets: weakly-consistent iteration so the init merge's forEach
66− // can't throw ConcurrentModificationException if a mutator adds a key concurrently.
67− private val touchedDraftKeys: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
68− private val touchedFollowUpKeys: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
69−
70− private fun markDraftTouched(sessionId: String) {
71− if (!_ready.value) touchedDraftKeys.add(sessionId)
72− }
73− private fun markFollowUpTouched(sessionId: String) {
74− if (!_ready.value) touchedFollowUpKeys.add(sessionId)
75− }
76−
77− init {
78− // Eagerly load the prefs file on a background thread so the first main-thread
79− // get() doesn't block on disk I/O. The loaded snapshot is published via [_drafts]
80− // so callers can observe readiness without blocking.
81− if (scope != null && appContext != null) {
82− scope.launch(Dispatchers.IO) {
83− // runCatchingCancellable (not plain runCatching): this block runs in a
84− // coroutine, and plain runCatching swallows CancellationException — if a
85− // future suspend point is added here, cancellation would leave _ready
86− // forever false and drafts stuck loading. Matches the convention used by
87− // the sibling stores (MessageCacheStore, OutboxStore, AttachmentDraftStore).
88− val all = runCatchingCancellable {
89− prefs.all.mapValues { it.value as? String ?: "" }
90− }.getOrDefault(emptyMap())
91− // Partition persisted keys: follow-up keys carry a prefix, everything else
92− // is a plain per-session draft.
93− val drafts = mutableMapOf<String, String>()
94− val followUps = mutableMapOf<String, String>()
95− all.forEach { (k, v) ->
96− if (k.startsWith(FOLLOWUP_PREFIX)) followUps[k.removePrefix(FOLLOWUP_PREFIX)] = v
97− else drafts[k] = v
98− }
99− // Merge instead of overwriting: any in-memory writes that arrived before
100− // the background load completed (e.g. a share-intent draft injected via
101− // setImmediate) take priority over the persisted snapshot so they aren't
102− // clobbered. For keys the user explicitly touched before the load finished,
103− // drop the persisted entry first so a value they *cleared* isn't resurrected
104− // (the cleared key is absent from `current`, so putAll alone can't remove it).
105− _drafts.update { current ->
106− drafts.apply {
107− touchedDraftKeys.forEach { remove(it) }
108− putAll(current)
109− }
110− }
111− _followUps.update { current ->
112− followUps.apply {
113− touchedFollowUpKeys.forEach { remove(it) }
114− putAll(current)
115− }
116− }
117− _ready.value = true
118− }
119− } else {
120− _ready.value = true
121− }
122− }
123−
124− /** Returns the draft for [sessionId], or "" if not found or still loading. */
125− open fun get(sessionId: String): String = _drafts.value[sessionId].orEmpty()
126−
127− /** Returns the queued follow-up for [sessionId], or "" if none / still loading. */
128− open fun getFollowUp(sessionId: String): String = _followUps.value[sessionId].orEmpty()
129−
130− /** Persist a queued follow-up immediately (fire-and-forget, main-thread-safe).
131− * Mirrors [flushDraft]: async apply() when prefs are open, else a background thread,
132− * so a follow-up queued just before process death is flushed before the process exits.
133− * A blank [text] clears the stored follow-up. */
134− open fun flushFollowUp(sessionId: String, text: String) {
135− markFollowUpTouched(sessionId)
136− _followUps.update { current ->
137− val updated = current.toMutableMap()
138− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
139− updated
140− }
141− writeAsync(FOLLOWUP_PREFIX + sessionId, text)
142− }
143−
144− /** Persist [key]=[text] (or remove it when blank) without blocking the main thread on
145− * first-time disk I/O — see [flushDraft] for the prefs-not-yet-open rationale. */
146− private fun writeAsync(key: String, text: String) {
147− val write = {
148− runCatching {
149− prefs.edit().apply {
150− if (text.isBlank()) remove(key) else putString(key, text)
151− }.apply()
152− }.onFailure { Log.w("DraftStore", "Failed to persist $key", it) }
153− }
154− // FIX: always submit to the single-thread flushExecutor (never apply directly) so
155− // writes persist in submission order. Previously the post-init fast path applied
156− // synchronously on the caller's thread, which could land BEFORE an earlier still-queued
157− // write, persisting stale text. The task resolves the prefs lazy and calls apply().
158− runCatching { flushExecutor.execute { write() } }
159− }
160−
161− /** Update the in-memory draft immediately without persisting to disk.
162− * Used when navigation must see the new value synchronously (e.g. share-intent
163− * injection before ChatScreen composes). Call [set] afterwards to persist. */
164− open fun setImmediate(sessionId: String, text: String) {
165− markDraftTouched(sessionId)
166− _drafts.update { current ->
167− val updated = current.toMutableMap()
168− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
169− updated
170− }
171− }
172−
173− open suspend fun set(sessionId: String, text: String) {
174− markDraftTouched(sessionId)
175− _drafts.update { current ->
176− val updated = current.toMutableMap()
177− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
178− updated
179− }
180− // Route persistence through the single-thread flushExecutor (like the other writers)
181− // rather than the shared IO pool, so this write can't race ahead of an earlier queued
182− // flush and land stale. writeAsync persists sessionId=text (or removes it when blank),
183− // which is exactly this draft's persistence.
184− writeAsync(sessionId, text)
185− }
186−
187− /** Remove the draft for a session (call on session deletion to avoid orphaned entries).
188− * Also clears any queued follow-up so a deleted session leaves nothing behind. */
189− open suspend fun remove(sessionId: String) {
190− markDraftTouched(sessionId)
191− markFollowUpTouched(sessionId)
192− _drafts.update { current ->
193− val updated = current.toMutableMap()
194− updated.remove(sessionId)
195− updated
196− }
197− _followUps.update { current ->
198− val updated = current.toMutableMap()
199− updated.remove(sessionId)
200− updated
201− }
202− // Submit the (combined draft + follow-up) removal to the same single-thread
203− // flushExecutor the other writers use, so it can't race ahead of an earlier queued
204− // write and resurrect stale text. Mirrors flushDraft's submission pattern.
205− runCatching {
206− flushExecutor.execute {
207− runCatching {
208− prefs.edit().remove(sessionId).remove(FOLLOWUP_PREFIX + sessionId).apply()
209− }.onFailure { Log.w("DraftStore", "Failed to remove draft for $sessionId", it) }
210− }
211− }
212− }
213−
214− /**
215− * Synchronously persist a draft. Intended for [ViewModel.onCleared] where the
216− * viewModelScope is already cancelled and a suspending write can't be used.
217− *
218− * If the SharedPreferences file has already been opened (the normal case — the
219− * background init load touches it shortly after construction), the write uses
220− * [apply] (asynchronous) and returns immediately without blocking the main thread.
221− *
222− * If the prefs file has NOT been opened yet (a rare race where onCleared fires
223− * before the background init), the write is dispatched to a background thread
224− * instead of blocking the main thread on a synchronous disk read. The draft
225− * may be lost if the process exits before the write completes, but this is
226− * preferable to an ANR.
227− */
228− open fun flushDraft(sessionId: String, text: String) {
229− markDraftTouched(sessionId)
230− _drafts.update { current ->
231− val updated = current.toMutableMap()
232− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
233− updated
234− }
235− // FIX: always route the persistence through the single-thread flushExecutor so writes
236− // land in submission order. Previously, once prefs were open this applied synchronously
237− // on the calling (main) thread, so a newer direct write could persist BEFORE an older
238− // still-queued write completed, clobbering the draft with stale text. The executor task
239− // resolves the prefs lazy and uses apply() (async) exactly as before; the write may be
240− // lost only if the process exits before the queued task runs (as previously).
241− runCatching {
242− flushExecutor.execute {
243− runCatching {
244− prefs.edit().apply {
245− if (text.isBlank()) remove(sessionId) else putString(sessionId, text)
246− }.apply()
247− }.onFailure { Log.w("DraftStore", "Failed to flush draft for $sessionId", it) }
248− }
249− }
250− }
251−
252− private companion object {
253− /** Key prefix distinguishing persisted follow-ups from plain drafts in the shared
254− * prefs file. The leading/trailing spaces can't collide with a real opencode session
255− * id (which are non-blank, space-free tokens like "ses_..."). */
256− const val FOLLOWUP_PREFIX = " followup "
257− }
258−
259− /** Shut down the background flush executor. Call from AppContainer.shutdown(). */
260− open fun shutdown() {
261− flushExecutor.shutdown()
262− // Await pending flushDraft writes so drafts aren't lost if the process exits
263− // immediately after shutdown (e.g. ANR-triggered process kill).
264− runCatching { flushExecutor.awaitTermination(2, java.util.concurrent.TimeUnit.SECONDS) }
265− }
266−}
app/src/main/java/soy/iko/opencode/data/repo/ErrorKind.ktdeleted−78
@@ -1,78 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import io.ktor.client.plugins.ClientRequestException
4−import io.ktor.client.plugins.HttpRequestTimeoutException
5−import io.ktor.client.plugins.RedirectResponseException
6−import io.ktor.client.plugins.ResponseException
7−import io.ktor.client.plugins.ServerResponseException
8−import java.io.IOException
9−import java.net.ConnectException
10−import java.net.SocketTimeoutException
11−import java.net.UnknownHostException
12−
13−/**
14− * User-facing categories for a thrown error. Extracted so the classification logic is
15− * unit-testable without an Android [android.content.Context] (the mapping from a kind
16− * to a localized string lives in [friendlyError]).
17− */
18−enum class ErrorKind {
19− /** Server host could not be resolved / connection refused. */
20− NOT_REACHABLE,
21−
22− /** Connect or read timed out. */
23− TIMEOUT,
24−
25− /** Server returned a 5xx response. */
26− SERVER,
27−
28− /** Server returned a 4xx response (auth, not-found, etc.). */
29− CLIENT,
30−
31− /** Any other network-level I/O failure. */
32− NETWORK,
33−
34− /** Anything that isn't network-related. */
35− UNKNOWN,
36−}
37−
38−/**
39− * Classify a throwable into an [ErrorKind] by inspecting concrete exception types rather
40− * than string-matching class names. Unwraps [cause] chains so an exception surface-wrapped
41− * by a library still classifies correctly.
42− */
43−fun classifyError(t: Throwable): ErrorKind {
44− var current: Throwable? = t
45− // Walk a bounded cause chain so wrappers (e.g. an IllegalStateException around an
46− // IOException) still classify by their root.
47− var hops = 0
48− while (current != null && hops < 8) {
49− when (current) {
50− is UnknownHostException, is ConnectException -> return ErrorKind.NOT_REACHABLE
51− is SocketTimeoutException, is HttpRequestTimeoutException ->
52− return ErrorKind.TIMEOUT
53− is ServerResponseException -> return ErrorKind.SERVER
54− is ClientRequestException -> return ErrorKind.CLIENT
55− is RedirectResponseException -> return ErrorKind.CLIENT
56− is IOException -> return ErrorKind.NETWORK
57− else -> {
58− // Any other ResponseException (unrecognized status family).
59− if (current is ResponseException) return ErrorKind.SERVER
60− }
61− }
62− current = current.cause
63− hops++
64− }
65− return ErrorKind.UNKNOWN
66−}
67−
68−/** The HTTP status code carried by a client/server error, if any. */
69−fun responseStatusCode(t: Throwable): Int? {
70− var current: Throwable? = t
71− var hops = 0
72− while (current != null && hops < 8) {
73− if (current is ResponseException) return current.response.status.value
74− current = current.cause
75− hops++
76− }
77− return null
78−}
app/src/main/java/soy/iko/opencode/data/repo/FileBrowserPrefs.ktdeleted−90
@@ -1,90 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import androidx.datastore.preferences.core.booleanPreferencesKey
5−import androidx.datastore.preferences.core.edit
6−import androidx.datastore.preferences.core.stringPreferencesKey
7−import androidx.datastore.preferences.preferencesDataStore
8−import kotlinx.coroutines.flow.Flow
9−import kotlinx.coroutines.flow.flowOf
10−import kotlinx.coroutines.flow.map
11−
12−private val Context.fileBrowserPrefsDataStore by preferencesDataStore(name = "file_browser_prefs")
13−
14−/** Sort axis for the file-browser directory listing. Name is always available; Size/Modified
15− * depend on the server emitting size/mtime (otherwise they sort nulls to the bottom). */
16−enum class FileSortKey { NAME, SIZE, MODIFIED }
17−
18−/**
19− * Persisted file-browser display prefs (folders-first, show-hidden, sort key + direction,
20− * changed-only filter) so a user who prefers size-sort or hidden-files-visible keeps it
21− * across restarts, not just rotation.
22− *
23− * `open` with a `protected` no-arg constructor so tests can subclass and override the flows
24− * without a real DataStore (mirrors the other stores). The flow accessors are getters (not
25− * eager initializers) and null-guard the context so the test constructor never touches disk.
26− */
27−@Suppress("TooManyFunctions")
28−open class FileBrowserPrefs private constructor(
29− private val appContext: Context?,
30− @Suppress("unused") private val testMode: Boolean,
31−) {
32− constructor(context: Context) : this(context.applicationContext, false)
33− protected constructor() : this(null, true)
34−
35− private val foldersFirstKey = booleanPreferencesKey("folders_first")
36− private val showHiddenKey = booleanPreferencesKey("show_hidden")
37− private val sortKeyPref = stringPreferencesKey("sort_key")
38− private val sortDescKey = booleanPreferencesKey("sort_desc")
39− private val changedOnlyKey = booleanPreferencesKey("changed_only")
40−
41− // Folders-first is the most useful default; the toggle flips between folders-first name
42− // sort and the server's raw order.
43− open val foldersFirst: Flow<Boolean>
44− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[foldersFirstKey] ?: true }
45− ?: flowOf(true)
46−
47− // Default off so the listing isn't cluttered with dotfiles; the user reveals .env / .git
48− // / .opencode on demand.
49− open val showHidden: Flow<Boolean>
50− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[showHiddenKey] ?: false }
51− ?: flowOf(false)
52−
53− // Stored as the enum name; an unknown value falls back to NAME (forward-compatible with a
54− // future rename/removal of an enum entry).
55− open val sortKey: Flow<FileSortKey>
56− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { prefs ->
57− runCatching { FileSortKey.valueOf(prefs[sortKeyPref] ?: FileSortKey.NAME.name) }
58− .getOrDefault(FileSortKey.NAME)
59− } ?: flowOf(FileSortKey.NAME)
60−
61− open val sortDesc: Flow<Boolean>
62− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[sortDescKey] ?: false }
63− ?: flowOf(false)
64−
65− // Default off: the changed-only filter narrows the listing to git-tracked changes, which is
66− // useful when reviewing a diff but not the default browsing view.
67− open val changedOnly: Flow<Boolean>
68− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[changedOnlyKey] ?: false }
69− ?: flowOf(false)
70−
71− open suspend fun setFoldersFirst(value: Boolean) {
72− appContext?.fileBrowserPrefsDataStore?.edit { it[foldersFirstKey] = value }
73− }
74−
75− open suspend fun setShowHidden(value: Boolean) {
76− appContext?.fileBrowserPrefsDataStore?.edit { it[showHiddenKey] = value }
77− }
78−
79− open suspend fun setSortKey(key: FileSortKey) {
80− appContext?.fileBrowserPrefsDataStore?.edit { it[sortKeyPref] = key.name }
81− }
82−
83− open suspend fun setSortDesc(value: Boolean) {
84− appContext?.fileBrowserPrefsDataStore?.edit { it[sortDescKey] = value }
85− }
86−
87− open suspend fun setChangedOnly(value: Boolean) {
88− appContext?.fileBrowserPrefsDataStore?.edit { it[changedOnlyKey] = value }
89− }
90−}
app/src/main/java/soy/iko/opencode/data/repo/MessageCacheStore.ktdeleted−137
@@ -1,137 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.sync.Mutex
7−import kotlinx.coroutines.sync.withLock
8−import kotlinx.coroutines.withContext
9−import kotlinx.serialization.builtins.ListSerializer
10−import soy.iko.opencode.data.model.MessageWithParts
11−import soy.iko.opencode.data.network.OpencodeJson
12−import soy.iko.opencode.util.runCatchingCancellable
13−import java.io.File
14−
15−/**
16− * On-disk cache of a session's reduced message list, so a conversation shows instantly on
17− * open (and remains readable while offline / before the network responds) instead of a blank
18− * screen until `GET /session/:id/message` returns.
19− *
20− * One JSON file per session under filesDir, encoded with [OpencodeJson] so the same sealed
21− * polymorphism used on the wire round-trips (unknown parts/messages are concrete
22− * `__unknown` variants, so they encode too). Every operation is best-effort — a cache
23− * miss or a write failure just falls back to the network — so problems never surface to
24− * the user. No annotation processing (Room/KSP) per the project's manual-DI convention.
25− */
26−open class MessageCacheStore private constructor(
27− private val appContext: Context?,
28− @Suppress("unused") private val testMode: Boolean,
29−) {
30− constructor(context: Context) : this(context.applicationContext, false)
31− protected constructor() : this(null, true)
32−
33− private val serializer = ListSerializer(MessageWithParts.serializer())
34−
35− /** Session ids are validated tokens upstream, but sanitize anyway so a stray id can't
36− * escape the directory. */
37− private val idRegex = Regex("[^A-Za-z0-9_-]")
38−
39− private val dir: File? by lazy {
40− appContext?.let { File(it.filesDir, "message_cache").apply { mkdirs() } }
41− }
42−
43− /** Per-profile subdirectory: two servers with a colliding session id must not share a cache
44− * file, so entries are namespaced by profile id under [dir]. */
45− private fun profileDir(profileId: String): File? =
46− dir?.let { File(it, idRegex.replace(profileId, "_")).apply { mkdirs() } }
47−
48− private fun fileFor(profileId: String, sessionId: String): File? =
49− profileDir(profileId)?.let { File(it, idRegex.replace(sessionId, "_") + ".json") }
50−
51− /** Per-session write lock so concurrent save/remove/load on the same file (e.g. both
52− * panes of two-pane mode saving the same session, or a save racing a delete's remove)
53− * can't tear or half-write the cache file. Keyed by session id; the map grows only with
54− * the number of distinct sessions touched, and each [Mutex] is a few bytes. */
55− private val locks = java.util.concurrent.ConcurrentHashMap<String, Mutex>()
56− private fun lockFor(sessionId: String): Mutex = locks.getOrPut(sessionId) { Mutex() }
57−
58− /** Sessions whose cache file has been removed by [remove]. A teardown flush of an
59− * observer (CacheWriter.flushOnTeardown) runs under NonCancellable and can race with
60− * remove(): both serialize on [lockFor], but their relative order is nondeterministic.
61− * If the flush's save lands after remove, it re-creates the deleted session's cache
62− * file, defeating the deletion (a privacy/disk-leak with no background cleanup). The
63− * tombstone lets a post-remove save detect the deletion and skip. Keyed by
64− * "$profileId/$sessionId" — a bare sessionId would suppress a *different* server's
65− * saves if two servers share a colliding session id (the very case the per-profile
66− * namespacing at [profileDir] exists to defend against). Cleared by [load] so
67− * re-opening a session re-enables saving. Bounded by distinct deleted sessions. */
68− private val tombstones: MutableSet<String> =
69− java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap())
70−
71− private fun tombstoneKey(profileId: String, sessionId: String): String = "$profileId/$sessionId"
72−
73− /** Load the cached messages for [sessionId] under [profileId], or empty if none / unreadable. */
74− open suspend fun load(profileId: String, sessionId: String): List<MessageWithParts> = lockFor(sessionId).withLock {
75− // Re-opening a session re-enables saving: clear any tombstone so a fresh conversation
76− // write isn't suppressed by a prior deletion of the same (reused) id.
77− tombstones.remove(tombstoneKey(profileId, sessionId))
78− withContext(Dispatchers.IO) {
79− val file = fileFor(profileId, sessionId)?.takeIf { it.exists() } ?: return@withContext emptyList()
80− runCatchingCancellable { OpencodeJson.decodeFromString(serializer, file.readText()) }
81− .getOrDefault(emptyList())
82− }
83− }
84−
85− /** Persist [messages] for [sessionId] under [profileId] (an empty list deletes the file). */
86− open suspend fun save(profileId: String, sessionId: String, messages: List<MessageWithParts>): Unit = lockFor(sessionId).withLock {
87− // Skip if this session was deleted since the observer started: a teardown flush racing
88− // after remove() must not re-create the file. (Held under the same per-session lock as
89− // remove, so the tombstone is visible to a save that lost the race.)
90− if (tombstoneKey(profileId, sessionId) in tombstones) return@withLock
91− withContext(Dispatchers.IO) {
92− val file = fileFor(profileId, sessionId) ?: return@withContext
93− runCatchingCancellable {
94− if (messages.isEmpty()) file.delete()
95− else {
96− // FIX: write atomically (temp file + rename) like RecentSessionsStore so a
97− // process kill mid-write can't leave a truncated file that fails to decode,
98− // wiping the cached conversation on the next open.
99− val encoded = OpencodeJson.encodeToString(serializer, messages)
100− val tmp = File(file.parentFile, file.name + ".tmp")
101− tmp.writeText(encoded)
102− if (!tmp.renameTo(file)) {
103− file.writeText(encoded)
104− tmp.delete()
105− }
106− }
107− }.onFailure { Log.w("MessageCacheStore", "Failed to cache messages for $sessionId", it) }
108− Unit
109− }
110− }
111−
112− /** Remove a session's cached messages (call on deletion). Clears the entry in every profile
113− * namespace: session ids are unique per server and deletion is terminal, so the caller
114− * needn't know which profile owned it. The per-session lock is intentionally NOT evicted —
115− * a concurrent teardown save() for this id must serialize against the same [Mutex] instance,
116− * and the map is bounded by the number of distinct sessions touched.
117− * [profileId] namespaces the tombstone so a delete on one server doesn't suppress another
118− * server's saves for a colliding session id. */
119− open suspend fun remove(profileId: String, sessionId: String) {
120− lockFor(sessionId).withLock {
121− // Set the tombstone before deleting so a concurrent/loser save sees it and skips,
122− // instead of re-creating the file we're about to delete.
123− tombstones.add(tombstoneKey(profileId, sessionId))
124− withContext(Dispatchers.IO) {
125− runCatchingCancellable {
126− val name = idRegex.replace(sessionId, "_") + ".json"
127− dir?.listFiles()?.forEach { entry ->
128− if (entry.isDirectory) File(entry, name).delete()
129− }
130− // Back-compat: pre-namespacing caches were written flat under [dir].
131− dir?.let { File(it, name).delete() }
132− }
133− Unit
134− }
135− }
136− }
137−}
app/src/main/java/soy/iko/opencode/data/repo/OutboxStore.ktdeleted−168
@@ -1,168 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.flow.MutableStateFlow
7−import kotlinx.coroutines.flow.StateFlow
8−import kotlinx.coroutines.flow.asStateFlow
9−import kotlinx.coroutines.sync.Mutex
10−import kotlinx.coroutines.sync.withLock
11−import kotlinx.coroutines.withContext
12−import kotlinx.serialization.Serializable
13−import kotlinx.serialization.decodeFromString
14−import kotlinx.serialization.encodeToString
15−import kotlinx.serialization.json.Json
16−import soy.iko.opencode.data.model.ModelRef
17−import soy.iko.opencode.util.runCatchingCancellable
18−import java.io.File
19−
20−/**
21− * One prompt composed while offline (or with no active connection), queued to send when
22− * connectivity returns. Tagged with the [profileId] it was composed for so a reconnect to a
23− * *different* server doesn't misfire it against a session id that only exists on the
24− * original server. [attachments] carry their self-contained base64 data URLs, so a queued
25− * image survives a process restart just like a staged attachment.
26− */
27−@Serializable
28−data class OutboxMessage(
29− val id: String,
30− val profileId: String,
31− val sessionId: String,
32− val text: String,
33− val attachments: List<PersistedAttachment> = emptyList(),
34− val model: ModelRef? = null,
35− val agent: String? = null,
36− val createdAt: Long,
37−)
38−
39−/**
40− * A persisted send-queue: prompts the user composed while disconnected, flushed on
41− * reconnect (see [soy.iko.opencode.di.AppContainer.observeOutbox]). Backed by one JSON file
42− * under filesDir (not SharedPreferences) because a queued attachment's base64 payload can be
43− * several megabytes. The in-memory [messages] StateFlow is the source of truth the UI and the
44− * flusher observe; disk is written through under a mutex on every mutation.
45− */
46−open class OutboxStore private constructor(
47− private val appContext: Context?,
48− @Suppress("unused") private val testMode: Boolean,
49−) {
50− constructor(context: Context) : this(context.applicationContext, false)
51− protected constructor() : this(null, true)
52−
53− private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
54− private val ioMutex = Mutex()
55−
56− private val _messages = MutableStateFlow<List<OutboxMessage>>(emptyList())
57− /** All queued messages across sessions/servers, in enqueue order. */
58− open val messages: StateFlow<List<OutboxMessage>> = _messages.asStateFlow()
59−
60− /** Set once the on-disk queue has been read into [_messages] (under [ioMutex]). Until this
61− * is true, a [mutate] must read disk first — otherwise a mutation that beats [load] would
62− * persist from an empty in-memory snapshot and overwrite (or, for a removal, delete) the
63− * persisted queue, losing every message the user composed offline in a previous run. */
64− private var loaded = false
65−
66− private val file: File? by lazy {
67− appContext?.let { File(it.filesDir, "outbox.json") }
68− }
69−
70− /** Read the persisted queue into [messages]. Call once at startup. Idempotent. */
71− open suspend fun load() {
72− ioMutex.withLock { loadLocked() }
73− }
74−
75− /** Read the on-disk queue into memory. MUST be called while holding [ioMutex]. Idempotent
76− * (guarded by [loaded]) so a [mutate] that arrives before [load] can call it to guarantee
77− * disk is read before any write, then a later [load] is a no-op. Returns true once the queue
78− * is in memory (or the file is genuinely absent), false if an existing file couldn't be
79− * read — the caller MUST NOT persist on false or it would overwrite the still-valid queue. */
80− private suspend fun loadLocked(): Boolean {
81− if (loaded) return true
82− val f = file?.takeIf { it.exists() }
83− if (f == null) {
84− // A genuinely absent file is a normal empty queue: mark loaded so mutations proceed.
85− loaded = true
86− return true
87− }
88− // Only mark [loaded] AFTER a successful read. A transient read/decode failure (or a
89− // cancelled read) of an *existing* file must not clobber the still-valid on-disk queue:
90− // leave loaded=false and report failure so the caller skips its write and a later
91− // mutate/load retries the read, instead of persisting an empty snapshot over the user's
92− // offline-composed messages.
93− val diskList = withContext(Dispatchers.IO) {
94− runCatchingCancellable { json.decodeFromString<List<OutboxMessage>>(f.readText()) }
95− }.getOrElse { return false }
96− // Don't clobber items enqueued while the load was in flight: merge by id, keeping
97− // the in-memory version on conflict (it's newer).
98− if (_messages.value.isEmpty()) {
99− _messages.value = diskList.sortedBy { it.createdAt }
100− } else {
101− val known = _messages.value.mapTo(mutableSetOf()) { it.id }
102− val merged = (diskList.filter { it.id !in known } + _messages.value).sortedBy { it.createdAt }
103− _messages.value = merged
104− // The merge reconciled items enqueued while this load was in flight with the
105− // on-disk set; write the merged set back so a later process kill can't drop the
106− // raced enqueue. persist() doesn't take ioMutex, so this won't deadlock.
107− persist(merged)
108− }
109− loaded = true
110− return true
111− }
112−
113− open suspend fun enqueue(message: OutboxMessage) = mutate { current ->
114− current.filterNot { it.id == message.id } + message
115− }
116−
117− open suspend fun remove(id: String) = mutate { current -> current.filterNot { it.id == id } }
118−
119− /** Remove every queued message for [sessionId] (e.g. the user discarded them, or the
120− * session was deleted). */
121− open suspend fun removeForSession(sessionId: String) =
122− mutate { current -> current.filterNot { it.sessionId == sessionId } }
123−
124− private suspend fun mutate(transform: (List<OutboxMessage>) -> List<OutboxMessage>) {
125− // Persist *under* the lock so concurrent mutations (e.g. the flusher removing sent
126− // messages while the UI enqueues a new one) can't race their disk writes: without
127− // this, the older snapshot could land last and drop/resurrect a queued prompt, or two
128− // overlapping writeText/delete calls could tear the file. The lock serializes both the
129− // in-memory update and the write, guaranteeing on-disk order matches memory order.
130− ioMutex.withLock {
131− // Ensure the persisted queue has been read into memory before mutating: a mutation
132− // that races ahead of load() would otherwise transform an empty in-memory snapshot
133− // and persist()/delete() the file, destroying messages queued in a previous run.
134− val loadedOk = loadLocked()
135− val updated = transform(_messages.value).sortedBy { it.createdAt }
136− _messages.value = updated
137− // Only write when the existing on-disk queue was actually read. If the read of an
138− // existing file failed (loadedOk == false), _messages is missing whatever it held, so
139− // persisting `updated` would overwrite the still-valid file with an incomplete
140− // snapshot — losing the user's prior offline-composed messages. Keep the transform in
141− // memory (so the UI reflects the new item) but leave disk untouched; loaded stays
142− // false, so the next mutate/load retries the read and then merges + persists.
143− if (loadedOk) persist(updated)
144− }
145− }
146−
147− private suspend fun persist(list: List<OutboxMessage>) {
148− val f = file ?: return
149− withContext(Dispatchers.IO) {
150− runCatchingCancellable {
151− if (list.isEmpty()) {
152− f.delete()
153− } else {
154− // FIX: write atomically (temp file + rename) like RecentSessionsStore so a
155− // process kill mid-write can't leave a truncated file — a torn file fails to
156− // decode and load() would then drop ALL queued offline messages.
157− val encoded = json.encodeToString(list)
158− val tmp = File(f.parentFile, f.name + ".tmp")
159− tmp.writeText(encoded)
160− if (!tmp.renameTo(f)) {
161− f.writeText(encoded)
162− tmp.delete()
163− }
164− }
165− }.onFailure { Log.w("OutboxStore", "Failed to persist outbox", it) }
166− }
167− }
168−}
app/src/main/java/soy/iko/opencode/data/repo/ProfileStore.ktdeleted−251
@@ -1,251 +0,0 @@
1−// Jetpack Security (androidx.security:security-crypto) was deprecated wholesale in 1.1.0 with
2−// no first-party drop-in replacement; we intentionally keep using EncryptedSharedPreferences /
3−// MasterKey for the encrypted password store (on-disk-compatible, still functional). Suppress
4−// the expected deprecation warnings here so the build log stays clean until a future migration.
5−@file:Suppress("DEPRECATION")
6−
7−package soy.iko.opencode.data.repo
8−
9−import android.content.Context
10−import android.content.SharedPreferences
11−import android.util.Log
12−import androidx.datastore.preferences.core.edit
13−import androidx.datastore.preferences.core.stringPreferencesKey
14−import androidx.datastore.preferences.preferencesDataStore
15−import androidx.security.crypto.EncryptedSharedPreferences
16−import androidx.security.crypto.MasterKey
17−import soy.iko.opencode.data.model.ServerProfile
18−import soy.iko.opencode.data.network.OpencodeJson
19−import kotlinx.coroutines.Dispatchers
20−import kotlinx.coroutines.sync.Mutex
21−import kotlinx.coroutines.sync.withLock
22−import kotlinx.coroutines.flow.Flow
23−import kotlinx.coroutines.flow.flowOn
24−import kotlinx.coroutines.flow.map
25−import kotlinx.coroutines.withContext
26−import kotlinx.serialization.Serializable
27−import kotlinx.serialization.builtins.ListSerializer
28−
29−private val Context.dataStore by preferencesDataStore(name = "server_profiles")
30−
31−/**
32− * Persists server profiles. Non-secret fields go to DataStore (as a JSON list);
33− * the Basic-auth password is stored separately in EncryptedSharedPreferences, keyed
34− * by profile id, and merged back in on read.
35− */
36−open class ProfileStore private constructor(
37− private val appContext: Context?,
38− @Suppress("unused") private val testMode: Boolean,
39−) {
40− constructor(context: Context) : this(context.applicationContext, false)
41− protected constructor() : this(null, true)
42−
43− private val profilesKey = stringPreferencesKey("profiles_json")
44−
45− /** Guards [migrateFallbackPasswords] so it runs at most once per process, not on every
46− * DataStore emission. The mutex serializes concurrent callers so a second collector waits
47− * for the migration's writes to land (rather than skipping ahead and reading empty secure
48− * prefs mid-migration); [migrationDone] is only set true *after* the writes complete. */
49− private val migrationMutex = Mutex()
50− @Volatile private var migrationDone = false
51−
52− private val securePrefs: SharedPreferences? by lazy {
53− val ctx = appContext ?: return@lazy null
54− runCatching {
55− val masterKey = MasterKey.Builder(ctx)
56− .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
57− .build()
58− EncryptedSharedPreferences.create(
59− ctx,
60− "server_secrets",
61− masterKey,
62− EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
63− EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
64− )
65− }.getOrElse {
66− Log.e("ProfileStore", "Encrypted prefs unavailable; passwords will not be persisted", it)
67− null
68− }
69− }
70−
71− /** True when EncryptedSharedPreferences could not be initialized. */
72− open val securePrefsUnavailable: Boolean get() = securePrefs == null
73−
74− /** Plaintext fallback used only when encrypted prefs are unavailable, so the user
75− * can still connect — but passwords won't survive an app reinstall. */
76− private val fallbackPrefs: SharedPreferences by lazy {
77− appContext!!.getSharedPreferences("server_secrets_fallback", Context.MODE_PRIVATE)
78− }
79−
80− private fun prefsForPasswords(): SharedPreferences =
81− securePrefs ?: fallbackPrefs
82−
83− /** Migrate any plaintext passwords from the fallback prefs to secure prefs,
84− * then clear the fallback. Runs at most once per process — subsequent calls
85− * are no-ops — so DataStore re-emissions don't repeatedly scan SharedPreferences. */
86− private suspend fun migrateFallbackPasswords() {
87− if (migrationDone) return
88− migrationMutex.withLock {
89− // Re-check inside the lock: a concurrent caller may have completed the migration
90− // while we were waiting. Serializing here (rather than a bare compareAndSet that
91− // marks done before doing the work) ensures a second collector doesn't read the
92− // secure store before the first caller's write has populated it.
93− if (migrationDone) return
94− val secure = securePrefs
95− if (secure == null) {
96− // No secure store to migrate into; nothing to do, and no point retrying.
97− migrationDone = true
98− return
99− }
100− withContext(Dispatchers.IO) {
101− val fallbackKeys = fallbackPrefs.all.keys.filter { it.startsWith("pw_") }
102− if (fallbackKeys.isNotEmpty()) {
103− // Write passwords to the secure store FIRST, then remove them from the
104− // plaintext fallback. SharedPreferences.apply() persists to disk
105− // asynchronously, so removing from fallback before the secure batch lands
106− // could lose the password if the process dies between the two writes.
107− // Writing secure first makes the worst case a harmless duplicate (both
108− // stores hold it; the migration is idempotent) rather than data loss.
109− secure.edit().apply {
110− for (key in fallbackKeys) {
111− val pw = fallbackPrefs.getString(key, null) ?: continue
112− putString(key, pw)
113− }
114− }.apply()
115− fallbackPrefs.edit().apply {
116− for (key in fallbackKeys) remove(key)
117− }.apply()
118− }
119− }
120− // Only mark done once the writes are in the secure store's in-memory cache (apply()
121− // updates it synchronously), so the next collector past the mutex reads real values.
122− migrationDone = true
123− }
124− }
125−
126− /** Stored shape on DataStore (everything except the secret password). */
127− @Serializable
128− private data class StoredProfile(
129− val id: String,
130− val label: String,
131− val baseUrl: String,
132− val username: String? = null,
133− val lastUsed: Long = 0,
134− // Non-secret TLS options; default to prior behavior for profiles saved before these
135− // fields existed (deserialization uses these defaults for missing keys).
136− val requireHttps: Boolean = false,
137− val certPin: String? = null,
138− )
139−
140− open val profiles: Flow<List<ServerProfile>> = appContext?.dataStore?.data?.map { prefs ->
141− // Migrate any orphaned plaintext passwords to secure prefs on first load.
142− migrateFallbackPasswords()
143− val json = prefs[profilesKey] ?: return@map emptyList()
144− val stored = runCatching {
145− OpencodeJson.decodeFromString(ListSerializer(StoredProfile.serializer()), json)
146− }.onFailure { Log.w("ProfileStore", "Failed to decode stored profiles, ignoring", it) }
147− .getOrDefault(emptyList())
148− .sortedByDescending { it.lastUsed }
149− // Batch all password lookups into a single IO dispatch instead of one
150− // withContext round-trip per profile (N dispatches → 1). DataStore already
151− // runs this map block on IO, but each passwordFor() call still pays the
152− // suspend + redispatch overhead.
153− val pwPrefs = prefsForPasswords()
154− stored.map { it.toProfile(pwPrefs) }
155− }
156− // The .map above runs in the *collector's* context, and every consumer collects on
157− // viewModelScope (Main). Without this, kotlinx JSON decode + EncryptedSharedPreferences
158− // AES decryption would run on the UI thread on each emission. flowOn moves that work to IO.
159− ?.flowOn(Dispatchers.IO)
160− ?: kotlinx.coroutines.flow.flowOf(emptyList())
161−
162− private fun StoredProfile.toProfile(pwPrefs: SharedPreferences): ServerProfile {
163− val pw = username?.let { pwPrefs.getString(passwordKey(id), null) }
164− return ServerProfile(
165− id = id,
166− label = label,
167− baseUrl = baseUrl,
168− username = username,
169− password = pw,
170− lastUsed = lastUsed,
171− requireHttps = requireHttps,
172− certPin = certPin,
173− )
174− }
175−
176− open suspend fun resolve(profile: ServerProfile): ServerProfile {
177− val pw = if (profile.hasAuth) {
178− withContext(Dispatchers.IO) { prefsForPasswords().getString(passwordKey(profile.id), null) }
179− } else {
180− null
181− }
182− return profile.copy(password = pw)
183− }
184−
185− open suspend fun save(profile: ServerProfile) {
186− // Write the password first so that if the DataStore write fails, we're left
187− // with an orphaned password (harmless, cleaned up on next save/delete) rather
188− // than a profile with no password (which would break authentication).
189− withContext(Dispatchers.IO) {
190− prefsForPasswords().edit().apply {
191− val pw = profile.password
192− if (!profile.username.isNullOrBlank() && !pw.isNullOrEmpty()) {
193− putString(passwordKey(profile.id), pw)
194− } else {
195− remove(passwordKey(profile.id))
196− }
197− }.apply()
198− }
199− appContext!!.dataStore.edit { prefs ->
200− val current = prefs[profilesKey]?.let {
201− runCatching { OpencodeJson.decodeFromString(ListSerializer(StoredProfile.serializer()), it) }
202− .getOrDefault(emptyList())
203− } ?: emptyList()
204− // If the incoming profile has lastUsed=0 (e.g. ServerEditViewModel.save()
205− // couldn't read the existing value due to a DataStore timeout), preserve
206− // the existing nonzero lastUsed so saving an edit doesn't reset the
207− // profile's sort position in the server list.
208− val preservedLastUsed = if (profile.lastUsed == 0L) {
209− current.firstOrNull { it.id == profile.id }?.lastUsed ?: 0L
210− } else {
211− profile.lastUsed
212− }
213− val stored = StoredProfile(
214− id = profile.id,
215− label = profile.label,
216− baseUrl = profile.baseUrl,
217− username = profile.username?.takeIf { it.isNotBlank() },
218− lastUsed = preservedLastUsed,
219− requireHttps = profile.requireHttps,
220− certPin = profile.certPin?.takeIf { it.isNotBlank() },
221− )
222− val updated = current.filterNot { it.id == profile.id } + stored
223− prefs[profilesKey] = OpencodeJson.encodeToString(ListSerializer(StoredProfile.serializer()), updated)
224− }
225− }
226−
227− open suspend fun delete(id: String) {
228− // Delete the profile from DataStore first, then the password. If the process
229− // dies between the two, an orphaned password remains (harmless, cleaned up on
230− // next save/delete) rather than a profile with no password.
231− appContext!!.dataStore.edit { prefs ->
232− val current = prefs[profilesKey]?.let {
233− runCatching { OpencodeJson.decodeFromString(ListSerializer(StoredProfile.serializer()), it) }
234− .getOrDefault(emptyList())
235− } ?: emptyList()
236− prefs[profilesKey] = OpencodeJson.encodeToString(
237− ListSerializer(StoredProfile.serializer()),
238− current.filterNot { it.id == id },
239− )
240− }
241− // Clean up the password in both secure and fallback prefs so no orphaned
242− // plaintext password lingers if secure prefs were temporarily unavailable.
243− withContext(Dispatchers.IO) {
244− val key = passwordKey(id)
245− securePrefs?.edit()?.remove(key)?.apply()
246− fallbackPrefs.edit().remove(key).apply()
247− }
248− }
249−
250− private fun passwordKey(id: String) = "pw_$id"
251−}
app/src/main/java/soy/iko/opencode/data/repo/RecentModelsStore.ktdeleted−80
@@ -1,80 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.flow.MutableStateFlow
5−import kotlinx.coroutines.flow.StateFlow
6−import kotlinx.coroutines.flow.asStateFlow
7−
8−/**
9− * Persists the most recently picked models so the model picker can surface them as a
10− * "Recent" section above the full catalog. Backed by SharedPreferences because the UI
11− * needs the initial value synchronously and the list is tiny (≤ [MAX_ENTRIES]), mirroring
12− * the low-stakes-persistence rationale of [SearchHistoryStore]. `open` with a `protected`
13− * no-arg constructor so tests can subclass and override without a real Context.
14− *
15− * Entries are stored as `providerID\modelID` composite keys (the separator is chosen so it
16− * can't collide with provider or model ids, which are URL/path-safe identifiers).
17− */
18−open class RecentModelsStore private constructor(
19− private val appContext: Context?,
20− @Suppress("unused") private val testMode: Boolean,
21−) {
22− constructor(context: Context) : this(context.applicationContext, false)
23− protected constructor() : this(null, true)
24−
25− private val prefs by lazy {
26− appContext?.getSharedPreferences("recent_models", Context.MODE_PRIVATE)
27− ?: error("No context — override methods in test subclass")
28− }
29−
30− private val _entries = MutableStateFlow<List<String>>(emptyList())
31− open val entries: StateFlow<List<String>> = _entries.asStateFlow()
32−
33− init {
34− if (appContext != null) {
35− _entries.value = runCatching {
36− prefs.getString(KEY, null)
37− ?.takeIf { it.isNotBlank() }
38− ?.split(SEPARATOR)
39− ?.filter { it.isNotBlank() }
40− ?.take(MAX_ENTRIES)
41− }.getOrDefault(emptyList()) ?: emptyList()
42− }
43− }
44−
45− /** Insert [providerId]/[modelId] at the head of the recents, deduped and capped at
46− * [MAX_ENTRIES]. Blank ids are ignored. */
47− open fun add(providerId: String, modelId: String) {
48− val p = providerId.trim()
49− val m = modelId.trim()
50− if (p.isBlank() || m.isBlank()) return
51− val key = "$p$SEPARATOR$m"
52− val updated = (listOf(key) + _entries.value.filter { it != key }).take(MAX_ENTRIES)
53− _entries.value = updated
54− runCatching {
55− prefs.edit().putString(KEY, updated.joinToString(SEPARATOR)).apply()
56− }
57− }
58−
59− /** Split a stored composite key back into its provider/model id pair. Returns null if
60− * the entry is malformed (shouldn't happen, but a corrupt prefs value must never crash
61− * the picker). */
62− fun split(entry: String): Pair<String, String>? {
63− val parts = entry.split(SEPARATOR)
64− return if (parts.size == 2 && parts[0].isNotBlank() && parts[1].isNotBlank())
65− parts[0] to parts[1] else null
66− }
67−
68− open fun clear() {
69− _entries.value = emptyList()
70− runCatching { prefs.edit().remove(KEY).apply() }
71− }
72−
73− private companion object {
74− const val KEY = "models"
75− // A newline can't appear in a provider/model id (they're URL/path-safe), so it's a
76− // safe list separator that won't collide with id contents.
77− const val SEPARATOR = "\n"
78− const val MAX_ENTRIES = 5
79− }
80−}
app/src/main/java/soy/iko/opencode/data/repo/RecentSessionsStore.ktdeleted−76
@@ -1,76 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.Dispatchers
5−import kotlinx.coroutines.sync.Mutex
6−import kotlinx.coroutines.sync.withLock
7−import kotlinx.coroutines.withContext
8−import kotlinx.serialization.Serializable
9−import kotlinx.serialization.decodeFromString
10−import kotlinx.serialization.encodeToString
11−import kotlinx.serialization.json.Json
12−import java.io.File
13−
14−/** A minimal session summary persisted for the home-screen widget and launcher shortcuts. */
15−@Serializable
16−data class RecentSession(val id: String, val title: String)
17−
18−/**
19− * Persists a short list of recent sessions to a small JSON file under filesDir so app-external
20− * surfaces (the home-screen widget's [android.widget.RemoteViewsService] and the "Resume last"
21− * launcher shortcut) can read them without a live connection or in-memory state. Both the app
22− * and the widget's RemoteViews factory run in the same process, so a plain file is sufficient.
23− */
24−object RecentSessionsStore {
25−
26− private const val FILE = "recent_sessions.json"
27− const val MAX = 8
28−
29− private val json = Json { ignoreUnknownKeys = true }
30−
31− /** Serializes concurrent [write]s. The synchronous [read] (called from the widget's
32− * RemoteViewsService) can't take a suspend lock, so [write] instead swaps the file in
33− * atomically via a temp-file rename — the reader always sees either the old or the new
34− * complete file, never a half-written one. */
35− private val writeMutex = Mutex()
36−
37− private fun file(context: Context) = File(context.applicationContext.filesDir, FILE)
38−
39− /** Synchronous read — safe to call from the widget factory (bounded, tiny file). */
40− fun read(context: Context): List<RecentSession> {
41− val f = file(context).takeIf { it.exists() } ?: return emptyList()
42− return runCatching { json.decodeFromString<List<RecentSession>>(f.readText()) }
43− .getOrDefault(emptyList())
44− }
45−
46− /** Persist [sessions] (capped to [MAX]); a no-op empty list writes an empty file. */
47− suspend fun write(context: Context, sessions: List<RecentSession>) = withContext(Dispatchers.IO) {
48− writeMutex.withLock {
49− runCatching {
50− val target = file(context)
51− val encoded = json.encodeToString(sessions.take(MAX))
52− val tmp = File(target.parentFile, "$FILE.tmp")
53− tmp.writeText(encoded)
54− // Atomic replace on POSIX filesystems (app's internal storage); the reader
55− // never observes a torn file. renameTo can fail when the target exists on
56− // some OEM filesystems — delete the target first so the rename is a pure
57− // create, and only if that still fails fall back to a copy-and-delete that
58− // preserves atomicity from the reader's perspective (the reader sees either
59− // the old complete file or the new complete file, never a half-written one,
60− // because the copy writes to the temp and then atomically moves it).
61− if (!tmp.renameTo(target)) {
62− target.delete()
63− if (!tmp.renameTo(target)) {
64− // Last-resort: copy bytes then delete temp. The target is briefly
65− // absent during the copy, but a concurrent reader sees an empty
66− // list (the runCatching on the read side handles a missing file),
67− // never a torn file — preserving the documented invariant.
68− tmp.copyTo(target, overwrite = true)
69− tmp.delete()
70− }
71− }
72− }
73− Unit
74− }
75− }
76−}
app/src/main/java/soy/iko/opencode/data/repo/SearchHistoryStore.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.flow.MutableStateFlow
5−import kotlinx.coroutines.flow.StateFlow
6−import kotlinx.coroutines.flow.asStateFlow
7−import soy.iko.opencode.data.network.NetworkConfig
8−
9−/**
10− * Persists the most recent unique global-search queries so the search screen can
11− * surface them as suggestions. Backed by SharedPreferences because the UI needs the
12− * initial value synchronously and the list is tiny (≤ [MAX_ENTRIES]), mirroring the
13− * low-stakes-persistence rationale of [DraftStore]. `open` with a `protected`
14− * no-arg constructor so tests can subclass and override without a real Context.
15− */
16−open class SearchHistoryStore private constructor(
17− private val appContext: Context?,
18− @Suppress("unused") private val testMode: Boolean,
19−) {
20− constructor(context: Context) : this(context.applicationContext, false)
21− protected constructor() : this(null, true)
22−
23− private val prefs by lazy {
24− appContext?.getSharedPreferences("search_history", Context.MODE_PRIVATE)
25− ?: error("No context — override methods in test subclass")
26− }
27−
28− private val _queries = MutableStateFlow<List<String>>(emptyList())
29− open val queries: StateFlow<List<String>> = _queries.asStateFlow()
30−
31− init {
32− if (appContext != null) {
33− _queries.value = runCatching {
34− prefs.getString(KEY, null)
35− ?.takeIf { it.isNotBlank() }
36− ?.split(SEPARATOR)
37− ?.filter { it.isNotBlank() }
38− ?.take(MAX_ENTRIES)
39− }.getOrDefault(emptyList()) ?: emptyList()
40− }
41− }
42−
43− /** Insert [query] at the head of the history, deduped and capped at [MAX_ENTRIES].
44− * Blank or sub-min-length queries are ignored so accidental empties and stray
45− * keystrokes don't pollute the suggestions. */
46− open fun add(query: String) {
47− val trimmed = query.trim()
48− if (trimmed.isBlank() || trimmed.length < NetworkConfig.minSearchQueryLength) return
49− val updated = (listOf(trimmed) + _queries.value.filter { it != trimmed }).take(MAX_ENTRIES)
50− _queries.value = updated
51− runCatching {
52− prefs.edit().putString(KEY, updated.joinToString(SEPARATOR)).apply()
53− }
54− }
55−
56− open fun clear() {
57− _queries.value = emptyList()
58− runCatching { prefs.edit().remove(KEY).apply() }
59− }
60−
61− private companion object {
62− const val KEY = "queries"
63− // The search field is single-line, so a newline can't appear in a stored query
64− // and is safe to use as the list separator.
65− const val SEPARATOR = "\n"
66− const val MAX_ENTRIES = 10
67− }
68−}
app/src/main/java/soy/iko/opencode/data/repo/SessionPrefsStore.ktdeleted−73
@@ -1,73 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import androidx.datastore.preferences.core.edit
5−import androidx.datastore.preferences.core.stringSetPreferencesKey
6−import androidx.datastore.preferences.preferencesDataStore
7−import kotlinx.coroutines.flow.Flow
8−import kotlinx.coroutines.flow.flowOf
9−import kotlinx.coroutines.flow.map
10−
11−private val Context.sessionPrefsDataStore by preferencesDataStore(name = "session_prefs")
12−
13−/**
14− * Local, per-session organization flags the opencode server doesn't track: **pinned**
15− * (sorted to the top of the session list) and **archived** (hidden from the list unless the
16− * user opts to show them). Keyed by opencode session id.
17− *
18− * `open` with a `protected` no-arg constructor so tests can subclass and override the flows
19− * without a real DataStore (mirrors the other stores). The flow accessors are getters (not
20− * eager initializers) and null-guard the context so the test constructor never touches disk.
21− */
22−open class SessionPrefsStore private constructor(
23− private val appContext: Context?,
24− @Suppress("unused") private val testMode: Boolean,
25−) {
26− constructor(context: Context) : this(context.applicationContext, false)
27− protected constructor() : this(null, true)
28−
29− private val pinnedKey = stringSetPreferencesKey("pinned")
30− private val archivedKey = stringSetPreferencesKey("archived")
31− private val mutedKey = stringSetPreferencesKey("muted")
32−
33− open val pinned: Flow<Set<String>>
34− get() = appContext?.sessionPrefsDataStore?.data?.map { it[pinnedKey] ?: emptySet() }
35− ?: flowOf(emptySet())
36−
37− open val archived: Flow<Set<String>>
38− get() = appContext?.sessionPrefsDataStore?.data?.map { it[archivedKey] ?: emptySet() }
39− ?: flowOf(emptySet())
40−
41− /** Session ids the user has muted (suppress unread badge + completion notification). */
42− open val muted: Flow<Set<String>>
43− get() = appContext?.sessionPrefsDataStore?.data?.map { it[mutedKey] ?: emptySet() }
44− ?: flowOf(emptySet())
45−
46− open suspend fun setPinned(sessionId: String, pinned: Boolean) = toggle(pinnedKey, sessionId, pinned)
47−
48− open suspend fun setArchived(sessionId: String, archived: Boolean) = toggle(archivedKey, sessionId, archived)
49−
50− open suspend fun setMuted(sessionId: String, muted: Boolean) = toggle(mutedKey, sessionId, muted)
51−
52− /** Drop a session from all sets — call on deletion so ids don't accumulate forever. */
53− open suspend fun forget(sessionId: String) {
54− val ctx = appContext ?: return
55− ctx.sessionPrefsDataStore.edit { prefs ->
56− prefs[pinnedKey] = (prefs[pinnedKey] ?: emptySet()) - sessionId
57− prefs[archivedKey] = (prefs[archivedKey] ?: emptySet()) - sessionId
58− prefs[mutedKey] = (prefs[mutedKey] ?: emptySet()) - sessionId
59− }
60− }
61−
62− private suspend fun toggle(
63− key: androidx.datastore.preferences.core.Preferences.Key<Set<String>>,
64− sessionId: String,
65− on: Boolean,
66− ) {
67− val ctx = appContext ?: return
68− ctx.sessionPrefsDataStore.edit { prefs ->
69− val current = prefs[key] ?: emptySet()
70− prefs[key] = if (on) current + sessionId else current - sessionId
71− }
72− }
73−}
app/src/main/java/soy/iko/opencode/data/repo/SessionRepository.ktdeleted−665
@@ -1,665 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import soy.iko.opencode.data.model.AssistantMessage
4−import soy.iko.opencode.data.model.BusEvent
5−import soy.iko.opencode.data.model.FilePromptPart
6−import soy.iko.opencode.data.model.MessageInfo
7−import soy.iko.opencode.data.model.MessagePartRemoved
8−import soy.iko.opencode.data.model.MessagePartUpdated
9−import soy.iko.opencode.data.model.MessageRemoved
10−import soy.iko.opencode.data.model.MessageUpdated
11−import soy.iko.opencode.data.model.MessageWithParts
12−import soy.iko.opencode.data.model.ModelRef
13−import soy.iko.opencode.data.model.Part
14−import soy.iko.opencode.data.model.SessionError
15−import soy.iko.opencode.data.model.SessionIdle
16−import soy.iko.opencode.data.model.UnknownMessage
17−import soy.iko.opencode.data.network.EventStreamClient
18−import soy.iko.opencode.data.network.NetworkConfig
19−import soy.iko.opencode.data.network.OpencodeApiClient
20−import soy.iko.opencode.util.runCatchingCancellable
21−import soy.iko.opencode.util.safeExceptionSummary
22−import android.util.Log
23−import kotlinx.coroutines.CoroutineScope
24−import kotlinx.coroutines.Dispatchers
25−import kotlinx.coroutines.Job
26−import kotlinx.coroutines.NonCancellable
27−import kotlinx.coroutines.delay
28−import kotlinx.coroutines.withContext
29−import kotlinx.coroutines.channels.Channel
30−import kotlinx.coroutines.flow.Flow
31−import kotlinx.coroutines.flow.channelFlow
32−import kotlinx.coroutines.flow.consumeAsFlow
33−import kotlinx.coroutines.flow.conflate
34−import kotlinx.coroutines.flow.flowOn
35−import kotlinx.coroutines.launch
36−import kotlinx.coroutines.sync.Mutex
37−import kotlinx.coroutines.sync.withLock
38−
39−/**
40− * Source of truth for a session's conversation. It seeds from `GET /session/:id/message`
41− * and then reduces [BusEvent]s from the SSE stream into an ordered list of messages,
42− * each keyed by message id with parts keyed by part id (idempotent upserts).
43− */
44−open class SessionRepository(
45− private val api: OpencodeApiClient,
46− private val eventStream: EventStreamClient,
47− // Optional on-disk cache so a conversation renders instantly on open and stays readable
48− // offline. Null in tests (and any path that doesn't wire it), where caching is skipped.
49− private val messageCache: MessageCacheStore? = null,
50− // Profile the cache is namespaced under, so two servers with a colliding session id don't
51− // share a cache file. Empty in tests / when no cache is wired.
52− private val profileId: String = "",
53−) {
54− open suspend fun listSessions() = api.listSessions()
55− open suspend fun createSession(title: String? = null, directory: String? = null) =
56− api.createSession(title, directory)
57− open suspend fun deleteSession(id: String) = api.deleteSession(id)
58− open suspend fun abort(sessionId: String) = api.abort(sessionId)
59−
60− open suspend fun sendPrompt(
61− sessionId: String,
62− text: String,
63− attachments: List<FilePromptPart> = emptyList(),
64− model: ModelRef?,
65− agent: String? = null,
66− // Stable key for retriable/re-sendable messages (the offline outbox). See
67− // [OpencodeApiClient.sendPrompt]. Null generates a fresh key per call.
68− idempotencyKey: String? = null,
69− ) = api.sendPrompt(sessionId, text, attachments, model, agent, idempotencyKey)
70−
71− open suspend fun runCommand(
72− sessionId: String,
73− command: String,
74− arguments: String = "",
75− agent: String? = null,
76− ) = api.runCommand(sessionId, command, arguments = arguments, agent = agent)
77−
78− /**
79− * A live, ordered view of [sessionId]'s messages. Begins collecting the event
80− * stream before the initial REST load so no streamed part is missed, then reduces
81− * events into the in-memory state. The flow is conflated so a fast burst of
82− * streaming tokens (each publishing a fresh snapshot) never back-pressures the
83− * event reducer — a slow collector simply sees the most recent snapshot.
84− */
85− /** Per-subscription helper that persists reduced snapshots to [messageCache], throttled so a
86− * fast token stream doesn't hammer the disk, plus a NonCancellable teardown flush. Extracted
87− * from [observeMessages] so this cache-write branching lives in its own methods. [scope] is
88− * the channelFlow scope, so scheduled saves are torn down with the flow — the teardown flush
89− * re-persists a trailing write the cancellation dropped. */
90− private inner class CacheWriter(private val scope: CoroutineScope, private val sessionId: String) {
91− private var lastWrite = 0L
92− private var pending: Job? = null
93− // Most recent snapshot handed to [schedule], and the most recent one whose on-disk write
94− // completed. `saved` is assigned from inside the launched save *after* it returns, so a
95− // save cancelled mid-IO by teardown is NOT marked saved and [flushOnTeardown] re-persists
96− // it. Written from the save coroutines, read from the collector/teardown; the only race is
97− // a stale read causing one redundant, idempotent re-save (atomic temp+rename makes a
98− // duplicate write of identical data harmless) — never data loss.
99− private var latest: List<MessageWithParts>? = null
100− private var saved: List<MessageWithParts>? = null
101−
102− fun schedule(snapshot: List<MessageWithParts>) {
103− val cache = messageCache ?: return
104− if (snapshot.isEmpty()) return
105− latest = snapshot
106− val now = System.currentTimeMillis()
107− pending?.cancel()
108− // Immediate write once the throttle window has elapsed; otherwise a trailing-edge
109− // write so a burst that ends inside the window (a run's final tokens right after a
110− // write) still persists its last snapshot. A newer snapshot cancels and replaces a
111− // pending trailing write, so continuous streaming coalesces to one write per window.
112− val delayMs = if (now - lastWrite >= NetworkConfig.messageCacheWriteThrottleMs) {
113− lastWrite = now
114− 0L
115− } else {
116− NetworkConfig.messageCacheWriteThrottleMs
117− }
118− pending = scope.launch {
119− if (delayMs > 0) delay(delayMs)
120− cache.save(profileId, sessionId, snapshot)
121− saved = snapshot
122− }
123− }
124−
125− suspend fun flushOnTeardown() {
126− // Scheduled saves are children of [scope], so teardown cancels a pending trailing
127− // write before its delay elapses — a run's final tokens would never reach disk. Flush
128− // the latest un-saved snapshot under NonCancellable so it survives the cancellation.
129− val cache = messageCache ?: return
130− val pendingSnapshot = latest ?: return
131− if (pendingSnapshot !== saved) {
132− withContext(NonCancellable) { cache.save(profileId, sessionId, pendingSnapshot) }
133− }
134− }
135− }
136−
137− open fun observeMessages(sessionId: String): Flow<List<MessageWithParts>> = channelFlow {
138− val store = MessageStore()
139− val lock = Mutex()
140− // Conflated dirty signal: a burst of reduce()/seed() calls coalesces into a
141− // single snapshot+send per demand cycle. Previously every changed event called
142− // snapshot() — allocating an O(N) copy of the whole message list — and ~97% of
143− // those copies were immediately discarded by the outer .conflate() during fast
144− // streaming (hundreds of tokens/sec). Marking dirty and snapshotting in one
145− // drain loop means N events in a burst allocate ~1 snapshot, not N.
146− val dirty = Channel<Unit>(Channel.CONFLATED)
147−
148− // Mark the store dirty; the drain loop below snapshots and publishes. CONFLATED
149− // collapses repeated marks into a single pending signal, so a tight burst of
150− // events doesn't even allocate N marks.
151− fun publish() { dirty.trySend(Unit) }
152−
153− // Subscribe to events first so we don't miss early deltas during the initial load.
154− launch {
155− eventStream.events.collect { event ->
156− if (lock.withLock { store.reduce(sessionId, event) }) publish()
157− }
158− }
159−
160− // Seed generation counter, shared between the initial load and the reconnect
161− // re-seed. Guards against a stale fetch (from an earlier reconnect, or from a slow
162− // initial load) clobbering a newer seed. Only mutated/read under [lock].
163− var seedGeneration = 0
164−
165− // Message ids introduced by the on-disk cache seed below. The initial REST seed uses
166− // these to prune ghosts: a cache-seeded message absent from the authoritative REST
167− // snapshot was deleted server-side while the app was closed. Restricting the prune to
168− // cache-seeded ids means live SSE messages added since subscribe (not yet indexed by
169− // REST) are never dropped. Written/read only in this collector coroutine.
170− var cacheSeededIds: Set<String> = emptySet()
171−
172− // Seed from the on-disk cache first so the conversation renders instantly — and stays
173− // readable offline — before the network responds. Guarded on generation 0 so a
174− // reconnect re-seed that somehow raced ahead isn't clobbered; the initial REST seed
175− // (also generation 0) then overrides this with authoritative data when it succeeds.
176− messageCache?.let { cache ->
177− val cached = cache.load(profileId, sessionId)
178− if (cached.isNotEmpty()) {
179− val changed = lock.withLock {
180− if (seedGeneration == 0) {
181− cacheSeededIds = cached.mapTo(mutableSetOf()) { it.info.id }
182− store.seed(cached, clearPivot = false)
183− } else false
184− }
185− if (changed) publish()
186− }
187− }
188−
189− // Re-seed from REST when the SSE stream reconnects after a drop. The REST fetch
190− // is performed *outside* the lock so events arriving via SSE during the fetch are
191− // not blocked. The seed itself is under the lock; a seed generation counter ensures
192− // a stale fetch (from an earlier reconnect) doesn't clobber a newer one.
193− launch {
194− // Re-seed from REST when the SSE stream reconnects after a drop. The
195− // hasConnectedBefore flag is NOT reset on disconnect — it stays true after
196− // the first successful connection so a subsequent reconnect triggers the
197− // re-seed. Resetting it on disconnect would make the condition always false
198− // after the first cycle, turning the re-seed into dead code.
199− //
200− // A seed generation counter guards against a stale re-seed clobbering a
201− // newer one: if two reconnects fire in quick succession, the older fetch
202− // (which returns later) is discarded because its generation no longer matches.
203− var hasConnectedBefore = false
204− eventStream.state.collect { state ->
205− if (state == EventStreamClient.ConnectionState.Connected) {
206− if (hasConnectedBefore) {
207− // Pivot before the fetch: parts already in memory predate this
208− // snapshot and must yield to it, while parts that stream in during
209− // the fetch (added to streamedSincePivot via reduce) outrank it.
210− // Bump the generation under the same lock so the compare in the
211− // initial seed sees a consistent value.
212− val generation = lock.withLock {
213− store.beginReseed()
214− ++seedGeneration
215− }
216− val fresh = runCatchingCancellable { api.listMessages(sessionId) }
217− .onFailure { Log.w("SessionRepository", "Re-seed message load failed for $sessionId; relying on SSE: ${safeExceptionSummary(it)}") }
218− .getOrDefault(emptyList())
219− var seedChanged = false
220− lock.withLock {
221− if (generation == seedGeneration) {
222− // Prune cache-seeded ghosts here too, not only in the initial
223− // REST seed. If the SSE stream connected→dropped→reconnected
224− // before the initial listMessages returned, seedGeneration was
225− // already >0 by the time the initial seed ran, so its prune was
226− // skipped (the `seedGeneration == 0` guard below). Without this
227− // prune, messages deleted server-side while the app was closed
228− // would survive as ghosts until a future app restart where the
229− // timing happened not to recur.
230− val pruned = store.pruneStaleCacheSeeded(cacheSeededIds, fresh)
231− // Merge without pruning: SSE events arriving during the
232− // REST fetch may have added messages not yet indexed by
233− // the REST endpoint. Pruning would silently delete them.
234− // Stale messages from deletions during the disconnect
235− // gap are eventually removed via MessageRemoved events
236− // or on the next app restart.
237− val seeded = store.seed(fresh, prune = false)
238− seedChanged = pruned || seeded
239− }
240− }
241− if (seedChanged) publish()
242− }
243− hasConnectedBefore = true
244− }
245− }
246− }
247−
248− // Load the authoritative message list concurrently with the drain loop below so the
249− // cache seed and any early SSE-reduced parts are emitted immediately. Running it inline
250− // here (before the drain starts) would withhold the already-reduced cached conversation
251− // until this fetch resolved — a blank screen for the whole withRetry backoff when offline.
252− launch {
253− val initialResult = runCatchingCancellable { api.listMessages(sessionId) }
254− .onFailure { Log.w("SessionRepository", "Initial message load failed for $sessionId; relying on cache/SSE: ${safeExceptionSummary(it)}") }
255− // Apply the initial seed only if no reconnect re-seed has run yet (generation still 0).
256− // A re-seed is always a fresher full snapshot, so if the (possibly slow) initial fetch
257− // returns after one has applied, seeding this older REST data would clobber the newer
258− // state — reverting a completed run to "running", regressing cost/token/part state —
259− // until the next SSE event or reconnect healed it. Only seed on SUCCESS: on failure
260− // (e.g. offline) keep whatever's shown (the cache seed above) rather than clearing it.
261− val seeded = lock.withLock {
262− val list = initialResult.getOrNull()
263− if (seedGeneration == 0 && list != null) {
264− // Prune ghosts first: cache-seeded messages absent from this authoritative
265− // REST snapshot were deleted server-side while the app was closed. Without
266− // this they'd survive restart forever (re-seeded from cache, never pruned by
267− // the reconnect path, and re-persisted by the drain loop).
268− val pruned = store.pruneStaleCacheSeeded(cacheSeededIds, list)
269− val changed = store.seed(list)
270− pruned || changed
271− } else false
272− }
273− if (seeded) publish()
274− }
275−
276− // Single drain: one snapshot+send per conflated dirty signal. The snapshot is
277− // taken under the lock so a reader never sees a half-reduced state; send() runs
278− // outside the lock so a slow downstream collector can't stall the drain. This
279− // loop also keeps the flow alive until the collector cancels; the launched jobs
280− // above are children of this scope and are torn down with it.
281− // Per-subscription cache writer: throttled snapshot persistence + a NonCancellable
282− // teardown flush. `this` is the channelFlow scope, so its scheduled saves are torn down
283− // with the flow (the teardown flush re-persists a cancelled trailing write).
284− val cacheWriter = CacheWriter(this, sessionId)
285− // Guarantee at least one emission even when nothing seeds the store: with no on-disk
286− // cache, a failing initial REST load (swallowed above), and a quiet SSE stream, none of
287− // the seed paths publish, so the flow would emit nothing at all. The sole collector
288− // (ChatViewModel) only clears its loading spinner on an emission, so without this a
289− // first-open of an erroring/empty session spins forever with no way to reach the
290− // "Failed to load / Retry" affordance. CONFLATED dirty coalesces this with any seed
291− // publish into a single send.
292− publish()
293− try {
294− dirty.consumeAsFlow().collect {
295− val snapshot = lock.withLock { store.snapshot() }
296− send(snapshot)
297− // Persist to the on-disk cache, throttled so a fast token stream doesn't hammer
298− // the disk — the cache only needs to be "recent enough" for an instant/offline
299− // first paint; the network corrects it on the next open.
300− cacheWriter.schedule(snapshot)
301− }
302− } finally {
303− cacheWriter.flushOnTeardown()
304− }
305− // Run the whole reducer pipeline — event reduction, list rebuilds, and the O(N)
306− // snapshot copy — on Dispatchers.Default rather than the collector's context. The
307− // sole consumer collects via stateIn(viewModelScope), i.e. Main.immediate, so without
308− // this every streamed token's reduce()/snapshot() would execute on the UI thread
309− // (hundreds/sec on a fast run). The seed REST calls here only suspend, so moving them
310− // off Main is harmless. JSON decoding already runs off-Main upstream in EventStreamClient.
311− }.flowOn(Dispatchers.Default).conflate()
312−
313− companion object {
314− /** Convenience: is this event a run-completion signal for [sessionId]?
315− * A null sessionID is NOT treated as a wildcard — an idle event with no
316− * session id must not reset the running state of every open chat. */
317− fun isIdle(event: BusEvent, sessionId: String): Boolean =
318− event is SessionIdle && event.properties.sessionID == sessionId
319−
320− fun isError(event: BusEvent, sessionId: String): Boolean =
321− event is SessionError && event.properties.sessionID == sessionId
322−
323− /** Does this event indicate an in-progress run for [sessionId]? A live streamed part or
324− * an assistant message that isn't yet complete/errored means the agent is still working.
325− * Used to restore the "running" indicator after an SSE reconnect: if the run is still
326− * going, such live events keep arriving; a run that finished during the outage produces
327− * none (its completion arrives via the REST re-seed, not the event stream). */
328− fun isRunActivity(event: BusEvent, sessionId: String): Boolean = when (event) {
329− // The session id rides on the part for message.part.updated; properties.sessionID
330− // is null on the wire. Mirror reduce()'s `part.sessionID ?: properties.sessionID`
331− // so a run that's only streaming parts still re-lights the indicator on reconnect.
332− is MessagePartUpdated -> (event.properties.part.sessionID ?: event.properties.sessionID) == sessionId
333− is MessageUpdated -> {
334− val info = event.properties.info
335− info.sessionID == sessionId && info is AssistantMessage && !info.isComplete && info.error == null
336− }
337− else -> false
338− }
339− }
340−}
341−
342−/**
343− * In-memory reduction state for one observed session. Not thread-safe; guard with a Mutex.
344− * Exposed as `internal` so the reducer logic can be unit-tested directly.
345− */
346−internal class MessageStore {
347− // messageId -> mutable holder (info + insertion-ordered parts); the map itself is
348− // insertion-ordered.
349− private val messages = LinkedHashMap<String, Holder>()
350−
351− /**
352− * Mutable per-message holder. Parts live in an insertion-ordered map keyed by part id, so a
353− * streamed part update is an O(1) put instead of an O(P) list rebuild. The immutable
354− * [MessageWithParts] view is materialized lazily and cached until the next mutation — so a
355− * burst of streamed token updates rebuilds a message's part list at most once per published
356− * [snapshot], not once per token. The cached view is also reference-stable across snapshots
357− * while unchanged, so Compose skips recomposing bubbles that didn't change.
358− */
359− private class Holder(var info: MessageInfo, val parts: LinkedHashMap<String, Part>) {
360− private var cached: MessageWithParts? = null
361− fun view(): MessageWithParts =
362− cached ?: MessageWithParts(info, parts.values.toList()).also { cached = it }
363− /** Adopt an existing immutable instance as the cache — avoids an immediate rebuild and
364− * preserves its identity (e.g. when seeding an authoritative REST snapshot). */
365− fun adopt(m: MessageWithParts) { cached = m }
366− fun invalidate() { cached = null }
367− }
368−
369− /** Build a [Holder] from an immutable message, reusing [m] itself as the cached view. */
370− private fun holderOf(m: MessageWithParts): Holder {
371− val parts = LinkedHashMap<String, Part>(m.parts.size)
372− for (p in m.parts) parts[p.id] = p
373− return Holder(m.info, parts).also { it.adopt(m) }
374− }
375−
376− /** Part ids upserted via [reduce] since the last reseed pivot ([beginReseed]) or seed.
377− * On a reconnect re-seed these are the parts that streamed in *during* the REST fetch,
378− * so they're newer than the snapshot and must win over it; every other part is taken
379− * from the authoritative REST snapshot. Without this distinction the merge kept every
380− * overlapping in-memory part, so a part that changed server-side during the disconnect
381− * (e.g. a tool going running -> completed) stayed stale until app restart. */
382− private val streamedSincePivot = mutableSetOf<String>()
383−
384− /** Message ids whose `info` was updated via a live SSE [reduce] since the last reseed
385− * pivot ([beginReseed]) or seed. Parallels [streamedSincePivot] but for message info:
386− * on a reconnect re-seed these are the messages whose info changed *during* the REST
387− * fetch, so the in-memory info is newer than the snapshot and must win; every other
388− * message's info is taken from the authoritative REST snapshot. Without this the merge
389− * kept the in-memory info, so a run that finished server-side during the disconnect
390− * (e.g. cost/token totals, completion time) stayed stale until app restart. */
391− private val messageInfoUpdatedSincePivot = mutableSetOf<String>()
392−
393− /** Mark the point a reconnect re-seed's REST fetch begins: parts/info streamed from here
394− * on are newer than the fetched snapshot. Call under the same lock as [seed]/[reduce]. */
395− fun beginReseed() {
396− streamedSincePivot.clear()
397− messageInfoUpdatedSincePivot.clear()
398− }
399−
400− /** Maximum number of messages to keep in memory; oldest are evicted when exceeded. */
401− internal val maxMessages = NetworkConfig.maxInMemoryMessages
402−
403− fun snapshot(): List<MessageWithParts> = messages.values.map { it.view() }
404−
405− fun seed(initial: List<MessageWithParts>, prune: Boolean = false, clearPivot: Boolean = true): Boolean {
406− var changed = false
407− // On re-seed (after SSE reconnect), remove messages that are no longer in the
408− // server snapshot (e.g. deleted during the disconnection gap). This keeps the
409− // in-memory state in sync with the authoritative REST snapshot rather than
410− // accumulating stale messages forever. Skipped on the initial seed to avoid
411− // racing with just-arrived SSE events whose messages may not yet be in REST.
412− if (prune) {
413− val incomingIds = initial.mapTo(mutableSetOf()) { it.info.id }
414− val before = messages.size
415− messages.keys.retainAll(incomingIds)
416− if (messages.size != before) changed = true
417− }
418−
419− for (m in initial) {
420− val key = syntheticKeyFor(m)
421− val existing = messages[key]
422− if (existing == null) {
423− messages[key] = holderOf(m)
424− changed = true
425− } else {
426− // A part streamed in between subscribe and this initial load may already
427− // have populated this message (see observeMessages). Merge instead of
428− // overwriting so that newer streamed part isn't discarded: take the
429− // snapshot's part order, swap in the streamed version where ids overlap,
430− // append any streamed-only parts, and adopt the authoritative REST info.
431− val streamedById = existing.parts
432− val snapshotIds = m.parts.mapTo(mutableSetOf()) { it.id }
433− // Prefer the in-memory version of an overlapping part ONLY if it streamed
434− // in since the reseed pivot (i.e. during this fetch), so it's newer than
435− // the snapshot. Otherwise the REST snapshot is authoritative and wins,
436− // discarding an in-memory part that went stale during a disconnect.
437− val ordered = m.parts.map { p ->
438− if (p.id in streamedSincePivot) streamedById[p.id] ?: p else p
439− }.toMutableList()
440− // Append only parts that streamed in *since the pivot* and are absent from the
441− // snapshot — i.e. genuinely newer than this REST fetch. A part in memory from
442− // before the pivot that the snapshot omits was removed server-side; the
443− // authoritative REST snapshot must be allowed to drop it, else it reappears as
444− // a ghost and gets baked into the on-disk cache forever.
445− for (p in existing.parts.values) {
446− if (p.id !in snapshotIds && p.id in streamedSincePivot) ordered.add(p)
447− }
448− // Adopt the authoritative REST info unless the in-memory info was itself
449− // updated live since the pivot (i.e. during this fetch), in which case it's
450− // newer than the snapshot. Otherwise the REST snapshot wins.
451− val info = if (existing.info is UnknownMessage || m.info.id !in messageInfoUpdatedSincePivot) m.info else existing.info
452− val merged = MessageWithParts(info = info, parts = ordered)
453− if (merged != existing.view()) {
454− // Store under `key` (the synthetic key for an empty-id UnknownMessage),
455− // not `m.info.id` (which is "" for such a message and would collide).
456− messages[key] = holderOf(merged)
457− changed = true
458− }
459− }
460− }
461− // A part that streamed in *before* this initial load (observeMessages subscribes to
462− // SSE before fetching) inserts its message at the front of the insertion-ordered map,
463− // and the merge above keeps that position — pinning a running message above the older
464− // history that seed() inserts afterward. Restore chronological order by creation time
465− // FIRST, so eviction below drops the genuinely-oldest entries: evictOldMessages()
466− // removes from the map's front, which before reordering is the newest streamed message.
467− if (reorderByTime()) changed = true
468− if (evictOldMessages()) changed = true
469− // Reset the pivot: everything just merged is now the baseline, so only parts/info
470− // that stream in *after* this seed can outrank the next reconnect's snapshot. The
471− // on-disk cache seed passes clearPivot = false: it runs *before* the authoritative
472− // initial REST seed, so clearing here would strip pivot protection from SSE parts/info
473− // that streamed in since subscribe, letting that REST seed regress them.
474− if (clearPivot) {
475− streamedSincePivot.clear()
476− messageInfoUpdatedSincePivot.clear()
477− }
478− return changed
479− }
480−
481− /** Remove messages that were seeded from the on-disk cache ([cacheSeededIds]) but are
482− * absent from the authoritative REST snapshot [rest] — i.e. deleted server-side while the
483− * app was closed. Restricted to cache-seeded ids so a message added by a live SSE event
484− * since subscribe (which the REST endpoint may not have indexed yet) is never pruned.
485− * This is what actually removes ghosts on restart; the reconnect re-seed deliberately
486− * keeps prune=false to avoid racing just-arrived SSE. Call under the same lock as [seed].
487− * Returns true if anything was removed. */
488− fun pruneStaleCacheSeeded(cacheSeededIds: Set<String>, rest: List<MessageWithParts>): Boolean {
489− if (cacheSeededIds.isEmpty()) return false
490− val restIds = rest.mapTo(mutableSetOf()) { it.info.id }
491− var changed = false
492− for (id in cacheSeededIds) {
493− if (id !in restIds && messages.remove(id) != null) changed = true
494− }
495− return changed
496− }
497−
498− /** Resolve the map key for a seed entry. An UnknownMessage with an empty id (from an
499− * unrecognized server role with no id field) was stored by handleMessageUpdated under a
500− * synthetic key ("unknown-c<created>" or "unknown-h<hash>"); derive the same key here so
501− * a REST seed merges onto the existing holder instead of missing it and inserting a
502− * duplicate under key "". */
503− private fun syntheticKeyFor(m: MessageWithParts): String =
504− if (m.info.id.isEmpty() && m.info is UnknownMessage) {
505− m.info.time?.created?.let { "unknown-c$it" } ?: "unknown-h${m.info.hashCode()}"
506− } else {
507− m.info.id
508− }
509−
510− /** Reorder the message map by message creation time (stable). Ties and entries with no
511− * server time yet (e.g. a brand-new message still streaming and not in REST) keep their
512− * relative order, so such a message stays last. Preserves each entry's map key so the
513− * synthetic UnknownMessage keys aren't collapsed. Returns true if the order changed. */
514− private fun reorderByTime(): Boolean {
515− val entries = messages.entries.map { it.key to it.value }
516− val sorted = entries.sortedBy { it.second.info.time?.created ?: Long.MAX_VALUE }
517− // Detect a reordering by comparing keys positionally, instead of allocating two more
518− // N-sized key lists just to compare them.
519− var changed = false
520− for (i in sorted.indices) {
521− if (sorted[i].first != entries[i].first) { changed = true; break }
522− }
523− if (!changed) return false
524− messages.clear()
525− for ((k, v) in sorted) messages[k] = v
526− return true
527− }
528−
529− /** Returns true if the state changed (and a new snapshot should be published). */
530− fun reduce(sessionId: String, event: BusEvent): Boolean {
531− return when (event) {
532− is MessageUpdated -> handleMessageUpdated(sessionId, event)
533−
534− is MessagePartUpdated -> {
535− val part = event.properties.part
536− val messageId = part.messageID ?: event.properties.messageID
537− val partSession = part.sessionID ?: event.properties.sessionID
538− when {
539− messageId == null -> false
540− partSession != null -> if (partSession == sessionId) upsertPart(messageId, part) else false
541− // No session id anywhere on the event: a null session is NOT a wildcard
542− // (mirroring isIdle/isError). Every open session's store sees the shared
543− // event stream, so accepting it unconditionally would leak the part into
544− // unrelated conversations (e.g. both panes in two-pane mode). Attribute it
545− // only if this store already holds the parent message — MessageUpdated,
546− // which always carries a session id, will have created it here first.
547− else -> if (messages.containsKey(messageId)) upsertPart(messageId, part) else false
548− }
549− }
550−
551− is MessagePartRemoved -> handlePartRemoved(sessionId, event)
552−
553− is MessageRemoved -> handleMessageRemoved(sessionId, event)
554−
555− else -> false
556− }
557− }
558−
559− private fun handleMessageUpdated(sessionId: String, event: MessageUpdated): Boolean {
560− val info = event.properties.info
561− if (info.sessionID != sessionId) return false
562− // An UnknownMessage with an empty id (e.g. from an unrecognized server role with no id
563− // field) would collide with other such messages in the map. It carries no id, only
564− // sessionID/time, so derive a synthetic key. Prefer the immutable creation timestamp: it's
565− // stable across updates, so a later update to the SAME unknown message (whose `time.updated`
566− // or `time.completed` changes) coalesces onto its holder via the existing==info guard below
567− // instead of forking a duplicate — the failure mode a full-content hash has, since any
568− // content change moves the hash. Distinct unknown messages still separate by their distinct
569− // creation times; only when even `created` is absent do we fall back to the content hash.
570− val key = if (info.id.isEmpty() && info is UnknownMessage) {
571− info.time?.created?.let { "unknown-c$it" } ?: "unknown-h${info.hashCode()}"
572− } else {
573− info.id
574− }
575− val existing = messages[key]
576− // A server re-sending byte-identical info is a no-op: skip it so we don't publish a
577− // redundant snapshot (mirrors upsertPart's identical-part guard).
578− if (existing != null && existing.info == info) return false
579− if (existing == null) {
580− messages[key] = Holder(info, LinkedHashMap())
581− } else {
582− existing.info = info
583− existing.invalidate()
584− }
585− // Record that this message's info streamed in live, so a re-seed after a reconnect knows
586− // it's newer than the REST snapshot and keeps it (see seed()/beginReseed()).
587− messageInfoUpdatedSincePivot.add(key)
588− if (existing == null) evictOldMessages()
589− return true
590− }
591−
592− /** Returns false if [eventSession] is non-null and doesn't match [sessionId]. */
593− private fun matchesSession(eventSession: String?, sessionId: String): Boolean =
594− eventSession == null || eventSession == sessionId
595−
596− private fun handlePartRemoved(sessionId: String, event: MessagePartRemoved): Boolean {
597− val messageId = event.properties.messageID ?: return false
598− val partId = event.properties.partID ?: return false
599− if (!matchesSession(event.properties.sessionID, sessionId)) return false
600− return removePart(messageId, partId)
601− }
602−
603− private fun handleMessageRemoved(sessionId: String, event: MessageRemoved): Boolean {
604− val id = event.properties.messageID ?: return false
605− if (!matchesSession(event.properties.sessionID, sessionId)) return false
606− val removed = messages.remove(id) ?: return false
607− messageInfoUpdatedSincePivot.remove(id)
608− removed.parts.keys.forEach { streamedSincePivot.remove(it) }
609− return true
610− }
611−
612− private fun upsertPart(messageId: String, part: Part): Boolean {
613− val current = messages[messageId]
614− if (current != null) {
615− // O(1) map lookup + put, vs the former O(P) indexOfFirst scan and full-list copy
616− // on every streamed token. A LinkedHashMap re-put keeps the part's original
617− // position (replace-in-place); a new id is appended — matching the old list order.
618− if (current.parts[part.id] == part) return false
619− current.parts[part.id] = part
620− current.invalidate()
621− } else {
622− val parts = LinkedHashMap<String, Part>()
623− parts[part.id] = part
624− messages[messageId] = Holder(
625− info = UnknownMessage(id = messageId, sessionID = part.sessionID ?: ""),
626− parts = parts,
627− )
628− }
629− // Record that this part streamed in, so a re-seed after a reconnect knows it's
630− // newer than the REST snapshot and keeps it (see seed()/beginReseed()).
631− streamedSincePivot.add(part.id)
632− if (current == null) evictOldMessages()
633− return true
634− }
635−
636− private fun removePart(messageId: String, partId: String): Boolean {
637− val current = messages[messageId] ?: return false
638− if (current.parts.remove(partId) == null) return false
639− // Drop the pivot entry too so the set doesn't accumulate ids of removed parts for
640− // the rest of the session (it's otherwise only cleared on reseed/eviction). No
641− // correctness impact today — a stale entry just falls back to the REST snapshot's
642− // version in seed() — but keeping it symmetric with handleMessageRemoved/eviction
643− // bounds the set's growth over a long-lived session.
644− streamedSincePivot.remove(partId)
645− current.invalidate()
646− return true
647− }
648−
649− /** Evict the oldest messages when the store exceeds [maxMessages], keeping memory bounded.
650− * Returns true if any messages were evicted. */
651− private fun evictOldMessages(): Boolean {
652− var evicted = false
653− while (messages.size > maxMessages) {
654− val oldestKey = messages.keys.iterator().next()
655− val removed = messages.remove(oldestKey)
656− // Prune the evicted message's pivot bookkeeping so these sets don't grow
657− // unbounded over a long-running session that never reconnects (they're only
658− // otherwise cleared on reseed/seed).
659− messageInfoUpdatedSincePivot.remove(oldestKey)
660− removed?.parts?.keys?.forEach { streamedSincePivot.remove(it) }
661− evicted = true
662− }
663− return evicted
664− }
665−}
app/src/main/java/soy/iko/opencode/data/repo/SettingsStore.ktdeleted−279
@@ -1,279 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import androidx.datastore.preferences.core.booleanPreferencesKey
5−import androidx.datastore.preferences.core.edit
6−import androidx.datastore.preferences.core.floatPreferencesKey
7−import androidx.datastore.preferences.core.intPreferencesKey
8−import androidx.datastore.preferences.core.stringPreferencesKey
9−import androidx.datastore.preferences.preferencesDataStore
10−import kotlinx.coroutines.flow.Flow
11−import kotlinx.coroutines.flow.map
12−
13−enum class ThemeMode { SYSTEM, LIGHT, DARK, AMOLED }
14−
15−private val Context.settingsDataStore by preferencesDataStore(name = "settings")
16−
17−/** App-preferences store: theme mode, dynamic color (Material You), input behavior. */
18−@Suppress("TooManyFunctions")
19−class SettingsStore(context: Context) {
20−
21− private val appContext = context.applicationContext
22− private val themeKey = stringPreferencesKey("theme_mode")
23− private val dynamicColorKey = booleanPreferencesKey("dynamic_color")
24− private val sendOnEnterKey = booleanPreferencesKey("send_on_enter")
25− private val appLockKey = booleanPreferencesKey("app_lock")
26− private val appLockReLockSecondsKey = intPreferencesKey("app_lock_relock_seconds")
27− private val chatTextScaleKey = floatPreferencesKey("chat_text_scale")
28− private val codeWrapKey = booleanPreferencesKey("code_wrap")
29− private val sessionSortModeKey = stringPreferencesKey("session_sort_mode")
30− private val sessionSortDescendingKey = booleanPreferencesKey("session_sort_descending")
31− private val sessionShowArchivedKey = booleanPreferencesKey("session_show_archived")
32− private val preferredModelIdKey = stringPreferencesKey("preferred_model_id")
33− private val preferredAgentNameKey = stringPreferencesKey("preferred_agent_name")
34− private val compactMessageSpacingKey = booleanPreferencesKey("compact_message_spacing")
35− private val hapticsEnabledKey = booleanPreferencesKey("haptics_enabled")
36− private val reducedMotionKey = booleanPreferencesKey("reduced_motion")
37− private val languageOverrideKey = stringPreferencesKey("language_override")
38− private val notifRunCompleteKey = booleanPreferencesKey("notif_run_complete")
39− private val notifPermissionKey = booleanPreferencesKey("notif_permission")
40− private val notifErrorKey = booleanPreferencesKey("notif_error")
41− private val swipeLeftActionKey = stringPreferencesKey("swipe_left_action")
42− private val swipeRightActionKey = stringPreferencesKey("swipe_right_action")
43−
44− companion object {
45− /** Bounds for the chat text-size multiplier so the UI can't be scaled into
46− * unreadability or an unusable micro-font. 1.0 is the design default. */
47− const val MIN_CHAT_TEXT_SCALE = 0.8f
48− const val MAX_CHAT_TEXT_SCALE = 1.6f
49− const val DEFAULT_CHAT_TEXT_SCALE = 1.0f
50− /** 0 means re-lock the instant the app backgrounds. Other entries are the grace
51− * period (seconds) during which a quick app-switch does NOT re-prompt for auth. */
52− val APP_LOCK_RELOCK_OPTIONS_SECONDS: List<Int> = listOf(0, 30, 60, 300, 1800, 3600)
53− const val DEFAULT_APP_LOCK_RELOCK_SECONDS = 0
54− }
55−
56− val themeMode: Flow<ThemeMode> = appContext.settingsDataStore.data.map { prefs ->
57− runCatching { ThemeMode.valueOf(prefs[themeKey] ?: ThemeMode.SYSTEM.name) }
58− .getOrDefault(ThemeMode.SYSTEM)
59− }
60−
61− // Default OFF so the app ships with its hand-built "Tokyo Night" brand palette rather than
62− // the wallpaper-derived Material You scheme, which fully replaces the brand colours. Users
63− // on Android 12+ can still opt into dynamic color from Settings.
64− val dynamicColor: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
65− prefs[dynamicColorKey] ?: false
66− }
67−
68− /** When true, the hardware Enter key sends the prompt; when false, Enter inserts a
69− * newline and Ctrl+Enter sends. Soft-keyboard IME action always sends. Defaults to
70− * true to match the prior hardcoded behavior. */
71− val sendOnEnter: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
72− prefs[sendOnEnterKey] ?: true
73− }
74−
75− /** When true, the app requires device biometric/credential authentication on launch
76− * (and when returning from the background) before the UI is shown, protecting the
77− * stored server credentials. Defaults to false so the app is usable out of the box. */
78− val appLock: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
79− prefs[appLockKey] ?: false
80− }
81−
82− /** Grace period (seconds) before re-locking after the app backgrounds. 0 = re-lock
83− * immediately (the prior behavior). Lets a quick app-switch not re-prompt, which is the
84− * standard reason users disable biometric locks in messaging/banking apps. */
85− val appLockReLockSeconds: Flow<Int> = appContext.settingsDataStore.data.map { prefs ->
86− prefs[appLockReLockSecondsKey] ?: DEFAULT_APP_LOCK_RELOCK_SECONDS
87− }
88−
89− /** Multiplier applied to chat message (markdown) and code text so users can size the
90− * conversation for readability independently of the system font scale. Clamped to
91− * [[MIN_CHAT_TEXT_SCALE], [MAX_CHAT_TEXT_SCALE]] on read so a corrupt/out-of-range
92− * stored value can never produce an unreadable UI. Defaults to 1.0 (design size). */
93− val chatTextScale: Flow<Float> = appContext.settingsDataStore.data.map { prefs ->
94− (prefs[chatTextScaleKey] ?: DEFAULT_CHAT_TEXT_SCALE)
95− .coerceIn(MIN_CHAT_TEXT_SCALE, MAX_CHAT_TEXT_SCALE)
96− }
97−
98− /** When true, fenced/indented code blocks soft-wrap long lines instead of scrolling
99− * horizontally. Defaults to false (horizontal scroll) to preserve code formatting. */
100− val codeWrap: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
101− prefs[codeWrapKey] ?: false
102− }
103−
104− /** Persisted session-list sort mode so a chosen ordering survives process death (not just
105− * rotation). Stored as the enum name; an unknown value falls back to RECENT. */
106− val sessionSortMode: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
107− prefs[sessionSortModeKey] ?: "RECENT"
108− }
109−
110− /** Persisted session-list sort direction. Defaults to descending (newest first). */
111− val sessionSortDescending: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
112− prefs[sessionSortDescendingKey] ?: true
113− }
114−
115− /** Persisted "show archived sessions" toggle so the choice survives process death. */
116− val sessionShowArchived: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
117− prefs[sessionShowArchivedKey] ?: false
118− }
119−
120− /** Preferred default model id for new sessions. Empty means "use the server default".
121− * A user who always picks a specific model doesn't have to pick it every session. */
122− val preferredModelId: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
123− prefs[preferredModelIdKey] ?: ""
124− }
125−
126− /** Preferred default agent name for new sessions. Empty means "use the server default". */
127− val preferredAgentName: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
128− prefs[preferredAgentNameKey] ?: ""
129− }
130−
131− /** When true, chat message bubbles use a tighter vertical spacing (8dp vs the default 16dp)
132− * so power users can fit more conversation on screen. Defaults to false (the design default). */
133− val compactMessageSpacing: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
134− prefs[compactMessageSpacingKey] ?: false
135− }
136−
137− /** When true, haptic feedback is fired on taps and confirmations. Defaults to true (the
138− * existing behavior). An in-app toggle lets users disable haptics without turning off
139− * system-wide vibration. Read by a CompositionLocal that gates haptic calls. */
140− val hapticsEnabled: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
141− prefs[hapticsEnabledKey] ?: true
142− }
143−
144− /** When true, animations and transitions are limited (collapsed to instant/snap).
145− * Defaults to false — the app already honors the system Developer Options animator
146− * scale, but this gives users an in-app toggle without disabling motion OS-wide.
147− * Read by a CompositionLocal that gates animation specs. */
148− val reducedMotion: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
149− prefs[reducedMotionKey] ?: false
150− }
151−
152− /** Override the app language (an ISO 639-1 code like "en" or "es", or empty for the
153− * system default). Applied via AppCompat's per-app language API so the OS can
154− * handle locale resolution without an app restart on Android 13+. */
155− val languageOverride: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
156− prefs[languageOverrideKey] ?: ""
157− }
158−
159− /** Granular notification toggles. Each gates a notification channel's posting so a user
160− * can mute specific notification types in-app (in addition to the OS channel controls).
161− * Default true for all (matching the prior "always post" behavior). */
162− val notifRunComplete: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
163− prefs[notifRunCompleteKey] ?: true
164− }
165− val notifPermission: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
166− prefs[notifPermissionKey] ?: true
167− }
168− val notifError: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
169− prefs[notifErrorKey] ?: true
170− }
171−
172− /** Remappable swipe actions for the session list. Stored as the SwipeAction enum name;
173− * an unknown value falls back to the default. Defaults: left=DELETE, right=ARCHIVE
174− * (matching the prior hardcoded behavior). */
175− val swipeLeftAction: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
176− prefs[swipeLeftActionKey] ?: SwipeAction.DELETE.name
177− }
178− val swipeRightAction: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
179− prefs[swipeRightActionKey] ?: SwipeAction.ARCHIVE.name
180− }
181−
182− suspend fun setThemeMode(mode: ThemeMode) {
183− appContext.settingsDataStore.edit { it[themeKey] = mode.name }
184− }
185−
186− suspend fun setDynamicColor(enabled: Boolean) {
187− appContext.settingsDataStore.edit { it[dynamicColorKey] = enabled }
188− }
189−
190− suspend fun setSendOnEnter(enabled: Boolean) {
191− appContext.settingsDataStore.edit { it[sendOnEnterKey] = enabled }
192− }
193−
194− suspend fun setAppLock(enabled: Boolean) {
195− appContext.settingsDataStore.edit { it[appLockKey] = enabled }
196− }
197−
198− suspend fun setAppLockReLockSeconds(seconds: Int) {
199− appContext.settingsDataStore.edit {
200− it[appLockReLockSecondsKey] = APP_LOCK_RELOCK_OPTIONS_SECONDS.minBy { k -> Math.abs(k - seconds) }
201− }
202− }
203−
204− suspend fun setChatTextScale(scale: Float) {
205− appContext.settingsDataStore.edit {
206− it[chatTextScaleKey] = scale.coerceIn(MIN_CHAT_TEXT_SCALE, MAX_CHAT_TEXT_SCALE)
207− }
208− }
209− suspend fun setCodeWrap(enabled: Boolean) {
210− appContext.settingsDataStore.edit {
211− it[codeWrapKey] = enabled
212− }
213− }
214−
215− suspend fun setSessionSortMode(mode: String) {
216− appContext.settingsDataStore.edit { it[sessionSortModeKey] = mode }
217− }
218−
219− suspend fun setSessionSortDescending(descending: Boolean) {
220− appContext.settingsDataStore.edit { it[sessionSortDescendingKey] = descending }
221− }
222− suspend fun setSessionShowArchived(show: Boolean) {
223− appContext.settingsDataStore.edit {
224− it[sessionShowArchivedKey] = show
225− }
226− }
227−
228− suspend fun setPreferredModelId(modelId: String) {
229− appContext.settingsDataStore.edit {
230− if (modelId.isEmpty()) it.remove(preferredModelIdKey) else it[preferredModelIdKey] = modelId
231− }
232− }
233−
234− suspend fun setPreferredAgentName(agentName: String) {
235− appContext.settingsDataStore.edit {
236− if (agentName.isEmpty()) it.remove(preferredAgentNameKey) else it[preferredAgentNameKey] = agentName
237− }
238− }
239−
240− suspend fun setCompactMessageSpacing(enabled: Boolean) {
241− appContext.settingsDataStore.edit {
242− it[compactMessageSpacingKey] = enabled
243− }
244− }
245−
246− suspend fun setHapticsEnabled(enabled: Boolean) {
247− appContext.settingsDataStore.edit { it[hapticsEnabledKey] = enabled }
248− }
249−
250− suspend fun setReducedMotion(enabled: Boolean) {
251− appContext.settingsDataStore.edit { it[reducedMotionKey] = enabled }
252− }
253−
254− suspend fun setLanguageOverride(code: String) {
255− appContext.settingsDataStore.edit {
256− if (code.isEmpty()) it.remove(languageOverrideKey) else it[languageOverrideKey] = code
257− }
258− }
259−
260− suspend fun setNotifRunComplete(enabled: Boolean) {
261− appContext.settingsDataStore.edit { it[notifRunCompleteKey] = enabled }
262− }
263− suspend fun setNotifPermission(enabled: Boolean) {
264− appContext.settingsDataStore.edit { it[notifPermissionKey] = enabled }
265− }
266− suspend fun setNotifError(enabled: Boolean) {
267− appContext.settingsDataStore.edit { it[notifErrorKey] = enabled }
268− }
269−
270− suspend fun setSwipeLeftAction(action: SwipeAction) {
271− appContext.settingsDataStore.edit { it[swipeLeftActionKey] = action.name }
272− }
273− suspend fun setSwipeRightAction(action: SwipeAction) {
274− appContext.settingsDataStore.edit { it[swipeRightActionKey] = action.name }
275− }
276−}
277−
278−/** Remappable swipe actions for the session list. NONE disables the swipe entirely. */
279−enum class SwipeAction { DELETE, ARCHIVE, MARK_READ, NONE }
app/src/main/java/soy/iko/opencode/di/AppContainer.ktdeleted−1545
@@ -1,1545 +0,0 @@
1−package soy.iko.opencode.di
2−
3−import android.content.Context
4−import android.net.ConnectivityManager
5−import android.net.Network
6−import android.net.NetworkCapabilities
7−import android.net.NetworkRequest
8−import android.util.Log
9−import soy.iko.opencode.data.model.AssistantMessage
10−import soy.iko.opencode.data.model.BusEvent
11−import soy.iko.opencode.data.model.FilePromptPart
12−import soy.iko.opencode.data.model.MessagePartUpdated
13−import soy.iko.opencode.data.model.MessageUpdated
14−import soy.iko.opencode.data.model.Permission
15−import soy.iko.opencode.data.model.PermissionReplied
16−import soy.iko.opencode.data.model.PermissionResponse
17−import soy.iko.opencode.data.model.PermissionUpdated
18−import soy.iko.opencode.data.model.StepFinishPart
19−import soy.iko.opencode.data.model.ServerProfile
20−import soy.iko.opencode.data.model.SessionError
21−import soy.iko.opencode.data.model.SessionIdle
22−import soy.iko.opencode.data.model.ToolPart
23−import soy.iko.opencode.data.model.TODO_WRITE_TOOL
24−import soy.iko.opencode.data.model.parseTodos
25−import soy.iko.opencode.data.model.statusEnum
26−import soy.iko.opencode.data.model.TodoStatus
27−import soy.iko.opencode.data.model.inputElement
28−import soy.iko.opencode.data.repo.AttachmentDraftStore
29−import soy.iko.opencode.data.repo.BackupManager
30−import soy.iko.opencode.data.repo.DraftStore
31−import soy.iko.opencode.data.repo.ErrorKind
32−import soy.iko.opencode.data.repo.FileBrowserPrefs
33−import soy.iko.opencode.data.repo.MessageCacheStore
34−import soy.iko.opencode.data.repo.OutboxMessage
35−import soy.iko.opencode.data.repo.OutboxStore
36−import soy.iko.opencode.data.repo.RecentModelsStore
37−import soy.iko.opencode.data.repo.SearchHistoryStore
38−import soy.iko.opencode.data.repo.SessionPrefsStore
39−import soy.iko.opencode.data.repo.SessionRepository
40−import soy.iko.opencode.data.repo.ProfileStore
41−import soy.iko.opencode.data.repo.SettingsStore
42−import soy.iko.opencode.data.repo.classifyError
43−import soy.iko.opencode.data.repo.responseStatusCode
44−import soy.iko.opencode.data.network.EventStreamClient
45−import soy.iko.opencode.data.network.HttpClientFactory
46−import soy.iko.opencode.data.network.NetworkConfig
47−import soy.iko.opencode.data.network.OpencodeApiClient
48−import soy.iko.opencode.notification.NotificationChannels
49−import soy.iko.opencode.notification.RunForegroundService
50−import soy.iko.opencode.util.safeExceptionSummary
51−import soy.iko.opencode.notification.SessionNotifications
52−import soy.iko.opencode.R
53−import soy.iko.opencode.util.runCatchingCancellable
54−import kotlinx.coroutines.CoroutineScope
55−import kotlinx.coroutines.Dispatchers
56−import kotlinx.coroutines.ExperimentalCoroutinesApi
57−import kotlinx.coroutines.SupervisorJob
58−import kotlinx.coroutines.cancel
59−import kotlinx.coroutines.delay
60−import kotlinx.coroutines.flow.MutableSharedFlow
61−import kotlinx.coroutines.flow.MutableStateFlow
62−import kotlinx.coroutines.flow.SharedFlow
63−import kotlinx.coroutines.flow.StateFlow
64−import kotlinx.coroutines.flow.asSharedFlow
65−import kotlinx.coroutines.flow.asStateFlow
66−import kotlinx.coroutines.flow.collectLatest
67−import kotlinx.coroutines.flow.combine
68−import kotlinx.coroutines.flow.debounce
69−import kotlinx.coroutines.flow.distinctUntilChanged
70−import kotlinx.coroutines.flow.drop
71−import kotlinx.coroutines.flow.emptyFlow
72−import kotlinx.coroutines.flow.first
73−import kotlinx.coroutines.Job
74−import kotlinx.coroutines.flow.flatMapLatest
75−import kotlinx.coroutines.flow.map
76−import kotlinx.coroutines.flow.update
77−import kotlinx.coroutines.isActive
78−import kotlinx.coroutines.launch
79−import kotlinx.coroutines.sync.Mutex
80−import kotlinx.coroutines.sync.withLock
81−import kotlinx.coroutines.withTimeoutOrNull
82−import java.util.concurrent.atomic.AtomicBoolean
83−
84−/**
85− * Result of probing a server URL to check connectivity and whether authentication
86− * is required, without persisting a profile or opening a long-lived connection.
87− */
88−sealed class ProbeResult {
89− /** Server is reachable and accepts unauthenticated requests. */
90− object Reachable : ProbeResult()
91−
92− /** Server is reachable but rejected the probe with an authentication error. */
93− object NeedsAuth : ProbeResult()
94−
95− /** Server could not be reached (host unresolved, connection refused, timeout, etc.). */
96− data class Unreachable(val error: String) : ProbeResult()
97−}
98−
99−/**
100− * Hand-written service locator held by [soy.iko.opencode.OpencodeApp]. Owns the
101− * process-wide singletons and the currently active [OpencodeConnection].
102− */
103−open class AppContainer private constructor(
104− private val appContext: Context?,
105− private val skipInit: Boolean,
106− @Suppress("unused") private val testMode: Boolean,
107−) {
108− constructor(context: Context) : this(context.applicationContext, false, false)
109− protected constructor() : this(null, true, true)
110−
111− private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
112− open val profileStore: ProfileStore by lazy { ProfileStore(appContext!!) }
113− open val settingsStore: SettingsStore by lazy { SettingsStore(appContext!!) }
114− open val draftStore: DraftStore by lazy { DraftStore(appContext!!, appScope) }
115− open val attachmentDraftStore: AttachmentDraftStore by lazy { AttachmentDraftStore(appContext!!) }
116− open val sessionPrefsStore: SessionPrefsStore by lazy { SessionPrefsStore(appContext!!) }
117− open val messageCacheStore: MessageCacheStore by lazy { MessageCacheStore(appContext!!) }
118− open val outboxStore: OutboxStore by lazy { OutboxStore(appContext!!) }
119− open val searchHistoryStore: SearchHistoryStore by lazy { SearchHistoryStore(appContext!!) }
120− open val recentModelsStore: RecentModelsStore by lazy { RecentModelsStore(appContext!!) }
121− open val fileBrowserPrefs: FileBrowserPrefs by lazy { FileBrowserPrefs(appContext!!) }
122− open val backupManager: BackupManager by lazy { BackupManager(profileStore, settingsStore, sessionPrefsStore) }
123−
124− /** True while the outbox is actively flushing queued messages to the server, so the UI
125− * can show a "sending queued messages…" indicator. */
126− private val _outboxSending = MutableStateFlow(false)
127− open val outboxSending: StateFlow<Boolean> = _outboxSending.asStateFlow()
128−
129− /** Bumped to nudge an immediate outbox flush (after enqueue, or a manual "Send now"),
130− * independent of connection/online changes. */
131− private val _outboxFlushTrigger = MutableStateFlow(0)
132− open fun flushOutbox() { _outboxFlushTrigger.update { it + 1 } }
133−
134− private val _activeConnection = MutableStateFlow<OpencodeConnection?>(null)
135− open val activeConnection: StateFlow<OpencodeConnection?> = _activeConnection.asStateFlow()
136−
137− /** True while a background auto-reconnect to the most-recent server is in flight. */
138− private val _reconnecting = MutableStateFlow(false)
139− open val reconnecting: StateFlow<Boolean> = _reconnecting.asStateFlow()
140−
141− /**
142− * Set once a startup auto-reconnect succeeds. The server list collects this and
143− * (once) navigates straight to the session list so a returning user skips it.
144− * [consumeAutoConnect] guards against re-firing on screen re-entry.
145− */
146− private val _autoConnectDone = MutableStateFlow(false)
147− open val autoConnectDone: StateFlow<Boolean> = _autoConnectDone.asStateFlow()
148− private val autoConnectConsumed = AtomicBoolean(false)
149− open fun consumeAutoConnect(): Boolean = autoConnectConsumed.compareAndSet(false, true)
150−
151− /** Text shared into the app (ACTION_SEND), prefilled into a session draft. */
152− private val _pendingShare = MutableStateFlow<String?>(null)
153− open val pendingShare: StateFlow<String?> = _pendingShare.asStateFlow()
154− open fun setPendingShare(text: String) { _pendingShare.value = text }
155− open fun consumePendingShare(): String? {
156− val current = _pendingShare.value ?: return null
157− return if (_pendingShare.compareAndSet(current, null)) current else null
158− }
159−
160− /** Image/file Uris (as strings) shared into the app, staged as attachments in the next
161− * opened session. Consumed once by the first ChatScreen to compose after the share. */
162− private val _pendingSharedMedia = MutableStateFlow<List<String>>(emptyList())
163− open val pendingSharedMedia: StateFlow<List<String>> = _pendingSharedMedia.asStateFlow()
164− open fun setPendingSharedMedia(uris: List<String>) { _pendingSharedMedia.value = uris }
165− open fun consumePendingSharedMedia(): List<String> {
166− val current = _pendingSharedMedia.value
167− if (current.isEmpty()) return emptyList()
168− return if (_pendingSharedMedia.compareAndSet(current, emptyList())) current else emptyList()
169− }
170−
171− /**
172− * Set from an external "New session" trigger (launcher shortcut / QS tile). The nav host
173− * consumes it once connected, creating a fresh session and opening it. Uses a counter
174− * (not a boolean) so re-tapping the shortcut while a prior request is still pending
175− * increments the value and re-fires the LaunchedEffect — a boolean StateFlow wouldn't
176− * emit when set to the same value, making the request unrecoverable by re-tapping.
177− */
178− private val _pendingNewSession = MutableStateFlow(0)
179− open val pendingNewSession: StateFlow<Int> = _pendingNewSession.asStateFlow()
180− open fun requestNewSession() { _pendingNewSession.update { it + 1 } }
181− open fun consumePendingNewSession(): Boolean {
182− while (true) {
183− val current = _pendingNewSession.value
184− if (current == 0) return false
185− if (_pendingNewSession.compareAndSet(current, current - 1)) return true
186− }
187− }
188−
189− /** A one-shot signal to navigate to the Diagnostics screen (e.g. from the crash-relaunch
190− * prompt). Consumed by OpencodeApp's NavHost. */
191− private val _pendingDiagnostics = MutableStateFlow(false)
192− open val pendingDiagnostics: StateFlow<Boolean> = _pendingDiagnostics.asStateFlow()
193− open fun requestDiagnostics() { _pendingDiagnostics.value = true }
194− open fun consumePendingDiagnostics(): Boolean = _pendingDiagnostics.compareAndSet(true, false)
195−
196− /**
197− * A session id to open from an external trigger (a notification tap or a deep link),
198− * paired with the originating server's profile id (if known) so a tap after the user
199− * has switched servers routes back to the server that ran the session. The nav host
200− * consumes it once a connection is active (switching to [profileId] first if needed).
201− */
202− data class PendingOpenSession(val sessionId: String, val profileId: String?)
203−
204− private val _pendingOpenSession = MutableStateFlow<PendingOpenSession?>(null)
205− open val pendingOpenSession: StateFlow<PendingOpenSession?> = _pendingOpenSession.asStateFlow()
206− open fun requestOpenSession(id: String, profileId: String? = null) {
207− _pendingOpenSession.value = PendingOpenSession(id, profileId)
208− }
209− open fun consumePendingOpenSession(): PendingOpenSession? {
210− val current = _pendingOpenSession.value ?: return null
211− return if (_pendingOpenSession.compareAndSet(current, null)) current else null
212− }
213−
214− /**
215− * A file path requested to be opened (via deep link `opencode://file/{path}` or future
216− * entry points), consumed by the NavHost to navigate to the file viewer. Mirrors the
217− * session open-signal pattern: a StateFlow the NavHost observes, drained atomically.
218− */
219− private val _pendingOpenFile = MutableStateFlow<String?>(null)
220− open val pendingOpenFile: StateFlow<String?> = _pendingOpenFile.asStateFlow()
221− open fun requestOpenFile(path: String) { _pendingOpenFile.value = path }
222− open fun consumePendingOpenFile(): String? {
223− val current = _pendingOpenFile.value ?: return null
224− return if (_pendingOpenFile.compareAndSet(current, null)) current else null
225− }
226−
227− /**
228− * The session the user is currently viewing (or null when not in a chat). Drives the
229− * unread tracker: messages arriving for any *other* session mark it unread, and
230− * opening a session clears its unread state.
231− */
232− private val _currentSession = MutableStateFlow<String?>(null)
233− open val currentSession: StateFlow<String?> = _currentSession.asStateFlow()
234−
235− /** Session ids that received activity while not being viewed, mapped to the count
236− * of unread message events. A count (not just a presence set) lets the session
237− * list badge show "3 unread" instead of a bare dot, so the user can tell whether
238− * one reply or a whole burst arrived. */
239− private val _unread = MutableStateFlow<Map<String, Int>>(emptyMap())
240− open val unread: StateFlow<Map<String, Int>> = _unread.asStateFlow()
241−
242− /** Session ids the user has muted. A muted session doesn't badge unread (the count is
243− * still tracked internally so unmuting can restore it, but the badge and completion
244− * notification are suppressed). Persisted via SessionPrefsStore so the choice survives
245− * process death. */
246− private val _mutedSessions = MutableStateFlow<Set<String>>(emptySet())
247− open val mutedSessions: StateFlow<Set<String>> = _mutedSessions.asStateFlow()
248−
249− /** True when any assistant run is actively streaming across all sessions. Drives the
250− * disconnect confirmation on the session list (disconnecting mid-run kills it). */
251− private val _anyRunActive = MutableStateFlow(false)
252− open val anyRunActive: StateFlow<Boolean> = _anyRunActive.asStateFlow()
253−
254− /** Session ids currently streaming an assistant run, surfaced so the session list can
255− * badge the row whose run is active. Mirrors [activeRuns] as an immutable snapshot so
256− * Compose can skip recomposition when the set hasn't changed. */
257− private val _runningSessionIds = MutableStateFlow<Set<String>>(emptySet())
258− open val runningSessionIds: StateFlow<Set<String>> = _runningSessionIds.asStateFlow()
259−
260− /** Latest task-plan progress text for the active run (e.g. "Step 2 of 5"), surfaced in
261− * the foreground-service notification so the user can see what the agent is working on
262− * without opening the app. Null when no plan is available or no run is active. */
263− private val _runProgressText = MutableStateFlow<String?>(null)
264− open val runProgressText: StateFlow<String?> = _runProgressText.asStateFlow()
265−
266− /** Whether the device currently has network connectivity. Distinct from the SSE
267− * connection state so the UI can tell "you're offline" (device) from "server
268− * unreachable" (credentials/host). Updated by the [networkCallback]. */
269− private val _isOnline = MutableStateFlow(true)
270− open val isOnline: StateFlow<Boolean> = _isOnline.asStateFlow()
271−
272− /** Whether a foreground Activity is currently showing. Distinct from [currentSession],
273− * which stays set while the app is merely backgrounded (the chat screen isn't disposed
274− * when the user locks their phone). Permission/completion notifications need the real
275− * foreground signal so they still fire for a session the user "has open" but has walked
276− * away from — the core of the run-in-the-background use case. Set from MainActivity's
277− * onStart/onStop. */
278− private val _isForeground = MutableStateFlow(false)
279− open val isForeground: StateFlow<Boolean> = _isForeground.asStateFlow()
280− open fun setForeground(foreground: Boolean) { _isForeground.value = foreground }
281−
282− /** True when the user is actively looking at [sessionId] (app foregrounded AND that
283− * session is the one on screen), so an in-app affordance (the permission dialog) is
284− * handling it and a notification would be redundant. */
285− private fun isActivelyViewing(sessionId: String): Boolean =
286− _isForeground.value && sessionId == _currentSession.value
287−
288− open fun setCurrentSession(id: String?) {
289− _currentSession.value = id
290− if (id != null) {
291− _unread.update { it - id }
292− unreadMessageIds.remove(id)
293− appContext?.let {
294− SessionNotifications.cancel(it, id)
295− SessionNotifications.cancelPermission(it, id)
296− SessionNotifications.cancelError(it, id)
297− }
298− }
299− }
300−
301− /** Clear unread badge and dedup set for a deleted session so its stale count doesn't
302− * linger in the session list badge or leak memory until the next connect/disconnect. */
303− open fun clearUnread(id: String) {
304− _unread.update { it - id }
305− unreadMessageIds.remove(id)
306− }
307−
308− /** Mark a session as read (clear its unread badge) — the "Mark read" notification action.
309− * Updates the launcher-icon badge directly (not just the in-memory [StateFlow]) so a
310− * "Mark read" tap while the app is backgrounded — when [SessionListScreen]'s
311− * `LaunchedEffect(totalUnread)` collector isn't running — still decrements the badge.
312− * Without this, the notification dismisses but the launcher badge shows a stale count
313− * until the app is next foregrounded. */
314− open fun markSessionRead(id: String) {
315− clearUnread(id)
316− appContext?.let { ctx ->
317− SessionNotifications.updateUnreadBadge(ctx, _unread.value.values.sum())
318− }
319− }
320−
321− /** Mark a session as unread with a count of 1 (or restore a prior count). Used by the
322− * session list's "Mark as unread" overflow action so a user can re-flag a conversation
323− * they want to revisit. No-op when the session is the one currently being viewed — a
324− * viewed session clears its own unread badge via [setCurrentSession], so marking it
325− * unread would race and immediately clear. Muted sessions are still marked (the count is
326− * tracked so unmuting restores it) but the list UI hides the badge while muted. */
327− open fun markSessionUnread(id: String, count: Int = 1) {
328− if (id == _currentSession.value) return
329− _unread.update { it + (id to count) }
330− }
331−
332− /** Toggle a session's mute state. A muted session suppresses the unread badge and the
333− * completion notification so a noisy conversation doesn't keep interrupting. Persisted
334− * via SessionPrefsStore so it survives process death. */
335− fun toggleSessionMute(id: String) {
336− val muted = id in _mutedSessions.value
337− val next = if (muted) _mutedSessions.value - id else _mutedSessions.value + id
338− _mutedSessions.value = next
339− appContext?.let {
340− appScope.launch {
341− runCatchingCancellable { sessionPrefsStore.setMuted(id, !muted) }
342− }
343− }
344− }
345−
346− /** True when [id] is muted (unread badge and completion notification suppressed). */
347− fun isSessionMuted(id: String): Boolean = id in _mutedSessions.value
348−
349− /** Clear every session's unread badge at once — the session list's "Mark all read" action. */
350− open fun clearAllUnread() {
351− _unread.update { emptyMap() }
352− }
353−
354− /** Restore a session's unread badge after a failed server switch reconnects.
355− * Preserves the prior [count] so a session badged with "5 unread" before the
356− * switch attempt still shows 5 (not 1) after the restore. No-op for the session
357− * the user is currently viewing, since a viewed session is never badged. */
358− open fun restoreUnread(id: String, count: Int) {
359− if (id != _currentSession.value) {
360− _unread.update { it + (id to count) }
361− }
362− }
363−
364− /** Resolve a localized string — view models reach resources through the container. */
365− open fun string(id: Int, vararg formatArgs: Any): String {
366− if (appContext == null) return ""
367− return if (formatArgs.isEmpty()) appContext.getString(id) else appContext.getString(id, *formatArgs)
368− }
369−
370− /**
371− * Convert a throwable into a user-facing message. Classifies the error by concrete
372− * type (network, timeout, HTTP status) rather than string-matching class names, so
373− * the message reflects what actually went wrong without leaking internal URLs/state.
374− */
375− open fun friendlyError(t: Throwable): String =
376− friendlyErrorFor(t, activeConnection.value?.profile?.baseUrl.orEmpty())
377−
378− /**
379− * Same classification as [friendlyError] but accepts an explicit base URL, so callers
380− * that aren't operating on the active connection (e.g. [probeServer]) can still
381− * produce a user-facing message with the right server address.
382− */
383− open fun friendlyErrorFor(t: Throwable, baseUrl: String): String =
384− when (classifyError(t)) {
385− ErrorKind.NOT_REACHABLE, ErrorKind.NETWORK ->
386− string(R.string.error_not_reachable, baseUrl)
387− ErrorKind.TIMEOUT -> string(R.string.error_timeout)
388− ErrorKind.SERVER -> string(R.string.error_server)
389− // Show only the HTTP status (e.g. 401, 404) — never the request URL,
390− // which a ClientRequestException carries in its message and which we
391− // promised not to leak (it can include auth or internal paths).
392− ErrorKind.CLIENT -> {
393− val code = responseStatusCode(t)
394− when (code) {
395− // Auth failures reuse the connection banner text: the request itself is
396− // fine, the credentials aren't, so the fix is re-editing the profile —
397− // not "request failed (401)" which implies an opaque program error.
398− 401, 403 -> string(R.string.connection_failed)
399− 404 -> string(R.string.error_not_found)
400− else -> code?.let { string(R.string.error_client_status, it) }
401− ?: string(R.string.error_generic)
402− }
403− }
404− ErrorKind.UNKNOWN -> string(R.string.error_generic)
405− }
406−
407− /**
408− * Drive the [RunForegroundService] from the process-lived [appScope] rather than from the
409− * Activity's composition. Previously the start/stop was wired to a
410− * `collectAsStateWithLifecycle` collector in the root composable, which pauses while the
411− * Activity is STOPPED — so a run *started while backgrounded* (e.g. via the notification
412− * inline-reply) never acquired foreground priority and its long-lived SSE stream could be
413− * killed by Doze, and a run that *ended* while backgrounded left the "working…"
414− * notification lingering until the app was reopened. Collecting here reacts to
415− * [anyRunActive] regardless of Activity state.
416− */
417− private fun observeRunForegroundService() {
418− val ctx = appContext ?: return
419− appScope.launch {
420− // Debounce so a run that starts then fails/idles almost immediately doesn't
421− // dispatch startForegroundService() then stopService() back-to-back — if the stop
422− // wins that race before the service calls startForeground(), Android raises the
423− // "did not then call startForeground()" crash ~5s later. Collapsing the window
424− // emits only the settled state; distinctUntilChanged drops a no-op re-emit when a
425− // brief true→false→true flurry settles back to the value already applied.
426− anyRunActive
427− .debounce(NetworkConfig.runForegroundDebounceMs)
428− .distinctUntilChanged()
429− .collect { active ->
430− if (active) {
431− // When exactly one run is active, resolve its title (and id, for the
432− // Stop action) so the notification identifies which session is running
433− // and can be aborted from the notification. Multiple concurrent runs
434− // fall back to the generic title (naming one would be misleading).
435− val activeId = synchronized(activeRuns) {
436− activeRuns.toList().singleOrNull()
437− }
438− val title = activeId?.let { sid ->
439− runCatchingCancellable {
440− activeConnection.value?.repository?.listSessions()
441− ?.firstOrNull { it.id == sid }?.displayTitle
442− }.getOrNull()
443− }
444− val profileId = activeConnection.value?.profile?.id
445− RunForegroundService.start(ctx, title, activeId, profileId, _runProgressText.value)
446− } else {
447− RunForegroundService.stop(ctx)
448− }
449− }
450− }
451− // Separate collector: update the FGS notification's progress text ("Step 2 of 5")
452− // as the agent works through its task plan. Re-sends the service intent with the
453− // updated progress, which the service uses to rebuild the notification.
454− appScope.launch {
455− _runProgressText
456− .drop(1) // skip initial value — the anyRunActive collector handles the first start
457− .distinctUntilChanged()
458− .collect { progress ->
459− if (_anyRunActive.value) {
460− val activeId = synchronized(activeRuns) { activeRuns.toList().singleOrNull() }
461− val title = activeId?.let { sid ->
462− runCatchingCancellable {
463− activeConnection.value?.repository?.listSessions()
464− ?.firstOrNull { it.id == sid }?.displayTitle
465− }.getOrNull()
466− }
467− val profileId = activeConnection.value?.profile?.id
468− RunForegroundService.start(ctx, title, activeId, profileId, progress)
469− }
470− }
471− }
472− }
473−
474− /**
475− * Post a system notification when the SSE stream hits a non-retryable failure
476− * ([Failed]/[AuthFailed]) while the app is backgrounded during an active run, so a
477− * backgrounded user is signaled that their run is stranded (the in-app banner isn't
478− * visible). The notification is cancelled when the stream reconnects. This closes the
479− * gap where a user who kicks off a run and backgrounds the app returns hours later to
480− * find nothing happened and no signal why — the stream parked on a 4xx mid-run and the
481− * in-app banner was never seen.
482− */
483− private fun observeBackgroundedConnectionFailures() {
484− val ctx = appContext ?: return
485− appScope.launch {
486− activeConnection.collectLatest { conn ->
487− if (conn == null) return@collectLatest
488− conn.events.state.collect { state ->
489− when (state) {
490− EventStreamClient.ConnectionState.Failed,
491− EventStreamClient.ConnectionState.AuthFailed -> {
492− // Only notify when the app is backgrounded AND a run was recently
493− // active (or still is) — a foregrounded user sees the banner, and
494− // a failure with no run is less actionable.
495− if (!_isForeground.value && _anyRunActive.value) {
496− runCatchingCancellable {
497− SessionNotifications.postConnectionLost(
498− ctx, conn.profile.displayLabel, conn.profile.id,
499− )
500− }.onFailure {
501− Log.w("AppContainer", "connection-lost notification failed: ${safeExceptionSummary(it)}")
502− }
503− }
504− }
505− EventStreamClient.ConnectionState.Connected -> {
506− runCatchingCancellable { SessionNotifications.cancelConnectionLost(ctx) }
507− }
508− else -> {}
509− }
510− }
511− }
512− }
513− }
514−
515− /**
516− * Reconcile active-run tracking on an SSE *reconnect*. A run that completes during a stream
517− * outage never delivers its `SessionIdle`, so its id would stay in [activeRuns] and pin
518− * [anyRunActive] (and the foreground service + "working…" notification) on indefinitely. On a
519− * reconnect we clear the tracking and let live streaming events re-populate it: a genuinely
520− * in-progress run re-adds itself within moments via [isLiveRunActivity], while a run that
521− * finished during the outage produces no further live events (its completion arrives only via
522− * the REST re-seed), so it correctly stays cleared. The first connect of a connection is not a
523− * reconnect; `connect()` already resets [activeRuns], so only subsequent Connected transitions
524− * trigger the sweep.
525− */
526− private fun observeRunReconcileOnReconnect() {
527− appScope.launch {
528− activeConnection.collectLatest { conn ->
529− if (conn == null) return@collectLatest
530− var hasConnectedBefore = false
531− conn.events.state.collect { state ->
532− if (state == EventStreamClient.ConnectionState.Connected) {
533− if (hasConnectedBefore) {
534− synchronized(activeRuns) {
535− activeRuns.clear()
536− publishRunState()
537− }
538− }
539− hasConnectedBefore = true
540− }
541− }
542− }
543− }
544− }
545−
546− /**
547− * Flush the offline outbox whenever there's an active connection and the device is
548− * online (and on any manual [flushOutbox] nudge). Queued messages are only sent to the
549− * server they were composed for (matched by profile id), so a reconnect to a different
550− * server never misfires them against a session id that doesn't exist there. Uses a plain
551− * `collect` (not collectLatest) so an in-flight send is never cancelled mid-flight and
552− * send order is preserved; each message carries a stable idempotency key (its persistent
553− * outbox id) so even a re-send across flushes is deduplicated server-side.
554− */
555− private fun observeOutbox() {
556− appScope.launch {
557− combine(activeConnection, isOnline, _outboxFlushTrigger) { conn, online, _ -> conn to online }
558− .collect { (conn, online) ->
559− if (conn == null || !online) return@collect
560− flushOutboxNow(conn)
561− }
562− }
563− }
564−
565− private suspend fun flushOutboxNow(conn: OpencodeConnection) {
566− val pending = outboxStore.messages.value
567− .filter { it.profileId == conn.profile.id }
568− .sortedBy { it.createdAt }
569− if (pending.isEmpty()) return
570− _outboxSending.value = true
571− try {
572− for (msg in pending) {
573− val result = runCatchingCancellable {
574− conn.repository.sendPrompt(
575− msg.sessionId,
576− msg.text,
577− attachments = msg.attachments.map {
578− FilePromptPart(mime = it.mime, url = it.url, filename = it.filename)
579− },
580− model = msg.model,
581− agent = msg.agent,
582− // Reuse the persistent outbox id as a stable idempotency key so a
583− // later flush of a message whose earlier POST reached the server (but
584− // whose response was lost) is deduplicated server-side instead of
585− // starting a duplicate agent run.
586− idempotencyKey = msg.id,
587− )
588− }.onFailure {
589− Log.w("AppContainer", "Outbox flush failed for ${msg.sessionId}: ${safeExceptionSummary(it)}")
590− }
591− if (result.isSuccess) {
592− outboxStore.remove(msg.id)
593− continue
594− }
595− // A permanently-undeliverable message (a non-408/429 4xx — e.g. the target
596− // session was deleted server-side, yielding a 404) must be dropped, not left at
597− // the head of the queue. The loop stops at the first failure to preserve send
598− // order, so a poison message would otherwise block every later queued message
599− // for this profile forever. Transient failures (offline again, 5xx, 408/429)
600− // keep the queue intact and retry on the next trigger.
601− // 401/403 (bad/expired credentials) are NOT permanent: the message itself is
602− // deliverable once the user fixes the profile. Dropping it would silently lose
603− // the user's composed offline prompt on a recoverable auth failure. They stay
604− // in the queue and retry on the next flush after auth is restored.
605− val status = result.exceptionOrNull()?.let { responseStatusCode(it) }
606− // Permanent = a non-408/429/401/403 4xx, matching withRetry's non-retryable rule
607− // except for auth failures, which are recoverable by re-editing the profile.
608− val permanent = when (status) {
609− null, 408, 429, 401, 403 -> false
610− in 400..499 -> true
611− else -> false
612− }
613− if (permanent) {
614− Log.w(
615− "AppContainer",
616− "Dropping undeliverable outbox message ${msg.id} for ${msg.sessionId} (HTTP $status): ${string(R.string.outbox_dropped_text)}",
617− )
618− outboxStore.remove(msg.id)
619− // Surface the dropped reply on the ERROR channel with a distinct title
620− // ("Message not delivered") so the user understands a queued reply
621− // couldn't be delivered — not that a run failed (which postError
622− // implies). Tap routes back to the originating profile's session.
623− val ctx = appContext
624− if (ctx != null) {
625− val title = resolveSessionTitle(msg.sessionId, conn.repository)
626− runCatchingCancellable {
627− SessionNotifications.postOutboxDropped(
628− ctx, msg.sessionId,
629− title,
630− conn.profile.id,
631− )
632− }.onFailure {
633− Log.w("AppContainer", "outbox drop notification failed: ${safeExceptionSummary(it)}")
634− }
635− }
636− } else {
637− break
638− }
639− }
640− } finally {
641− _outboxSending.value = false
642− }
643− }
644−
645− /** Release resources held for the process lifetime (network callback, app scope). */
646− open fun shutdown() {
647− // Cancel the app scope first so any coroutine holding the connection mutex
648− // (e.g. a connect() suspended on profileStore) is cancelled and releases the
649− // mutex. Otherwise the runBlocking below would deadlock waiting for a coroutine
650− // that can't be cancelled until after the runBlocking completes.
651− appScope.cancel()
652− // Capture the active connection BEFORE the bounded close attempt so a timeout
653− // can still close it outside the mutex. Without this, the timeout path would
654− // null the StateFlow reference without closing the connection — leaking the SSE
655− // socket, OkHttp pool, and the connection's coroutine scope.
656− val stuck = _activeConnection.value
657− var closed = false
658− // Bounded runBlocking so a stuck mutex or a slow close() can't ANR the app.
659− // 2 seconds is generous: appScope.cancel() already triggered cancellation of
660− // any coroutine holding the mutex; we're just waiting for it to unwind.
661− kotlinx.coroutines.runBlocking {
662− withTimeoutOrNull(2_000) {
663− connectionMutex.withLock {
664− runCatching { _activeConnection.value?.close() }
665− _activeConnection.value = null
666− closed = true
667− }
668− }
669− // If the timeout fired, force-clear the StateFlow so observers see no
670− // connection. The stuck connection (if any) is closed below, outside the
671− // mutex, so a slow close() can't ANR — its scope is cancelled and the JVM
672− // exit reaps any remaining sockets.
673− _activeConnection.value = null
674− }
675− if (!closed && stuck != null) {
676− // The timeout path fired (the locked close didn't complete). Cancel the
677− // stuck connection's scope directly. close() suspends (scopeJob.join), so
678− // wrap in a bounded runBlocking that can't ANR — at this point the app is
679− // shutting down, so reaping is best-effort.
680− runCatching {
681− kotlinx.coroutines.runBlocking {
682− kotlinx.coroutines.withTimeoutOrNull(1_000) { stuck.close() }
683− }
684− }
685− }
686− val cm = appContext?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
687− networkCallback?.let { runCatching { cm?.unregisterNetworkCallback(it) } }
688− if (!skipInit) soy.iko.opencode.data.repo.CrashLogger.get(appContext!!).shutdown()
689− if (!skipInit) draftStore.shutdown()
690− }
691−
692− /**
693− * Watch the SSE bus for new message activity and badge any session that isn't
694− * currently open. This powers the unread dot on the session list so the user can
695− * tell which conversations got a reply while they were elsewhere.
696− *
697− * Uses [flatMapLatest] so a server switch (which replaces the active connection)
698− * re-subscribes to the new event stream and drops the old one.
699− */
700− @OptIn(ExperimentalCoroutinesApi::class)
701− private fun observeMessageActivity() {
702− appScope.launch {
703− // Retry the observer if it fails for any reason (transient flow exception,
704− // cancellation due to scope issues). Without this, a single failure would
705− // permanently disable unread tracking and completion notifications.
706− while (isActive) {
707− runCatchingCancellable {
708− activeConnection
709− .flatMapLatest { conn ->
710− // Capture the originating connection so notification coroutines
711− // resolve titles and route permission responses against THIS
712− // server, not whichever happens to be active when they resume.
713− // A server switch during a listSessions() round-trip would
714− // otherwise resolve the title (or POST the permission reply)
715− // against the new server, where the session/permission doesn't
716− // exist — showing an opaque id or silently losing the reply.
717− conn?.events?.events?.map { conn to it } ?: emptyFlow()
718− }
719− .collect { (conn, event) ->
720− // A permission request needs the user's approval. Post a heads-up
721− // notification (with Allow/Reject actions) unless the user is actively
722− // viewing this session, where the in-app permission dialog handles it.
723− if (event is PermissionUpdated) {
724− val psid = event.properties.sessionID.takeIf { it.isNotBlank() } ?: return@collect
725− if (!isActivelyViewing(psid)) appScope.launch { notifyPermission(event.properties, conn) }
726− return@collect
727− }
728− // The permission was answered (in-app, from the notification, or
729− // auto-resolved): clear its heads-up notification.
730− if (event is PermissionReplied) {
731− val psid = event.properties.sessionID?.takeIf { it.isNotBlank() } ?: return@collect
732− appContext?.let { SessionNotifications.cancelPermission(it, psid) }
733− return@collect
734− }
735− // A run failed. Clear its active-run tracking (an error isn't always
736− // followed by a SessionIdle) and notify unless it's being viewed.
737− if (event is SessionError) {
738− val esid = event.properties.sessionID ?: return@collect
739− val wasRunning = synchronized(activeRuns) {
740− activeRuns.remove(esid).also { removed ->
741− if (removed) publishRunState()
742− }
743− }
744− if (wasRunning && !isActivelyViewing(esid)) {
745− appScope.launch { notifySessionError(esid, conn.repository, conn.profile.id) }
746− }
747− return@collect
748− }
749− // SessionIdle is not "message activity" (don't badge as unread)
750− // but signals a run finished — fire a completion notification if the
751− // session isn't currently being viewed and was actively streaming.
752− if (event is SessionIdle) {
753− val idleSid = event.properties.sessionID ?: return@collect
754− // Clear the run state unconditionally — even for the session on
755− // screen. Gating the removal on `idleSid != currentSession` (as
756− // this once did) leaks the id in activeRuns and pins anyRunActive
757− // true forever whenever a run finishes while being viewed. Only
758− // the completion *notification* is suppressed for the viewed one.
759− val wasRunning = synchronized(activeRuns) {
760− activeRuns.remove(idleSid).also { removed ->
761− if (removed) publishRunState()
762− }
763− }
764− // Clear the progress text when the run finishes.
765− _runProgressText.value = null
766− if (wasRunning && !isActivelyViewing(idleSid)) {
767− // Fire this off the collector's coroutine: notifySessionCompleted
768− // does a network listSessions() to resolve the title, and blocking
769− // the shared-event collector here would stall the SharedFlow,
770− // overflowing its DROP_OLDEST buffer and silently dropping live
771− // parts/updates for every other subscriber (e.g. the message reducer).
772− appScope.launch { notifySessionCompleted(idleSid, conn.repository, conn.profile.id) }
773− }
774− return@collect
775− }
776− // Track the agent's task-plan progress (from todowrite tool calls) so the
777− // foreground-service notification can show "Step 2 of 5" instead of just a
778− // chronometer. The todowrite tool sends the full plan on every call, so the
779− // latest call's input is a complete snapshot.
780− if (event is MessagePartUpdated) {
781− val part = event.properties.part
782− if (part is ToolPart && part.tool.equals(TODO_WRITE_TOOL, ignoreCase = true)) {
783− val todos = parseTodos(part.state.inputElement())
784− if (todos.isNotEmpty()) {
785− val completed = todos.count { it.statusEnum() == TodoStatus.COMPLETED }
786− _runProgressText.value = appContext?.getString(
787− soy.iko.opencode.R.string.notif_running_progress,
788− completed + 1,
789− todos.size,
790− )
791− }
792− }
793− }
794− val sid = sessionOf(event) ?: return@collect
795− // Re-read currentSession here, right before mutating the badge state:
796− // the user may have opened this session between when this event was
797− // enqueued and now (setCurrentSession clears its badge and dedup set).
798− // A stale earlier check would race a badge — and a dedup entry — back
799− // in for the session that's actually on screen.
800− if (sid != _currentSession.value) {
801− // Track the message id in the dedup set for *every* session (muted or
802− // not), so unmuting can't re-count messages that arrived while muted.
803− // The visible badge increment below is gated on !muted so a muted
804− // conversation doesn't interrupt, but the dedup tracking must not be
805− // — otherwise the first event after unmute for an already-seen message
806− // id would pass the counted.add() check (empty set) and re-increment.
807− val messageId = messageIdOfEvent(event)
808− val counted = unreadMessageIds.getOrPut(sid) {
809− java.util.Collections.synchronizedSet(mutableSetOf())
810− }
811− val isNewMessage = messageId == null || counted.add(messageId)
812− if (isNewMessage && sid !in _mutedSessions.value) {
813− // Skip the unread badge for muted sessions — the count is still
814− // tracked in unreadMessageIds (so unmuting can't re-count the
815− // same messages), but the visible badge is suppressed so a muted
816− // conversation doesn't interrupt. The completion notification is
817− // also gated on isSessionMuted (see notifySessionCompleted).
818− _unread.update { current ->
819− // Guard again inside the atomic update lambda so a retry
820− // (or an open that landed just now) can't reintroduce the
821− // badge for the session on screen.
822− if (sid == _currentSession.value) current
823− else current + (sid to (current[sid] ?: 0) + 1)
824− }
825− }
826− }
827− // Track sessions actively streaming so we know which idle events
828− // represent a finished run worth notifying about.
829− if (isLiveRunActivity(event)) {
830− // add() returns true only when the id is genuinely new. Only republish
831− // the run-state snapshot in that case: a continuously-streaming session
832− // re-adds its id on every token (hundreds/sec), and republishing each
833− // time allocates a fresh Set via toSet() + writes two StateFlows under
834− // the monitor — pure overhead since the set membership didn't change.
835− // The access-order refresh from LinkedHashSet.add still happens (keeping
836− // the session from being evicted by a reconnect sweep); we just skip the
837− // O(set size) snapshot + StateFlow writes when nothing changed.
838− synchronized(activeRuns) {
839− if (activeRuns.add(sid)) {
840− publishRunState()
841− }
842− }
843− }
844− } }.onFailure { Log.w("AppContainer", "Message activity observer failed, will retry: ${safeExceptionSummary(it)}") }
845− if (!isActive) break
846− delay(NetworkConfig.observerRetryDelayMs)
847− }
848− }
849− }
850−
851− /** True if [event] is live streaming activity worth tracking as an active run. A
852− * trailing message.updated that lands *after* the run finished (final cost/token totals,
853− * carrying a completion time) is NOT live streaming: with no further SessionIdle to
854− * follow it, re-adding the session would pin anyRunActive true indefinitely. */
855− private fun isLiveRunActivity(event: BusEvent): Boolean {
856− if (event !is MessagePartUpdated && event !is MessageUpdated) return false
857− // For MessageUpdated, only an in-flight *assistant* message counts as live activity.
858− // A UserMessage or UnknownMessage update (e.g. a metadata refresh of an existing user
859− // message) would otherwise add the session to activeRuns with no following SessionIdle
860− // to clear it — pinning anyRunActive true and the foreground notification indefinitely.
861− // Mirrors SessionRepository.isRunActivity's guard exactly.
862− if (event is MessageUpdated) {
863− val info = event.properties.info
864− return info is AssistantMessage && !info.isComplete && info.error == null
865− }
866− // A step-finish part is the trailing completion marker for a run (it carries the
867− // final cost/token totals) and arrives after the last stream delta. Like a completed
868− // message.updated, treating it as live would re-add the session to activeRuns with no
869− // following SessionIdle to clear it — pinning anyRunActive true indefinitely when such
870− // a part is replayed/reordered after the run already went idle.
871− val part = (event as MessagePartUpdated).properties.part
872− return part !is StepFinishPart
873− }
874−
875− /** Snapshot [activeRuns] into [_runningSessionIds] and derive [_anyRunActive] from it.
876− * MUST be called under the [activeRuns] monitor so the published flag and snapshot can't
877− * diverge from the set a concurrent SSE add()/remove() is mutating — the same invariant
878− * [connectLocked]/[teardownActiveLocked] rely on. */
879− private fun publishRunState() {
880− _anyRunActive.value = activeRuns.isNotEmpty()
881− _runningSessionIds.value = activeRuns.toSet()
882− }
883−
884− /** Session ids currently streaming an assistant run (best-effort, in-process). Backed by
885− * an access-order [java.util.LinkedHashMap] so re-adding an already-present id on each
886− * streaming event refreshes its recency (a plain LinkedHashSet.add is a no-op that does
887− * NOT reorder). Entries are drained by [SessionIdle] (and cleared wholesale on reconnect
888− * reconcile); we intentionally do NOT cap the set, because evicting the eldest would drop
889− * its completion notification when its SessionIdle eventually arrives — a busy server
890− * with many concurrent runs is still bounded by the server's own concurrency, so growth
891− * is not unbounded in practice. */
892− private val activeRuns: MutableSet<String> = java.util.Collections.synchronizedSet(
893− java.util.Collections.newSetFromMap(java.util.LinkedHashMap<String, Boolean>(16, 0.75f, true)),
894− )
895−
896− /** Per non-viewed session, the set of message ids already reflected in its unread
897− * count. De-duplicates the many streaming events that share one message id so the
898− * badge counts messages, not deltas. Cleared when a session is viewed or on connect. */
899− private val unreadMessageIds = java.util.concurrent.ConcurrentHashMap<String, MutableSet<String>>()
900−
901− /** Guards connect/disconnect so concurrent callers can't leak an old connection. */
902− private val connectionMutex = Mutex()
903−
904− /** Only persist the `lastUsed` timestamp if it's older than this, to avoid
905− * a DataStore + encrypted-prefs write on every rapid reconnect. */
906− private companion object {
907− const val LAST_USED_SAVE_THRESHOLD_MS = 60_000L
908− }
909−
910− /** Resolve the human-readable title for [sessionId] (best-effort), falling back to the id.
911− * Uses [originRepo] — the repository of the connection that emitted the event — so a
912− * server switch during the listSessions() round-trip doesn't resolve the title against
913− * an unrelated server (showing an opaque id, or worse, a colliding session's title). */
914− private suspend fun resolveSessionTitle(sessionId: String, originRepo: SessionRepository): String =
915− runCatchingCancellable {
916− originRepo.listSessions()?.firstOrNull { it.id == sessionId }?.displayTitle
917− }.getOrNull() ?: sessionId
918−
919− /** Resolve the title for [sessionId] (best-effort) and post a completion notification.
920− * [originProfileId] is the id of the server that ran the session; it's embedded in the
921− * inline-reply action so a follow-up routes back to THIS server even after the user switches
922− * connections (mirrors [notifyPermission]). */
923− private suspend fun notifySessionCompleted(sessionId: String, originRepo: SessionRepository, originProfileId: String) {
924− val title = resolveSessionTitle(sessionId, originRepo)
925− // Re-check viewing right before posting: the call site checks !isActivelyViewing(sid)
926− // at event time, but resolveSessionTitle() suspends on a listSessions() round-trip.
927− // If the user opened the session in that gap, setCurrentSession already cancelled the
928− // prior notification — posting a fresh one here would leave a "session ready" heads-up
929− // lingering while they're already looking at the finished run.
930− if (isActivelyViewing(sessionId)) return
931− // Suppress the completion notification for muted sessions — the whole point of muting
932− // is that a noisy conversation doesn't interrupt.
933− if (sessionId in _mutedSessions.value) return
934− appContext?.let { SessionNotifications.postCompleted(it, sessionId, title, originProfileId) }
935− }
936−
937− /** Post a heads-up permission notification for [permission], resolving its session title.
938− * [originConn] is the connection that emitted the permission event — its profile id is
939− * embedded in the notification so the receiver routes the response back to THIS server. */
940− private suspend fun notifyPermission(permission: Permission, originConn: OpencodeConnection) {
941− val sessionId = permission.sessionID.takeIf { it.isNotBlank() } ?: return
942− val title = resolveSessionTitle(sessionId, originConn.repository)
943− // Re-check viewing just before posting — see notifySessionCompleted for the race.
944− if (isActivelyViewing(sessionId)) return
945− appContext?.let { SessionNotifications.postPermission(it, permission, title, originConn.profile.id) }
946− }
947−
948− /** Post an error notification for a failed background run. [originProfileId] is embedded
949− * in the tap intent so the session opens under the server that ran it, not whichever
950− * is active when the user taps — mirroring [notifySessionCompleted]. */
951− private suspend fun notifySessionError(sessionId: String, originRepo: SessionRepository, originProfileId: String) {
952− val title = resolveSessionTitle(sessionId, originRepo)
953− // Re-check viewing just before posting — see notifySessionCompleted for the race.
954− if (isActivelyViewing(sessionId)) return
955− appContext?.let { SessionNotifications.postError(it, sessionId, title, originProfileId) }
956− }
957−
958− /** Respond to a permission from a notification action (Allow once / Always / Reject),
959− * off any UI. Runs on the process-lived app scope; [onDone] fires when the call resolves
960− * so the receiver's goAsync() result can finish. Its Boolean is true only when a live
961− * connection existed AND respondPermission succeeded — the receiver uses it to decide
962− * whether to dismiss the notification. A missing connection makes the respond a no-op,
963− * so it must report failure (not success) rather than let the notification vanish with
964− * the tool left unanswered.
965− *
966− * [profileId] is the id of the server that posted the permission request (embedded in
967− * the notification's PendingIntent). If it doesn't match the currently active
968− * connection's profile, the response is NOT sent: posting it to a different server
969− * would 404 (treated as "already resolved" success by respondPermission), dismissing
970− * the notification while the original server's tool stays paused forever. Reporting
971− * failure instead leaves the notification up so the user can switch back and retry. */
972− open fun respondToPermissionFromNotification(
973− sessionId: String,
974− permissionId: String,
975− response: PermissionResponse,
976− profileId: String?,
977− onDone: (Boolean) -> Unit,
978− ) {
979− appScope.launch {
980− // Guarantee onDone (so the BroadcastReceiver's goAsync() finishes) even if the
981− // scope is cancelled mid-call (process shutdown cancels appScope first). Without
982− // this, a cancelled scope leaves pending.finish() never called → a receiver ANR
983− // and the permission response silently lost.
984− var success = false
985− try {
986− success = runCatchingCancellable {
987− val conn = activeConnection.value ?: return@runCatchingCancellable false
988− // Route to the originating server only. A mismatch means the user
989− // switched servers while the permission was pending; sending the reply
990− // to the wrong server would be silently swallowed as a 404-success.
991− if (profileId != null && conn.profile.id != profileId) return@runCatchingCancellable false
992− conn.api.respondPermission(sessionId, permissionId, response)
993− true
994− }.onFailure {
995− Log.w("AppContainer", "notif permission respond failed: ${safeExceptionSummary(it)}")
996− }.getOrDefault(false)
997− } finally {
998− onDone(success)
999− }
1000− }
1001− }
1002−
1003− /** Send a follow-up prompt from a notification's inline reply, off any UI. Uses the
1004− * server's default model/agent. Routes through the durable [outboxStore] — the same path
1005− * the in-app composer uses ([soy.iko.opencode.ui.chat.ChatViewModel.enqueueOffline]) —
1006− * rather than a direct repository send, so a reply composed while disconnected survives to
1007− * be flushed on reconnect instead of being silently dropped. [flushOutbox] nudges an
1008− * immediate send when a connection is live, so an online reply still goes out now. [onDone]
1009− * reports whether the reply was durably enqueued so the receiver only dismisses the
1010− * notification on success. */
1011− open fun sendPromptFromNotification(sessionId: String, text: String, originProfileId: String?, onDone: (Boolean) -> Unit) {
1012− appScope.launch {
1013− // Guarantee onDone (so the BroadcastReceiver's goAsync() finishes) even if the
1014− // scope is cancelled mid-call — see respondToPermissionFromNotification above.
1015− var enqueued = false
1016− try {
1017− // Attribute to the profile that POSTED the notification (embedded in the reply
1018− // intent) so the follow-up is always enqueued against the server that owns
1019− // [sessionId] — never whichever server happens to be active now, which would POST
1020− // A's session id to B, 404, and silently drop the reply. Fall back to the active/
1021− // most-recent profile only for a legacy intent that predates the embedded id.
1022− val profileId = originProfileId
1023− ?: activeConnection.value?.profile?.id
1024− ?: runCatchingCancellable { profileStore.profiles.first().firstOrNull()?.id }.getOrNull()
1025− enqueued = if (profileId == null) {
1026− false
1027− } else {
1028− runCatchingCancellable {
1029− outboxStore.enqueue(
1030− OutboxMessage(
1031− id = java.util.UUID.randomUUID().toString(),
1032− profileId = profileId,
1033− sessionId = sessionId,
1034− text = text,
1035− model = null,
1036− createdAt = System.currentTimeMillis(),
1037− ),
1038− )
1039− }.onFailure {
1040− Log.w("AppContainer", "notif reply enqueue failed: ${safeExceptionSummary(it)}")
1041− }.isSuccess
1042− }
1043− if (enqueued) flushOutbox()
1044− } finally {
1045− onDone(enqueued)
1046− }
1047− }
1048− }
1049−
1050− /** Abort the active run for [sessionId] from a notification Stop action. Routes to the
1051− * originating profile only — sending the abort to a different server would 404 (silently
1052− * swallowed) and leave the original run stranded. A profile mismatch reports failure so the
1053− * notification stays up and the user can switch back, mirroring
1054− * [respondToPermissionFromNotification]'s routing guard. Runs on the app scope so it
1055− * survives the BroadcastReceiver's lifetime. */
1056− open fun abortRunFromNotification(sessionId: String, originProfileId: String?, onDone: (Boolean) -> Unit) {
1057− appScope.launch {
1058− var success = false
1059− try {
1060− val conn = activeConnection.value?.takeIf {
1061− originProfileId == null || it.profile.id == originProfileId
1062− }
1063− if (conn != null) {
1064− success = runCatchingCancellable { conn.repository.abort(sessionId) }.isSuccess
1065− }
1066− } finally {
1067− onDone(success)
1068− }
1069− }
1070− }
1071−
1072− /**
1073− * Retry the last user prompt for [sessionId] from an error notification's "Retry last"
1074− * action. Fetches the session's messages, re-sends the most recent user prompt, and
1075− * cancels the error notification on success. Routes to the originating profile's
1076− * connection only — sending the retry to a different server would 404 or start a fresh
1077− * run on an unrelated session id. A profile mismatch reports failure so the notification
1078− * stays up and the user can switch back, mirroring [respondToPermissionFromNotification]'s
1079− * routing guard. A no-op (reported as false) when there's no connection or no prior prompt.
1080− */
1081− open fun retryLastFromNotification(sessionId: String, originProfileId: String?, onDone: (Boolean) -> Unit) {
1082− appScope.launch {
1083− var success = false
1084− try {
1085− val conn = activeConnection.value?.takeIf {
1086− originProfileId == null || it.profile.id == originProfileId
1087− }
1088− if (conn != null) {
1089− success = runCatchingCancellable {
1090− val messages = conn.api.listMessages(sessionId)
1091− val lastPrompt = messages
1092− .lastOrNull { it.info is soy.iko.opencode.data.model.UserMessage }
1093− ?.parts
1094− ?.filterIsInstance<soy.iko.opencode.data.model.TextPart>()
1095− ?.joinToString("\n\n") { it.text }
1096− ?.takeIf { it.isNotBlank() }
1097− if (lastPrompt != null) {
1098− // model=null lets the server reuse the session's current model; we
1099− // don't know the originally-selected model from a notification context.
1100− conn.repository.sendPrompt(sessionId, lastPrompt, model = null)
1101− true
1102− } else {
1103− false
1104− }
1105− }.isSuccess
1106− }
1107− } finally {
1108− onDone(success)
1109− }
1110− }
1111− }
1112−
1113− /** Extract the session id an event pertains to, for message-activity events. */
1114− private fun sessionOf(event: BusEvent): String? = sessionOfEvent(event)
1115−
1116− /**
1117− * On cold start, transparently reconnect to the most recently used server so a
1118− * returning user lands in their session list instead of the empty server screen.
1119− */
1120− private suspend fun autoConnect() {
1121− val recent = runCatchingCancellable { profileStore.profiles.first() }
1122− .getOrDefault(emptyList())
1123− .firstOrNull() ?: return
1124− // The profile read above suspends on DataStore. A manual connect() to a different
1125− // server during that window establishes a connection the user explicitly chose; we must
1126− // not clobber it by connecting to `recent` on top. connectIfIdle() checks "is anything
1127− // active?" and connects atomically under connectionMutex, returning null if the cold-start
1128− // slot was already taken — closing the TOCTOU window an unlocked null-check plus connect()'s
1129− // unconditional close would leave. (disconnectIf below similarly guards the failed-ping
1130− // teardown by identity.)
1131− _reconnecting.value = true
1132− var conn: OpencodeConnection? = null
1133− try {
1134− val ok = runCatchingCancellable {
1135− conn = connectIfIdle(recent) ?: return@runCatchingCancellable false
1136− conn!!.api.ping()
1137− true
1138− }.getOrDefault(false)
1139− when {
1140− conn == null -> Unit // slot already taken by a manual connect — leave it be
1141− ok -> _autoConnectDone.value = true
1142− else -> disconnectIf(conn!!)
1143− }
1144− } finally {
1145− // Reset in a finally so a CancellationException (e.g. scope cancelled during
1146− // shutdown) can't leave the flag pinned true — runCatchingCancellable rethrows it,
1147− // skipping the line below the try block.
1148− _reconnecting.value = false
1149− }
1150− }
1151−
1152− /**
1153− * When the device regains connectivity, nudge the active SSE stream to reconnect
1154− * immediately instead of waiting out the exponential backoff.
1155− */
1156− private val networkCallback: ConnectivityManager.NetworkCallback? = registerNetworkMonitor()
1157−
1158− private fun registerNetworkMonitor(): ConnectivityManager.NetworkCallback? {
1159− if (appContext == null) return null
1160− val cm = appContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
1161− ?: return null
1162− // Seed the online state from the current active network so the indicator is
1163− // correct on cold start rather than defaulting to "online" until a callback fires.
1164− _isOnline.value = runCatching { cm.activeNetwork != null }.getOrDefault(true)
1165− val callback = object : ConnectivityManager.NetworkCallback() {
1166− override fun onAvailable(network: Network) { _isOnline.value = true; activeConnection.value?.events?.triggerReconnect() }
1167− // A matched (internet-capable) network was lost. Don't eagerly flip offline: during a
1168− // Wi-Fi→cellular handoff onLost(WiFi) fires before onAvailable(cellular) and
1169− // cm.activeNetwork is transiently null in that window — flashing offline there would
1170− // skip outbox flushing and blink the indicator. Instead re-check activeNetwork after a
1171− // short grace period and only report offline if there's still no active network.
1172− //
1173− // This MUST live in onLost, not onUnavailable: onUnavailable is delivered only for
1174− // requestNetwork() with a timeout, never for registerNetworkCallback() — relying on it
1175− // (as this once did) meant offline was never detected after the first onAvailable.
1176− override fun onLost(network: Network) {
1177− appScope.launch {
1178− delay(NetworkConfig.networkOfflineGraceMs)
1179− _isOnline.value = runCatching { cm.activeNetwork != null }.getOrDefault(true)
1180− }
1181− }
1182− }
1183− // Only match networks that actually provide internet — a capability-less request
1184− // fires onAvailable for transports that can't reach the server (and would trigger
1185− // spurious reconnects), so require NET_CAPABILITY_INTERNET.
1186− val request = NetworkRequest.Builder()
1187− .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1188− .build()
1189− runCatching { cm.registerNetworkCallback(request, callback) }
1190− .onFailure { Log.w("AppContainer", "Failed to register network callback", it) }
1191− return callback
1192− }
1193−
1194− /** Open (or re-open) a connection to [profile], replacing any current one.
1195− * Only persists the updated `lastUsed` timestamp if it's stale (older than a
1196− * minute), so rapid reconnect storms don't each trigger a DataStore write. */
1197− open suspend fun connect(profile: ServerProfile): OpencodeConnection =
1198− connectionMutex.withLock { connectLocked(profile) }
1199−
1200− /** Connect to the profile with [profileId], looking it up from [profileStore]. Returns
1201− * true on success, false if the profile wasn't found or connect threw. Used by the
1202− * notification body-tap path to route a session open back to the originating server. */
1203− open suspend fun connectByProfileId(profileId: String): Boolean {
1204− val profile = profileStore.profiles.first().find { it.id == profileId } ?: return false
1205− return runCatchingCancellable { connect(profile) }.isSuccess
1206− }
1207−
1208− /** Connect to [profile] only if nothing is currently active, checking-and-connecting
1209− * atomically under [connectionMutex]. Returns null (touching nothing) when a connection is
1210− * already active, so autoConnect() can't clobber a manual connect() the user made during its
1211− * suspending profile read — closing the TOCTOU window an unlocked null-check would leave. */
1212− private suspend fun connectIfIdle(profile: ServerProfile): OpencodeConnection? =
1213− connectionMutex.withLock {
1214− if (_activeConnection.value != null) null else connectLocked(profile)
1215− }
1216−
1217− /** Build and install a connection to [profile], replacing any current one. Caller MUST hold
1218− * [connectionMutex]. */
1219− private suspend fun connectLocked(profile: ServerProfile): OpencodeConnection {
1220− // Capture the previous profile id before closing, so we can preserve unread badges
1221− // when reconnecting to the same server — a brief network blip or manual reconnect
1222− // shouldn't erase "5 unread". Only a genuine server switch clears them.
1223− val previousProfileId = _activeConnection.value?.profile?.id
1224− _activeConnection.value?.close()
1225− _activeConnection.value = null
1226− // Mutate the run set and its derived flag together under activeRuns' monitor: the SSE
1227− // event handler adds ids under the same lock, so an unlocked clear() here could
1228− // interleave with an add()+flag=true and leave _anyRunActive pinned true with a torn-
1229− // down connection and no SessionIdle to clear it — a stuck foreground service.
1230− synchronized(activeRuns) {
1231− activeRuns.clear()
1232− publishRunState()
1233− }
1234− if (previousProfileId != profile.id) {
1235− _unread.value = emptyMap()
1236− unreadMessageIds.clear()
1237− }
1238− val now = System.currentTimeMillis()
1239− val resolved = profileStore.resolve(profile)
1240− val needsSave = (now - resolved.lastUsed) > LAST_USED_SAVE_THRESHOLD_MS
1241− val finalProfile = if (needsSave) resolved.copy(lastUsed = now) else resolved
1242− if (needsSave) profileStore.save(finalProfile)
1243− return OpencodeConnection(finalProfile, messageCacheStore).also { _activeConnection.value = it }
1244− }
1245−
1246− open suspend fun disconnect() {
1247− // Acquire the connection mutex so disconnect is serialized with connect().
1248− // Previously this was fire-and-forget (launch on appScope), which raced with
1249− // a subsequent connect(): connect() could acquire the mutex, create a new
1250− // connection, and then the pending disconnect() would close it.
1251− connectionMutex.withLock { teardownActiveLocked() }
1252− }
1253−
1254− /** Tear down [expected] only if it is still the active connection, with the identity
1255− * check performed *under* the mutex. A caller that checks `activeConnection.value === x`
1256− * itself and then calls [disconnect] has a TOCTOU race: a concurrent connect() to a
1257− * different server can replace the active connection in the gap, and [disconnect] would
1258− * then close that new connection. autoConnect()'s failed-ping teardown uses this. */
1259− private suspend fun disconnectIf(expected: OpencodeConnection) {
1260− connectionMutex.withLock {
1261− if (_activeConnection.value === expected) teardownActiveLocked()
1262− }
1263− }
1264−
1265− /** Close and reset the active connection. Caller MUST hold [connectionMutex]. */
1266− private suspend fun teardownActiveLocked() {
1267− _activeConnection.value?.close()
1268− _activeConnection.value = null
1269− // Reset run/unread state on disconnect too. With no SSE stream there's no
1270− // SessionIdle to drain activeRuns, so without this the working indicator
1271− // (anyRunActive) and unread badges would stay pinned until the next connect().
1272− // Mutate under activeRuns' monitor (see connect()) so a concurrent SSE add() can't
1273− // re-pin _anyRunActive after the clear.
1274− synchronized(activeRuns) {
1275− activeRuns.clear()
1276− publishRunState()
1277− }
1278− _unread.value = emptyMap()
1279− unreadMessageIds.clear()
1280− }
1281−
1282− /** Deferred profile deletions keyed by id, run on the process-lived [appScope] (not a
1283− * ViewModel scope) so navigating away during the undo window still commits the delete
1284− * instead of silently cancelling it — mirroring [CrashLogger.scheduleDelete]. */
1285− private val pendingProfileDeletes = java.util.concurrent.ConcurrentHashMap<String, Job>()
1286−
1287− /**
1288− * Schedule the profile [id] for deletion after [delayMs], cancellable via
1289− * [cancelProfileDelete] (the Undo action). [onDeleted]/[onError] run on [appScope]
1290− * after the delete resolves so the caller can clear its optimistic-hide state. A
1291− * repeated schedule for the same id replaces the prior timer.
1292− */
1293− open fun scheduleProfileDelete(
1294− id: String,
1295− delayMs: Long,
1296− onDeleted: () -> Unit,
1297− onError: (Throwable) -> Unit,
1298− ) {
1299− val job = appScope.launch {
1300− delay(delayMs)
1301− // Claim the delete by removing our own entry BEFORE committing it — the atomic
1302− // remove is the sync point with cancelProfileDelete. Losing the race (an undo
1303− // removed us first) means we skip, honouring cancel's `true`; deleting first
1304− // would let a cancel land in the gap and falsely report undo of a gone profile.
1305− // remove(id, thisJob) also no-ops for a stale job after a reschedule.
1306− val claimed = coroutineContext[Job]?.let { pendingProfileDeletes.remove(id, it) } == true
1307− if (!claimed) return@launch
1308− runCatchingCancellable { profileStore.delete(id) }
1309− .onSuccess { onDeleted() }
1310− .onFailure { onError(it) }
1311− }
1312− pendingProfileDeletes[id]?.cancel()
1313− pendingProfileDeletes[id] = job
1314− }
1315−
1316− /** Cancel a pending deferred profile delete (the Undo action). Returns true if it was
1317− * still pending (undo succeeded), false if the delete had already fired. */
1318− open fun cancelProfileDelete(id: String): Boolean {
1319− val job = pendingProfileDeletes.remove(id) ?: return false
1320− job.cancel()
1321− return true
1322− }
1323−
1324− /** Deferred session deletions keyed by id, run on the process-lived [appScope] (not a
1325− * ViewModel scope) so navigating away during the undo window still commits the delete
1326− * instead of silently cancelling it (which would leave the session deleted-in-UI but
1327− * alive on the server, reappearing on the next refresh). */
1328− private val pendingSessionDeletes = java.util.concurrent.ConcurrentHashMap<String, Job>()
1329−
1330− /** One-shot events carrying the id of a session scheduled for deferred deletion from
1331− * outside the session list (e.g. from the chat screen's Delete). The SessionListScreen
1332− * collects these to show an Undo snackbar, mirroring its own VM-level undo events. */
1333− private val _externalSessionUndoEvents = MutableSharedFlow<String>(
1334− extraBufferCapacity = NetworkConfig.snackbarEventBufferCapacity,
1335− onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
1336− )
1337− val externalSessionUndoEvents: SharedFlow<String> = _externalSessionUndoEvents.asSharedFlow()
1338−
1339− /** Emit an undo event for a session delete initiated outside the session list (e.g.
1340− * from the chat screen). The SessionListScreen collects these to show an Undo snackbar. */
1341− fun emitExternalSessionUndo(sessionId: String) {
1342− _externalSessionUndoEvents.tryEmit(sessionId)
1343− }
1344−
1345− /**
1346− * Schedule session [id] for deletion after [delayMs], cancellable via [cancelSessionDelete]
1347− * (the Undo action). Also clears the session's stored draft on a successful delete.
1348− * [onDeleted]/[onError] run on [appScope] after the delete resolves so the caller can update
1349− * its optimistic-hide state. A repeated schedule for the same id replaces the prior timer.
1350− *
1351− * The owning connection is captured now, at schedule time — NOT re-resolved when the timer
1352− * fires. Otherwise a server switch during the undo window would send the delete to whichever
1353− * server happens to be active at fire time: the original session would never be deleted (its
1354− * row reappears on the next refresh) and, in the rare id-collision case, an unrelated session
1355− * on the new server could be deleted instead. A disconnect closes the captured connection's
1356− * HTTP client, so a delete deferred across a disconnect fails and is surfaced via [onError]
1357− * (the session cannot be deleted on a server we're no longer connected to). No-ops (as an
1358− * error) if there is no active connection at schedule time.
1359− */
1360− open fun scheduleSessionDelete(
1361− id: String,
1362− delayMs: Long,
1363− onDeleted: () -> Unit,
1364− onError: (Throwable) -> Unit,
1365− ) {
1366− val conn = _activeConnection.value
1367− val job = appScope.launch {
1368− delay(delayMs)
1369− // Claim the delete by removing our own entry BEFORE committing it — the atomic
1370− // remove is the sync point with cancelSessionDelete. Losing the race (an undo
1371− // removed us first) means we skip, honouring cancel's `true`; deleting first
1372− // would let a cancel land in the gap and falsely report undo of a gone session.
1373− // remove(id, thisJob) also no-ops for a stale job after a reschedule.
1374− val claimed = coroutineContext[Job]?.let { pendingSessionDeletes.remove(id, it) } == true
1375− if (!claimed) return@launch
1376− if (conn == null) {
1377− onError(IllegalStateException("No active connection"))
1378− } else {
1379− runCatchingCancellable { conn.repository.deleteSession(id) }
1380− .onSuccess {
1381− draftStore.remove(id)
1382− attachmentDraftStore.remove(id)
1383− sessionPrefsStore.forget(id)
1384− messageCacheStore.remove(conn.profile.id, id)
1385− outboxStore.removeForSession(id)
1386− clearUnread(id)
1387− onDeleted()
1388− }
1389− .onFailure { onError(it) }
1390− }
1391− }
1392− pendingSessionDeletes[id]?.cancel()
1393− pendingSessionDeletes[id] = job
1394− }
1395−
1396− /** Cancel a pending deferred session delete (the Undo action). Returns true if it was
1397− * still pending (undo succeeded), false if the delete had already fired. */
1398− open fun cancelSessionDelete(id: String): Boolean {
1399− val job = pendingSessionDeletes.remove(id) ?: return false
1400− job.cancel()
1401− return true
1402− }
1403−
1404− /**
1405− * Probe a server URL (without credentials) to check reachability and detect whether
1406− * the server requires authentication. Builds a short-lived HTTP client with the same
1407− * base URL normalization as [connect] but no auth, calls the health endpoint, and
1408− * classifies the outcome:
1409− *
1410− * - 2xx → [ProbeResult.Reachable] (no auth needed)
1411− * - 401/403 → [ProbeResult.NeedsAuth]
1412− * - anything else → [ProbeResult.Unreachable] with a user-facing message
1413− *
1414− * The probe client is always closed afterwards so no resources linger. This does not
1415− * touch the active connection or the profile store.
1416− */
1417− open suspend fun probeServer(baseUrl: String, requireHttps: Boolean, certPin: String?): ProbeResult {
1418− return probeWithProfile(ServerProfile(
1419− id = "probe",
1420− label = "",
1421− baseUrl = baseUrl.trim(),
1422− username = null,
1423− password = null,
1424− // Probe the same effective URL save()/connect() will use: HttpClientFactory upgrades
1425− // http->https and installs the cert pinner when these are set, so a probe without them
1426− // would validate a plain-http endpoint the real connection never talks to.
1427− requireHttps = requireHttps,
1428− certPin = certPin,
1429− ))
1430− }
1431−
1432− /**
1433− * Probe a server URL *with* credentials to validate them. Returns true if the
1434− * server accepts the credentials (ping succeeds), false on 401/403, and throws
1435− * on other failures (unreachable, timeout) so the caller can surface a friendly
1436− * message. Mirrors [probeServer]'s short-lived-client pattern.
1437− */
1438− open suspend fun probeWithCredentials(
1439− baseUrl: String,
1440− username: String,
1441− password: String,
1442− requireHttps: Boolean,
1443− certPin: String?,
1444− ): Boolean {
1445− val probeProfile = ServerProfile(
1446− id = "probe-auth",
1447− label = "",
1448− baseUrl = baseUrl.trim(),
1449− username = username.trim().takeIf { it.isNotBlank() },
1450− password = password.trim().takeIf { it.isNotEmpty() },
1451− // Match the effective URL/pinning save()/connect() will use (see probeServer).
1452− requireHttps = requireHttps,
1453− certPin = certPin,
1454− )
1455− val client = HttpClientFactory.create(probeProfile)
1456− return try {
1457− val api = OpencodeApiClient(client)
1458− api.ping()
1459− true
1460− } catch (c: kotlinx.coroutines.CancellationException) {
1461− throw c
1462− } catch (e: Exception) {
1463− val status = responseStatusCode(e)
1464− if (status == 401 || status == 403) false else throw e
1465− } finally {
1466− runCatching { client.close() }
1467− }
1468− }
1469−
1470− private suspend fun probeWithProfile(profile: ServerProfile): ProbeResult {
1471− val client = HttpClientFactory.create(profile)
1472− return try {
1473− val api = OpencodeApiClient(client)
1474− api.ping()
1475− ProbeResult.Reachable
1476− } catch (c: kotlinx.coroutines.CancellationException) {
1477− throw c
1478− } catch (e: Exception) {
1479− val status = responseStatusCode(e)
1480− if (status == 401 || status == 403) {
1481− ProbeResult.NeedsAuth
1482− } else {
1483− ProbeResult.Unreachable(friendlyErrorFor(e, profile.baseUrl))
1484− }
1485− } finally {
1486− runCatching { client.close() }
1487− }
1488− }
1489−
1490− // Declared last so every property above is fully initialized before these observers start.
1491− // They only launch coroutines into appScope (Dispatchers.IO) — nothing here runs
1492− // synchronously during construction — so placing init at the end removes any dependence on
1493− // the textual declaration order of the fields those observers reference.
1494− init {
1495− if (!skipInit) {
1496− NotificationChannels.create(appContext!!)
1497− observeMessageActivity()
1498− observeRunReconcileOnReconnect()
1499− observeRunForegroundService()
1500− observeBackgroundedConnectionFailures()
1501− // Load the persisted muted-sessions set so isSessionMuted() reflects the choice
1502− // immediately on cold start (before any session list composition).
1503− appScope.launch {
1504− runCatchingCancellable {
1505− sessionPrefsStore.muted.collect { ids -> _mutedSessions.value = ids }
1506− }
1507− }
1508− // Flush right after load() populates the queue. observeOutbox()'s combine is keyed
1509− // on activeConnection/isOnline/_outboxFlushTrigger — NOT on outboxStore.messages — so
1510− // if connect() sets activeConnection before load() finishes reading a (possibly
1511− // multi-MB) outbox.json, the connect-triggered flush sees an empty queue and nothing
1512− // re-triggers it. Nudging the flush here guarantees a loaded queue is sent.
1513− appScope.launch {
1514− runCatchingCancellable { outboxStore.load() }
1515− flushOutbox()
1516− }
1517− observeOutbox()
1518− appScope.launch { autoConnect() }
1519− }
1520− }
1521−}
1522−
1523−/**
1524− * Extract the session id a message-activity event pertains to, or null for events that
1525− * don't describe message activity. This drives the unread badge: any session that
1526− * receives activity while it isn't the currently-viewed one gets badged. Extracted as
1527− * a top-level `internal` function so the rule is unit-testable without an Android
1528− * [Context] (the surrounding [AppContainer] needs one).
1529− */
1530−internal fun sessionOfEvent(event: BusEvent): String? = when (event) {
1531− is MessageUpdated -> event.properties.info.sessionID
1532− is MessagePartUpdated -> event.properties.part.sessionID ?: event.properties.sessionID
1533− else -> null
1534−}
1535−
1536−/**
1537− * The message id a message-activity event pertains to, used to de-duplicate the unread
1538− * badge so a reply's many streaming events count once. Null for events that carry no
1539− * message id (those fall back to being counted individually).
1540− */
1541−internal fun messageIdOfEvent(event: BusEvent): String? = when (event) {
1542− is MessageUpdated -> event.properties.info.id
1543− is MessagePartUpdated -> event.properties.messageID ?: event.properties.part.messageID
1544− else -> null
1545−}
app/src/main/java/soy/iko/opencode/di/OpencodeConnection.ktdeleted−47
@@ -1,47 +0,0 @@
1−package soy.iko.opencode.di
2−
3−import soy.iko.opencode.data.model.ServerProfile
4−import soy.iko.opencode.data.network.EventStreamClient
5−import soy.iko.opencode.data.network.HttpClientFactory
6−import soy.iko.opencode.data.network.OpencodeApiClient
7−import soy.iko.opencode.data.repo.MessageCacheStore
8−import soy.iko.opencode.data.repo.SessionRepository
9−import kotlinx.coroutines.CoroutineScope
10−import kotlinx.coroutines.Dispatchers
11−import kotlinx.coroutines.SupervisorJob
12−import kotlinx.coroutines.cancel
13−
14−/**
15− * An active connection to one opencode server. Bundles the Ktor client, REST API,
16− * SSE event stream, and the reducing repository, all sharing a connection-scoped
17− * coroutine scope that is cancelled on [close].
18− */
19−open class OpencodeConnection(
20− val profile: ServerProfile,
21− // Optional on-disk message cache, supplied by AppContainer, so conversations render
22− // instantly and stay readable offline. Null in the test constructor.
23− private val messageCache: MessageCacheStore? = null,
24−) {
25−
26− protected constructor() : this(ServerProfile(id = "", label = "", baseUrl = "http://localhost"), null)
27−
28− private val scopeJob = SupervisorJob()
29− private val scope by lazy { CoroutineScope(scopeJob + Dispatchers.IO) }
30− private val client by lazy { HttpClientFactory.create(profile) }
31−
32− open val api: OpencodeApiClient by lazy { OpencodeApiClient(client) }
33− open val events: EventStreamClient by lazy { EventStreamClient(client, scope) }
34− open val repository: SessionRepository by lazy { SessionRepository(api, events, messageCache, profile.id) }
35−
36− /**
37− * Cancel the coroutine scope and wait for in-flight work (including the SSE reader)
38− * to wind down before closing the HTTP client. Calling client.close() while the SSE
39− * coroutine is still mid-request produces a spurious "stream error, will retry"
40− * warning during normal teardown.
41− */
42− open suspend fun close() {
43− scope.cancel()
44− scopeJob.join()
45− runCatching { client.close() }
46− }
47−}
app/src/main/java/soy/iko/opencode/notification/NotificationActionReceiver.ktdeleted−195
@@ -1,195 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.content.BroadcastReceiver
4−import android.content.Context
5−import android.content.Intent
6−import androidx.core.app.RemoteInput
7−import soy.iko.opencode.OpencodeApp
8−import soy.iko.opencode.R
9−import soy.iko.opencode.data.model.PermissionResponse
10−import soy.iko.opencode.data.network.NetworkConfig
11−import java.util.concurrent.atomic.AtomicBoolean
12−
13−/**
14− * Handles the action buttons on the app's notifications so the user can respond without
15− * opening the app — the core of the "kick it off and walk away" flow:
16− *
17− * - [ACTION_PERMISSION] with a [PermissionResponse] → replies to a paused tool's permission
18− * request (Allow once / Always / Reject) via the active connection.
19− * - [ACTION_REPLY] with a [RemoteInput] text payload → sends a follow-up prompt to a session
20− * that just finished a run.
21− *
22− * The receiver is not exported (see the manifest); the [PendingIntent]s that target it are
23− * created by the app itself. Work is done on the process-lived app scope via [OpencodeApp]'s
24− * container, and [goAsync] keeps the receiver alive until the (network) call resolves.
25− *
26− * A watchdog finishes the [PendingResult] within [NetworkConfig.notificationReceiverTimeoutMs]
27− * so a slow network call (e.g. a permission respond retried with exponential backoff) can't
28− * ANR the receiver. The underlying call keeps running on the app scope; only the receiver's
29− * lifetime is bounded. [finishOnce] guards against a double finish() (which would throw).
30− */
31−class NotificationActionReceiver : BroadcastReceiver() {
32−
33− override fun onReceive(context: Context, intent: Intent) {
34− val container = (context.applicationContext as? OpencodeApp)?.container ?: return
35− if (intent.action == ACTION_STOP_RUN) {
36− handleStopRun(context, container, intent)
37− return
38− }
39− val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() } ?: return
40− when (intent.action) {
41− ACTION_MARK_READ -> {
42− // "Mark read" from a completion notification — clear the unread badge and
43− // dismiss the notification without opening the session.
44− container.markSessionRead(sessionId)
45− SessionNotifications.cancel(context, sessionId)
46− return
47− }
48− ACTION_PERMISSION -> {
49− val permissionId = intent.getStringExtra(EXTRA_PERMISSION_ID)?.takeIf { it.isNotBlank() } ?: return
50− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
51− val response = PermissionResponse.entries.firstOrNull {
52− it.wire == intent.getStringExtra(EXTRA_RESPONSE)
53− } ?: return
54− val pending = goAsync()
55− val finished = AtomicBoolean(false)
56− var watchdogThread: Thread? = null
57− val finishOnce = {
58− if (finished.compareAndSet(false, true)) {
59− watchdogThread?.interrupt()
60− pending.finish()
61− }
62− }
63− watchdogThread = watchdog(finishOnce)
64− container.respondToPermissionFromNotification(sessionId, permissionId, response, profileId) { success ->
65− // Only dismiss the notification once the tool was actually answered. If
66− // there was no live connection (respond is a no-op) or the call failed,
67− // leave it up so the user can retry — otherwise it vanishes with the
68− // permission request left unanswered.
69− if (success) SessionNotifications.cancelPermission(context, sessionId)
70− finishOnce()
71− }
72− }
73− ACTION_REPLY -> {
74− val text = RemoteInput.getResultsFromIntent(intent)
75− ?.getCharSequence(KEY_REPLY_TEXT)?.toString()?.trim()
76− ?.takeIf { it.isNotEmpty() }
77− if (text == null) {
78− // The RemoteInput fired but the reply was empty/whitespace. SystemUI locks the
79− // inline field in a "sending…" state until the notification is updated or
80− // cancelled — cancel it so the field doesn't stay stuck with nothing to send.
81− SessionNotifications.cancel(context, sessionId)
82− return
83− }
84− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
85− val pending = goAsync()
86− val finished = AtomicBoolean(false)
87− var watchdogThread: Thread? = null
88− val finishOnce = {
89− if (finished.compareAndSet(false, true)) {
90− watchdogThread?.interrupt()
91− pending.finish()
92− }
93− }
94− watchdogThread = watchdog(finishOnce)
95− container.sendPromptFromNotification(sessionId, text, profileId) { enqueued ->
96− // The reply is durably queued (and flushed now if online). Show a brief
97− // "Sent" confirmation by updating the completion notification's text, then
98− // let it auto-cancel on tap — instead of vanishing silently. If the enqueue
99− // failed, post a "reply not sent" error: leaving the completion notification
100− // up strands SystemUI's RemoteInput field in a permanent "sending…" spinner
101− // that can't be resubmitted, so "leave it up to retry" doesn't actually let
102− // the user retry.
103− if (enqueued) {
104− SessionNotifications.postReplySent(context, sessionId, profileId)
105− } else {
106− SessionNotifications.postReplyFailed(context, sessionId, profileId)
107− }
108− finishOnce()
109− }
110− }
111− ACTION_RETRY_LAST -> {
112− // "Retry last" from an error notification: re-send the most recent user prompt
113− // for this session without opening the app. Cancels the error notification on
114− // success so the user sees the retry took effect.
115− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
116− val pending = goAsync()
117− val finished = AtomicBoolean(false)
118− var watchdogThread: Thread? = null
119− val finishOnce = {
120− if (finished.compareAndSet(false, true)) {
121− watchdogThread?.interrupt()
122− pending.finish()
123− }
124− }
125− watchdogThread = watchdog(finishOnce)
126− container.retryLastFromNotification(sessionId, profileId) { success ->
127− if (success) SessionNotifications.cancel(context, sessionId)
128− finishOnce()
129− }
130− }
131− }
132− }
133−
134− /** Handle the Stop action from the foreground-service notification. Extracted from
135− * [onReceive] to keep that function's cyclomatic complexity under detekt's threshold. */
136− private fun handleStopRun(context: Context, container: soy.iko.opencode.di.AppContainer, intent: Intent) {
137− // The session id may be absent if multiple runs were active (generic notification);
138− // in that case we can't target a specific run — just let it ride.
139− val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() } ?: return
140− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
141− val pending = goAsync()
142− val finished = AtomicBoolean(false)
143− var watchdogThread: Thread? = null
144− val finishOnce = {
145− if (finished.compareAndSet(false, true)) {
146− watchdogThread?.interrupt()
147− pending.finish()
148− }
149− }
150− watchdogThread = watchdog(finishOnce)
151− container.abortRunFromNotification(sessionId, profileId) { success ->
152− // On a failed abort (transient network error), the run continues but the FGS
153− // notification will disappear once anyRunActive clears — leaving the user with
154− // no signal that their Stop tap didn't take. Post a quick "couldn't stop"
155− // notification so they know to open the app. On success, the FGS disappearing
156− // is sufficient feedback.
157− if (!success) {
158− SessionNotifications.postError(
159− context, sessionId,
160− context.getString(R.string.couldnt_stop_run),
161− profileId,
162− )
163− }
164− finishOnce()
165− }
166− }
167−
168− /** Schedule a deadline after which the receiver's [PendingResult] is finished even if
169− * the network call hasn't resolved, so the system can't ANR the receiver. The
170− * underlying work continues on the app scope. Returns the watchdog thread so the
171− * caller can [interrupt][Thread.interrupt] it when work completes early, releasing
172− * the sleeping thread immediately instead of leaving it for the full timeout. */
173− private fun watchdog(finishOnce: () -> Unit): Thread =
174− Thread {
175− try {
176− Thread.sleep(NetworkConfig.notificationReceiverTimeoutMs)
177− } catch (_: InterruptedException) {
178− return@Thread
179− }
180− finishOnce()
181− }.apply { isDaemon = true; name = "notif-receiver-watchdog"; start() }
182−
183− companion object {
184− const val ACTION_PERMISSION = "soy.iko.opencode.action.PERMISSION"
185− const val ACTION_REPLY = "soy.iko.opencode.action.REPLY"
186− const val ACTION_STOP_RUN = "soy.iko.opencode.action.STOP_RUN"
187− const val ACTION_MARK_READ = "soy.iko.opencode.action.MARK_READ"
188− const val ACTION_RETRY_LAST = "soy.iko.opencode.action.RETRY_LAST"
189− const val EXTRA_SESSION_ID = "soy.iko.opencode.extra.SESSION_ID"
190− const val EXTRA_PERMISSION_ID = "soy.iko.opencode.extra.PERMISSION_ID"
191− const val EXTRA_PROFILE_ID = "soy.iko.opencode.extra.PROFILE_ID"
192− const val EXTRA_RESPONSE = "soy.iko.opencode.extra.RESPONSE"
193− const val KEY_REPLY_TEXT = "soy.iko.opencode.key.REPLY_TEXT"
194− }
195−}
app/src/main/java/soy/iko/opencode/notification/NotificationChannels.ktdeleted−65
@@ -1,65 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.app.NotificationChannel
4−import android.app.NotificationManager
5−import android.content.Context
6−import soy.iko.opencode.R
7−
8−/**
9− * The app's notification channels. Created once at startup (idempotent — recreating an
10− * existing channel is a no-op). Two channels keep user control granular:
11− *
12− * - [STATUS]: low-importance, no sound. Used by the foreground service's persistent
13− * "agent running" indicator.
14− * - [COMPLETED]: default importance. Used when a background session finishes a run.
15− * - [PERMISSION]: high importance (heads-up + sound). Used when a paused tool run needs
16− * the user's approval — the whole point is to reach the user who has walked away, so it
17− * interrupts rather than sitting silently in the shade.
18− * - [ERROR]: default importance. Used when a background run fails.
19− */
20−object NotificationChannels {
21− const val STATUS = "run_status"
22− const val COMPLETED = "session_completed"
23− const val PERMISSION = "permission_request"
24− const val ERROR = "session_error"
25− const val UNREAD = "unread_badge"
26−
27− fun create(context: Context) {
28− val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
29− nm.createNotificationChannel(
30− NotificationChannel(STATUS, context.getString(R.string.notif_channel_status), NotificationManager.IMPORTANCE_LOW).apply {
31− description = context.getString(R.string.notif_channel_status_desc)
32− setShowBadge(false)
33− },
34− )
35− nm.createNotificationChannel(
36− NotificationChannel(COMPLETED, context.getString(R.string.notif_channel_completed), NotificationManager.IMPORTANCE_DEFAULT).apply {
37− description = context.getString(R.string.notif_channel_completed_desc)
38− },
39− )
40− nm.createNotificationChannel(
41− NotificationChannel(PERMISSION, context.getString(R.string.notif_channel_permission), NotificationManager.IMPORTANCE_HIGH).apply {
42− description = context.getString(R.string.notif_channel_permission_desc)
43− },
44− )
45− nm.createNotificationChannel(
46− // HIGH importance so a failed run stands out from a completed one by
47− // sound/vibration — both are actionable, but a failure is time-sensitive.
48− NotificationChannel(ERROR, context.getString(R.string.notif_channel_error), NotificationManager.IMPORTANCE_HIGH).apply {
49− description = context.getString(R.string.notif_channel_error_desc)
50− },
51− )
52− // A silent, badge-only channel that carries the launcher icon's unread count (the only
53− // way to badge the launcher icon on Android is via a notification on a badge-enabled
54− // channel). Low importance + no sound/vibration so it never alerts; setShowBadge(true)
55− // so its number renders on the launcher icon.
56− nm.createNotificationChannel(
57− NotificationChannel(UNREAD, context.getString(R.string.notif_channel_unread), NotificationManager.IMPORTANCE_MIN).apply {
58− description = context.getString(R.string.notif_channel_unread_desc)
59− setShowBadge(true)
60− setSound(null, null)
61− enableVibration(false)
62− },
63− )
64− }
65−}
app/src/main/java/soy/iko/opencode/notification/RunForegroundService.ktdeleted−323
@@ -1,323 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.app.Notification
4−import android.app.PendingIntent
5−import android.app.Service
6−import android.content.Context
7−import android.content.Intent
8−import android.content.pm.ServiceInfo
9−import android.content.res.Configuration
10−import android.os.Build
11−import android.os.IBinder
12−import android.util.Log
13−import android.annotation.SuppressLint
14−import androidx.core.app.NotificationCompat
15−import androidx.core.app.NotificationManagerCompat
16−import androidx.core.app.ServiceCompat
17−import soy.iko.opencode.MainActivity
18−import soy.iko.opencode.R
19−
20−/**
21− * A foreground service kept alive while an opencode agent is actively running. Holding a
22− * foreground priority lets the long-lived SSE `/event` subscription survive backgrounding
23− * (Doze/app-standby would otherwise choke the socket and stall streaming mid-run).
24− *
25− * The service is started when a run begins ([start]) and stopped when it goes idle
26− * ([stop]). It shows a low-importance "Agent is working…" notification in [NotificationChannels.STATUS].
27− * Started/stopped via Compose from the chat screen based on the `running` state.
28− */
29−class RunForegroundService : Service() {
30−
31− // Wall-clock time the current run started, captured on the first onStartCommand of
32− // the run and reused across progress-driven notification rebuilds so the chronometer's
33− // base doesn't jump back to 0:00 every time the agent advances a step. Reset to 0 in
34− // onDestroy once the run ends (stop() → onDestroy) so the next run starts fresh.
35− //
36− // Instance field (not companion/static): a static field would survive a stopped-then-
37− // recreated service instance and leave the chronometer pinned to a previous run's start
38− // if onDestroy hadn't run yet when the next run's first intent arrived. As an instance
39− // field it's reset by construction on every new Service instance.
40− private var runStartMillis: Long = 0L
41− // Whether *this* service instance has successfully called startForeground. Tracked so
42− // progress-driven re-starts (which re-enter onStartCommand) don't re-call startForeground
43− // and re-bind the 5s obligation each time — that would let a backgrounded re-start throw
44− // ForegroundServiceStartNotAllowedException even though the service is already in the
45− // foreground. After the first successful startForeground, progress updates refresh the
46− // notification via NotificationManager.notify directly (see [updateProgress]), which
47− // never throws the background-start exception.
48− private var isInForeground: Boolean = false
49− // The most recent session title/id/profile/progress handed to onStartCommand, retained so
50− // [updateProgress] can rebuild the notification with a new progress string without a fresh
51− // startForegroundService intent (which can throw when backgrounded).
52− private var lastTitle: String? = null
53− private var lastSessionId: String? = null
54− private var lastProfileId: String? = null
55− private var lastProgress: String? = null
56−
57− @android.annotation.SuppressLint("MissingPermission")
58− override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
59− instance = this
60− // The session title (when a single run is active) is passed via the intent extra so
61− // the notification can identify which session is running, instead of a generic
62− // "Agent is working…". Null/blank falls back to the generic title.
63− val sessionTitle = intent?.getStringExtra(EXTRA_SESSION_TITLE)?.takeIf { it.isNotBlank() }
64− val sessionId = intent?.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() }
65− val profileId = intent?.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
66− val progress = intent?.getStringExtra(EXTRA_PROGRESS)?.takeIf { it.isNotBlank() }
67− lastTitle = sessionTitle
68− lastSessionId = sessionId
69− lastProfileId = profileId
70− lastProgress = progress
71− // Capture the wall-clock start of the *first* intent of this run and reuse it across
72− // rebuilds so the chronometer's base doesn't jump back to 0:00 every time the agent
73− // advances a step. As an instance field it's 0 on a fresh service, so a recreated
74− // service (after onDestroy reset) starts the clock fresh too.
75− if (runStartMillis == 0L) runStartMillis = System.currentTimeMillis()
76− val notification = buildNotification(sessionTitle, sessionId, profileId, progress)
77− // Only call startForeground once per service lifetime — re-calling it on every
78− // progress-driven re-start re-binds the "must call startForeground within 5s"
79− // obligation each time, and if the app is backgrounded between two progress
80− // updates the new call can throw ForegroundServiceStartNotAllowedException even
81− // though the service is already in the foreground. That would drop foreground
82− // priority mid-run (the catch below stopSelf()s, killing the FGS while
83− // anyRunActive is still true). After the first successful startForeground,
84− // progress updates refresh the notification via NotificationManager.notify
85− // directly, which never throws the background-start exception.
86− if (!isInForeground) {
87− runCatching {
88− ServiceCompat.startForeground(
89− this,
90− NOTIF_ID,
91− notification,
92− if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
93− ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
94− } else {
95− 0
96− },
97− )
98− }.onFailure {
99− Log.w(TAG, "startForeground failed; running without foreground priority", it)
100− stopSelf()
101− }.also { isInForeground = it.isSuccess }
102− } else {
103− // Already in the foreground: refresh the notification in place. NotificationManager
104− // updates an ongoing notification without re-asserting foreground priority.
105− runCatching {
106− NotificationManagerCompat.from(this).notify(NOTIF_ID, notification)
107− }.onFailure { Log.w(TAG, "Failed to update foreground notification", it) }
108− }
109− return START_NOT_STICKY
110− }
111−
112− /** Rebuild the notification with an updated progress string and re-notify in place, *without*
113− * re-entering [onStartCommand] (and therefore without calling [Context.startForegroundService],
114− * which can throw [android.app.ForegroundServiceStartNotAllowedException] on Android 12+ when
115− * the app is backgrounded — even if the service is already in the foreground). Called directly
116− * by the companion [updateProgress] when a progress refresh is needed while the service is
117− * already running; falls back to [start] (which goes through startForegroundService) when the
118− * service isn't alive yet, so the first progress update still lands. */
119− @SuppressLint("MissingPermission")
120− private fun updateProgress(progress: String?) {
121− lastProgress = progress
122− val notification = buildNotification(lastTitle, lastSessionId, lastProfileId, progress)
123− runCatching {
124− NotificationManagerCompat.from(this).notify(NOTIF_ID, notification)
125− }.onFailure { Log.w(TAG, "Failed to update foreground notification progress", it) }
126− }
127−
128− private fun mainContentIntent(): PendingIntent {
129− // Tapping the notification opens the app so the user can see the running session.
130− val openIntent = Intent(this, MainActivity::class.java).apply {
131− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
132− }
133− return PendingIntent.getActivity(
134− this, 0, openIntent,
135− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
136− )
137− }
138−
139− private fun buildNotification(
140− sessionTitle: String?,
141− sessionId: String?,
142− profileId: String? = null,
143− progress: String? = null,
144− ): Notification {
145− val pendingIntent = mainContentIntent()
146− val contentText = progress ?: sessionTitle ?: getString(R.string.notif_running_text)
147− val builder = NotificationCompat.Builder(this, NotificationChannels.STATUS)
148− .setSmallIcon(R.drawable.ic_stat_notify)
149− .setColor(brandColor(this))
150− .setContentTitle(getString(R.string.notif_running_title))
151− .setContentText(contentText)
152− .setContentIntent(pendingIntent)
153− .setOngoing(true)
154− // Show a live elapsed timer so the user can see how long the current run has
155− // been going — no per-tick plumbing needed; the system renders the chronometer.
156− // runStartMillis is captured once at the start of the run (see onStartCommand)
157− // and reused across progress-driven rebuilds so the chronometer base is stable.
158− .setWhen(runStartMillis)
159− .setUsesChronometer(true)
160− .setShowWhen(true)
161− .setPriority(NotificationCompat.PRIORITY_LOW)
162− .setCategory(NotificationCompat.CATEGORY_PROGRESS)
163− // An indeterminate progress bar so the notification reads as actively "in progress"
164− // at a glance (alongside the chronometer), matching the conventional run affordance.
165− .setProgress(0, 0, true)
166− // Add a Stop action so the user can cancel the run without opening the app — the
167− // core of the "kick it off and walk away" flow. Only when a specific session is
168− // known (multiple concurrent runs can't be targeted individually). The profile id
169− // is embedded so [AppContainer.abortRunFromNotification]'s routing guard sends the
170− // abort to the originating server even if the user has switched profiles between
171− // starting the run and tapping Stop (mirroring the other notification actions).
172− if (sessionId != null) {
173− val stopIntent = Intent(this, NotificationActionReceiver::class.java).apply {
174− action = NotificationActionReceiver.ACTION_STOP_RUN
175− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
176− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
177− }
178− val stopPending = PendingIntent.getBroadcast(
179− this, sessionId.hashCode(), stopIntent,
180− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
181− )
182− builder.addAction(
183− R.drawable.ic_action_stop,
184− getString(R.string.notif_action_stop),
185− stopPending,
186− )
187− }
188− return builder.build()
189− }
190−
191− // Android 14+ can time out a foreground service (notably the ~6h/day cumulative cap on
192− // dataSync in Android 15) and calls onTimeout expecting a prompt stop; not stopping risks
193− // the system force-stopping/ANR-ing the app. Stop cleanly — a still-active run just
194− // continues without foreground priority. Post a low-priority notification so the user
195− // knows their long-running task may be paused in the background, rather than silently
196− // losing foreground priority. Both overloads are covered (the 2-arg form is API 35+).
197− override fun onTimeout(startId: Int) {
198− Log.w(TAG, "Foreground service timed out; stopping")
199− postTimeoutNotification()
200− stopSelf()
201− }
202−
203− override fun onTimeout(startId: Int, fgsType: Int) {
204− Log.w(TAG, "Foreground service timed out (type=$fgsType); stopping")
205− postTimeoutNotification()
206− stopSelf()
207− }
208−
209− /** Post a low-priority notification informing the user that the foreground service was
210− * timed out by the system — the run continues but may be killed by Doze without warning. */
211− @SuppressLint("MissingPermission")
212− private fun postTimeoutNotification() {
213− runCatching {
214− val notification = NotificationCompat.Builder(this, NotificationChannels.STATUS)
215− .setSmallIcon(R.drawable.ic_stat_notify)
216− .setColor(brandColor(this))
217− .setContentTitle(getString(R.string.notif_running_title))
218− .setContentText(getString(R.string.notif_fg_timeout_text))
219− .setContentIntent(mainContentIntent())
220− .setAutoCancel(true)
221− .setPriority(NotificationCompat.PRIORITY_LOW)
222− .build()
223− NotificationManagerCompat.from(this).notify(NOTIF_TIMEOUT_ID, notification)
224− }
225− }
226−
227− override fun onDestroy() {
228− // Safety net: if the process is being killed while a run is in progress,
229− // ensure the notification is removed rather than lingering.
230− ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
231− // Clear the run-start / foreground / instance state so the next run's chronometer
232− // begins fresh and startForeground is re-asserted on the first intent of the next
233− // run. These are instance fields, so a recreated service resets them by construction
234− // — but clearing here also covers the same-instance restart case.
235− runStartMillis = 0L
236− isInForeground = false
237− lastTitle = null
238− lastSessionId = null
239− lastProfileId = null
240− lastProgress = null
241− instance = null
242− super.onDestroy()
243− }
244−
245− override fun onBind(intent: Intent?): IBinder? = null
246−
247− // Reset the brand-color cache when the configuration (notably uiMode/night mode) changes
248− // so the notification icon tint follows the app theme instead of staying pinned to whatever
249− // the first build resolved. The service isn't recreated on a config change (it's a service,
250− // not an Activity), so without this the cached color is stale until onDestroy.
251− override fun onConfigurationChanged(newConfig: Configuration) {
252− super.onConfigurationChanged(newConfig)
253− brandColorCache = 0
254− }
255−
256− companion object {
257− private const val TAG = "RunForegroundService"
258− private const val NOTIF_ID = 1
259− private const val NOTIF_TIMEOUT_ID = 2
260− // Brand accent for the foreground notifications' small-icon tint circle. Resolved
261− // from resources (R.color.notif_brand) so it follows the app theme (light/dark)
262− // instead of a hardcoded constant. Lazily computed on first use from the app context
263− // and reset in onConfigurationChanged so a theme toggle mid-run doesn't pin the tint
264− // to the old theme for the rest of the run.
265− private var brandColorCache: Int = 0
266− private fun brandColor(context: Context): Int {
267− if (brandColorCache == 0) {
268− brandColorCache = androidx.core.content.ContextCompat.getColor(context, R.color.notif_brand)
269− }
270− return brandColorCache
271− }
272− // Live reference to the running service instance, published in onStartCommand and
273− // cleared in onDestroy. @Volatile so [updateProgress]'s read from the app-scope
274− // coroutine sees the most recent publication. Null when the service isn't running.
275− @Volatile private var instance: RunForegroundService? = null
276− const val EXTRA_SESSION_TITLE = "soy.iko.opencode.extra.SESSION_TITLE"
277− const val EXTRA_SESSION_ID = "soy.iko.opencode.extra.SESSION_ID"
278− const val EXTRA_PROFILE_ID = "soy.iko.opencode.extra.PROFILE_ID"
279− const val EXTRA_PROGRESS = "soy.iko.opencode.extra.PROGRESS"
280−
281− /** Start the service (or refresh an already-running one). [profileId] is embedded in the
282− * Stop action's PendingIntent so an abort from the notification reaches the originating
283− * server even after a profile switch. */
284− fun start(
285− context: Context,
286− sessionTitle: String? = null,
287− sessionId: String? = null,
288− profileId: String? = null,
289− progress: String? = null,
290− ) {
291− // If the service is already in the foreground, refresh the notification in place
292− // via NotificationManager.notify (through the live instance) instead of going
293− // through startForegroundService. On Android 12+, startForegroundService can
294− // throw ForegroundServiceStartNotAllowedException when the app is backgrounded
295− // — *even if the service is already running in the foreground* — and the
296− // runCatching below would swallow it, leaving the progress text un-updated
297− // precisely when the app is backgrounded (the FGS's whole purpose). The in-place
298− // notify never throws, so progress refreshes always land while the service runs.
299− val live = instance
300− if (live != null) {
301− live.updateProgress(progress)
302− return
303− }
304− // startForegroundService can throw ForegroundServiceStartNotAllowedException
305− // on Android 12+ if the app is in the background. Wrap it so a backgrounded
306− // start (e.g. the user navigates away at the wrong moment) doesn't crash.
307− runCatching {
308− val intent = Intent(context, RunForegroundService::class.java)
309− sessionTitle?.let { intent.putExtra(EXTRA_SESSION_TITLE, it) }
310− sessionId?.let { intent.putExtra(EXTRA_SESSION_ID, it) }
311− profileId?.let { intent.putExtra(EXTRA_PROFILE_ID, it) }
312− progress?.let { intent.putExtra(EXTRA_PROGRESS, it) }
313− context.startForegroundService(intent)
314− }.onFailure {
315− Log.w(TAG, "startForegroundService failed; running without foreground priority", it)
316− }
317− }
318−
319− fun stop(context: Context) {
320− context.stopService(Intent(context, RunForegroundService::class.java))
321− }
322− }
323−}
app/src/main/java/soy/iko/opencode/notification/SessionNotifications.ktdeleted−556
@@ -1,556 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.annotation.SuppressLint
4−import android.app.Notification
5−import android.app.NotificationManager
6−import android.app.PendingIntent
7−import android.content.Context
8−import android.content.Intent
9−import android.os.Build
10−import android.util.Log
11−import androidx.core.app.NotificationCompat
12−import androidx.core.app.NotificationManagerCompat
13−import androidx.core.app.RemoteInput
14−import soy.iko.opencode.MainActivity
15−import soy.iko.opencode.R
16−import soy.iko.opencode.data.model.Permission
17−import soy.iko.opencode.data.model.PermissionResponse
18−import java.security.MessageDigest
19−
20−/**
21− * Builds and posts the app's session notifications:
22− *
23− * - [postCompleted]: a "session ready" notification when a background run finishes, with an
24− * inline [RemoteInput] Reply action so a follow-up can be sent without opening the app.
25− * - [postPermission]: a heads-up notification when a paused tool needs approval, with
26− * Allow once / Always / Reject action buttons handled by [NotificationActionReceiver].
27− * - [postError]: a notification when a background run fails.
28− *
29− * Tapping a notification body opens the session via [MainActivity] with an
30− * [MainActivity.EXTRA_SESSION_ID] extra. Notification posting is guarded for Android 13+
31− * runtime permission: if the user hasn't granted POST_NOTIFICATIONS, the post is silently
32− * skipped rather than throwing.
33− */
34−object SessionNotifications {
35−
36− private const val NOTIF_ID_PREFIX = 4000
37− private const val TAG = "SessionNotifications"
38− // Fixed notification IDs use NEGATIVE space (mirroring the SUMMARY_*_ID constants below)
39− // so they can never collide with the hash-derived per-session IDs returned by notifId(),
40− // which are always positive (NOTIF_ID_PREFIX + (hash % (0x7FFFFFFF - NOTIF_ID_PREFIX)),
41− // range [4000, 2147483646]). A collision would let a session-specific notification
42− // overwrite or be canceled by the fixed one (~1 in 2 billion per session, but a real
43− // ID-space flaw). Negative IDs are valid for NotificationManager.cancel/notify.
44− private const val UNREAD_BADGE_ID = -10
45− private const val CONNECTION_LOST_ID = -11
46−
47− // Distinct namespaces so a session can have a completion, a permission, and an error
48− // notification outstanding at once without their ids colliding.
49− private const val NS_COMPLETED = "done"
50− private const val NS_PERMISSION = "perm"
51− private const val NS_ERROR = "err"
52−
53− private val notifIdRegex = Regex("[^A-Za-z0-9_-]")
54−
55− /** Derive a stable, collision-resistant notification id from a namespace + session id.
56− * String.hashCode() can collide for different inputs; a SHA-256 truncated to 31
57− * bits makes accidental collisions astronomically unlikely. The namespace keeps the
58− * three notification kinds for one session in separate id spaces. */
59− private fun notifId(namespace: String, sessionId: String): Int {
60− val digest = runCatching { MessageDigest.getInstance("SHA-256") }
61− .getOrNull()?.digest("$namespace:$sessionId".toByteArray()) ?: return NOTIF_ID_PREFIX
62− // Take the first 4 bytes, mask to 31 bits (always positive) to fit an Int id.
63− // Kotlin's shl/or/and are equal-precedence infix functions evaluated strictly
64− // left-to-right, so the shifts MUST be parenthesized individually — otherwise
65− // `a shl 24 or b shl 16` parses as `((a shl 24) or b) shl 16`, shifting the first
66− // byte out of the Int entirely and collapsing the id's entropy.
67− val hash = (((digest[0].toInt() and 0xFF) shl 24) or
68− ((digest[1].toInt() and 0xFF) shl 16) or
69− ((digest[2].toInt() and 0xFF) shl 8) or
70− (digest[3].toInt() and 0xFF)).and(0x7FFFFFFF)
71− // Offset by NOTIF_ID_PREFIX, staying within the positive Int range.
72− // Using modulo ensures the prefix is preserved without Int overflow.
73− return NOTIF_ID_PREFIX + (hash % (0x7FFFFFFF - NOTIF_ID_PREFIX))
74− }
75−
76− /** Respect the POST_NOTIFICATIONS runtime permission (Android 13+): if the user denied
77− * it, callers should skip posting instead of throwing. Foreground-service notifications
78− * are exempt, so the running indicator still shows during a run. */
79− private fun canPost(context: Context): Boolean =
80− Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
81− androidx.core.content.ContextCompat.checkSelfPermission(
82− context, android.Manifest.permission.POST_NOTIFICATIONS,
83− ) == android.content.pm.PackageManager.PERMISSION_GRANTED
84−
85− /** A PendingIntent that opens [sessionId] in the app when the notification body is tapped.
86− * [profileId] (the originating server) is embedded so a tap after the user has switched
87− * servers routes back to the server that ran the session, not whichever is active —
88− * mirroring the Reply and permission action intents. */
89− private fun openSessionIntent(
90− context: Context, sessionId: String, requestCode: Int, profileId: String?,
91− ): PendingIntent {
92− // Sanitize the session id before embedding it in the deep-link URI so characters like
93− // /, ?, # can't inject path segments or query parameters.
94− val safeId = notifIdRegex.replace(sessionId, "")
95− val openIntent = Intent(context, MainActivity::class.java).apply {
96− action = Intent.ACTION_VIEW
97− data = android.net.Uri.parse("opencode://session/$safeId")
98− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
99− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
100− }
101− return PendingIntent.getActivity(
102− context, requestCode, openIntent,
103− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
104− )
105− }
106−
107− // canPost() checks POST_NOTIFICATIONS before every notify(); lint can't follow the
108− // check through the helper, so suppress its MissingPermission flag on these posts.
109− @SuppressLint("MissingPermission")
110− fun postCompleted(context: Context, sessionId: String, title: String, profileId: String?) {
111− if (!canPost(context)) return
112− val notifId = notifId(NS_COMPLETED, sessionId)
113−
114− // Inline reply: a RemoteInput-backed action that broadcasts the typed follow-up to
115− // NotificationActionReceiver. The PendingIntent MUST be mutable so the system can
116− // fill in the RemoteInput results before delivering it. [profileId] is embedded so the
117− // receiver enqueues the reply against the server that ran the session, not whichever
118− // server is active when the user taps (mirrors postPermission).
119− val remoteInput = RemoteInput.Builder(NotificationActionReceiver.KEY_REPLY_TEXT)
120− .setLabel(context.getString(R.string.notif_reply_hint))
121− .build()
122− val replyIntent = Intent(context, NotificationActionReceiver::class.java).apply {
123− action = NotificationActionReceiver.ACTION_REPLY
124− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
125− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
126− }
127− val replyPending = PendingIntent.getBroadcast(
128− context, notifId, replyIntent,
129− PendingIntent.FLAG_UPDATE_CURRENT or mutableFlag(),
130− )
131− val replyAction = NotificationCompat.Action.Builder(
132− R.drawable.ic_action_reply,
133− context.getString(R.string.notif_action_reply),
134− replyPending,
135− ).addRemoteInput(remoteInput).setAllowGeneratedReplies(true).build()
136−
137− // "Mark read" action so the user can triage a completion without opening the session.
138− val markReadIntent = Intent(context, NotificationActionReceiver::class.java).apply {
139− action = NotificationActionReceiver.ACTION_MARK_READ
140− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
141− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
142− }
143− val markReadPending = PendingIntent.getBroadcast(
144− context, notifId + 100, markReadIntent,
145− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
146− )
147− val markReadAction = NotificationCompat.Action.Builder(
148− R.drawable.ic_action_check,
149− context.getString(R.string.notif_action_mark_read),
150− markReadPending,
151− ).build()
152−
153− val notification = NotificationCompat.Builder(context, NotificationChannels.COMPLETED)
154− .setSmallIcon(R.drawable.ic_stat_notify)
155− .setContentTitle(context.getString(R.string.notif_completed_title))
156− // No % escaping here: getString(id, arg) inserts the argument verbatim and
157− // never re-scans it for format specifiers, so escaping the title would show
158− // literal doubled percent signs (e.g. a "50% done" title as "50%% done").
159− .setContentText(context.getString(R.string.notif_completed_text, title))
160− .setAutoCancel(true)
161− .setOnlyAlertOnce(true)
162− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
163− .addAction(replyAction)
164− .addAction(markReadAction)
165− .setCategory(NotificationCompat.CATEGORY_MESSAGE)
166− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
167− // Group notifications from the same server so multiple completions collapse into
168− // a stackable group on Android 7+ instead of filling the shade with individual entries.
169− .setGroup(GROUP_COMPLETED)
170− .build()
171−
172− runCatching {
173− NotificationManagerCompat.from(context).notify(notifId, notification)
174− // Post a summary notification so the group has a single top-level entry in the shade.
175− postCompletedSummary(context)
176− }.onFailure { Log.w(TAG, "Failed to post completion notification", it) }
177− }
178−
179− /** Post (or update) a summary notification for the completed-sessions group so multiple
180− * completions collapse into one stackable entry instead of filling the shade. */
181− @SuppressLint("MissingPermission")
182− private fun postCompletedSummary(context: Context) {
183− // The summary needs a content intent so tapping it opens the app (and so
184− // setAutoCancel can fire on tap — without a PendingIntent the tap does nothing
185− // and the summary can only be dismissed by swiping). A plain open-app intent is
186− // right for a group summary: there's no single session to route to.
187− val openIntent = Intent(context, MainActivity::class.java).apply {
188− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
189− }
190− val contentIntent = PendingIntent.getActivity(
191− context, 0, openIntent,
192− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
193− )
194− val summary = NotificationCompat.Builder(context, NotificationChannels.COMPLETED)
195− .setSmallIcon(R.drawable.ic_stat_notify)
196− .setContentTitle(context.getString(R.string.notif_completed_title))
197− .setContentText(context.getString(R.string.app_name))
198− .setContentIntent(contentIntent)
199− .setAutoCancel(true)
200− .setCategory(NotificationCompat.CATEGORY_MESSAGE)
201− .setGroup(GROUP_COMPLETED)
202− .setGroupSummary(true)
203− .build()
204− runCatching {
205− NotificationManagerCompat.from(context).notify(SUMMARY_COMPLETED_ID, summary)
206− }.onFailure { Log.w(TAG, "Failed to post completion summary notification", it) }
207− }
208−
209− /** Post a heads-up notification for a permission request with Allow once / Always /
210− * Reject action buttons. [sessionTitle] labels the notification; [permission]'s title/
211− * pattern/type supplies the detail line. [profileId] is embedded in the action intents
212− * so the receiver routes the response back to the server that posted the request, not
213− * whichever server happens to be active when the user taps. */
214− @SuppressLint("MissingPermission")
215− fun postPermission(context: Context, permission: Permission, sessionTitle: String, profileId: String?) {
216− if (!canPost(context)) return
217− val sessionId = permission.sessionID.takeIf { it.isNotBlank() } ?: return
218− val notifId = notifId(NS_PERMISSION, sessionId)
219− val detail = permission.title?.takeIf { it.isNotBlank() }
220− ?: permission.patternText?.takeIf { it.isNotBlank() }
221− ?: permission.type?.takeIf { it.isNotBlank() }
222− ?: context.getString(R.string.notif_permission_fallback)
223−
224− val builder = NotificationCompat.Builder(context, NotificationChannels.PERMISSION)
225− .setSmallIcon(R.drawable.ic_stat_notify)
226− .setContentTitle(context.getString(R.string.notif_permission_title, sessionTitle))
227− .setContentText(detail)
228− .setStyle(NotificationCompat.BigTextStyle().bigText(detail))
229− .setAutoCancel(true)
230− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
231− .setPriority(NotificationCompat.PRIORITY_HIGH)
232− .setGroup(GROUP_PERMISSION)
233− .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
234− .setPublicVersion(
235− NotificationCompat.Builder(context, NotificationChannels.PERMISSION)
236− .setSmallIcon(R.drawable.ic_stat_notify)
237− .setContentTitle(context.getString(R.string.notif_permission_public))
238− .build(),
239− )
240−
241− // One action per response. Each PendingIntent needs a distinct request code or
242− // FLAG_UPDATE_CURRENT would collapse them into one (the last extras win).
243− listOf(
244− Triple(PermissionResponse.ONCE, R.string.notif_action_allow_once, R.drawable.ic_action_check),
245− Triple(PermissionResponse.ALWAYS, R.string.notif_action_always, R.drawable.ic_action_check),
246− Triple(PermissionResponse.REJECT, R.string.notif_action_reject, R.drawable.ic_action_block),
247− ).forEach { (response, labelRes, iconRes) ->
248− val intent = Intent(context, NotificationActionReceiver::class.java).apply {
249− action = NotificationActionReceiver.ACTION_PERMISSION
250− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
251− putExtra(NotificationActionReceiver.EXTRA_PERMISSION_ID, permission.id)
252− putExtra(NotificationActionReceiver.EXTRA_RESPONSE, response.wire)
253− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
254− }
255− val pending = PendingIntent.getBroadcast(
256− context, notifId + response.ordinal + 1, intent,
257− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
258− )
259− builder.addAction(iconRes, context.getString(labelRes), pending)
260− }
261−
262− runCatching { NotificationManagerCompat.from(context).notify(notifId, builder.build()) }
263− .onFailure { Log.w(TAG, "Failed to post permission notification", it) }
264− // Group permission notifications so a multi-session burst collapses into a stackable
265− // group instead of filling the shade — mirroring the completed-sessions grouping.
266− runCatching { postGroupSummary(context, NotificationChannels.PERMISSION, GROUP_PERMISSION, SUMMARY_PERMISSION_ID) }
267− .onFailure { Log.w(TAG, "Failed to post permission summary notification", it) }
268− }
269−
270− /** Post a notification when a permission prompt auto-rejected on timeout. A user who
271− * walked away from an in-app prompt returns to find the run stopped with no on-screen
272− * record of why; this leaves a persistent trace in the shade explaining the stop and
273− * offering to re-open the session. Uses the permission channel (heads-up) so it's seen. */
274− @SuppressLint("MissingPermission")
275− fun postPermissionAutoRejected(context: Context, sessionId: String, sessionTitle: String, profileId: String?) {
276− if (!canPost(context)) return
277− val notifId = notifId(NS_PERMISSION, sessionId) + 1 // distinct from the live prompt
278− val detail = context.getString(R.string.notif_permission_auto_rejected_text)
279− val builder = NotificationCompat.Builder(context, NotificationChannels.PERMISSION)
280− .setSmallIcon(R.drawable.ic_stat_notify)
281− .setContentTitle(context.getString(R.string.notif_permission_auto_rejected_title, sessionTitle))
282− .setContentText(detail)
283− .setStyle(NotificationCompat.BigTextStyle().bigText(detail))
284− .setAutoCancel(true)
285− .setOnlyAlertOnce(true)
286− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
287− .setCategory(NotificationCompat.CATEGORY_STATUS)
288− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
289− .setGroup(GROUP_PERMISSION)
290− .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
291− runCatching { NotificationManagerCompat.from(context).notify(notifId, builder.build()) }
292− .onFailure { Log.w(TAG, "Failed to post permission auto-reject notification", it) }
293− runCatching { postGroupSummary(context, NotificationChannels.PERMISSION, GROUP_PERMISSION, SUMMARY_PERMISSION_ID) }
294− .onFailure { Log.w(TAG, "Failed to post permission summary notification", it) }
295− }
296−
297− /** Post a notification when a background run fails. */
298− @SuppressLint("MissingPermission")
299− fun postError(context: Context, sessionId: String, title: String, profileId: String? = null) {
300− if (!canPost(context)) return
301− val notifId = notifId(NS_ERROR, sessionId)
302− val builder = NotificationCompat.Builder(context, NotificationChannels.ERROR)
303− .setSmallIcon(R.drawable.ic_stat_notify)
304− .setContentTitle(context.getString(R.string.notif_error_title))
305− .setContentText(context.getString(R.string.notif_error_text, title))
306− .setAutoCancel(true)
307− .setOnlyAlertOnce(true)
308− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
309− .setCategory(NotificationCompat.CATEGORY_ERROR)
310− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
311− // Group error notifications so a burst of failures collapses into a stackable group.
312− .setGroup(GROUP_ERROR)
313− .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
314− .setPublicVersion(
315− NotificationCompat.Builder(context, NotificationChannels.ERROR)
316− .setSmallIcon(R.drawable.ic_stat_notify)
317− .setContentTitle(context.getString(R.string.notif_error_public))
318− .build(),
319− )
320− // A "Retry last" action lets the user re-run the failed prompt straight from the shade
321− // without opening the app — a failed run is exactly when a one-tap retry is most useful.
322− val retryIntent = Intent(context, NotificationActionReceiver::class.java).apply {
323− action = NotificationActionReceiver.ACTION_RETRY_LAST
324− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
325− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
326− }
327− val retryPending = PendingIntent.getBroadcast(
328− context, notifId + 10, retryIntent,
329− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
330− )
331− builder.addAction(R.drawable.ic_action_refresh, context.getString(R.string.retry_last), retryPending)
332− val notification = builder.build()
333− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
334− .onFailure { Log.w(TAG, "Failed to post error notification", it) }
335− runCatching { postGroupSummary(context, NotificationChannels.ERROR, GROUP_ERROR, SUMMARY_ERROR_ID) }
336− .onFailure { Log.w(TAG, "Failed to post error summary notification", it) }
337− }
338−
339− /** Update the completion notification to show a brief "Sent" confirmation after a
340− * successful inline reply, replacing the completion notification's content. Auto-cancels
341− * on tap (via a [setContentIntent]) so it doesn't linger. */
342− @SuppressLint("MissingPermission")
343− fun postReplySent(context: Context, sessionId: String, profileId: String? = null) {
344− if (!canPost(context)) {
345− cancel(context, sessionId)
346− return
347− }
348− val notifId = notifId(NS_COMPLETED, sessionId)
349− val notification = NotificationCompat.Builder(context, NotificationChannels.COMPLETED)
350− .setSmallIcon(R.drawable.ic_stat_notify)
351− .setContentTitle(context.getString(R.string.notif_reply_sent))
352− // setAutoCancel(true) only fires when the user taps a contentIntent; without one
353− // the "Sent" notification lingers indefinitely (the prior behavior). Wire the
354− // open-session intent so a tap dismisses the notification and opens the session.
355− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
356− .setAutoCancel(true)
357− .setPriority(NotificationCompat.PRIORITY_LOW)
358− .setGroup(GROUP_COMPLETED)
359− .build()
360− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
361− .onFailure { Log.w(TAG, "Failed to post reply-sent notification", it) }
362− }
363−
364− /** An inline reply couldn't be durably enqueued (no resolvable profile, or the outbox write
365− * threw). Cancel the completion notification so SystemUI's RemoteInput field doesn't stay
366− * stuck in the "sending…" spinner — a stuck field can't be resubmitted — and post an error
367− * notification so the reply isn't silently lost and the user can reopen the session to retry. */
368− @SuppressLint("MissingPermission")
369− fun postReplyFailed(context: Context, sessionId: String, profileId: String? = null) {
370− NotificationManagerCompat.from(context).cancel(notifId(NS_COMPLETED, sessionId))
371− maybeCancelSummary(context, GROUP_COMPLETED, SUMMARY_COMPLETED_ID)
372− if (!canPost(context)) return
373− val notifId = notifId(NS_ERROR, sessionId)
374− val notification = NotificationCompat.Builder(context, NotificationChannels.ERROR)
375− .setSmallIcon(R.drawable.ic_stat_notify)
376− .setContentTitle(context.getString(R.string.notif_reply_failed_title))
377− .setContentText(context.getString(R.string.notif_reply_failed_text))
378− .setAutoCancel(true)
379− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
380− .setCategory(NotificationCompat.CATEGORY_ERROR)
381− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
382− .build()
383− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
384− .onFailure { Log.w(TAG, "Failed to post reply-failed notification", it) }
385− }
386−
387− /** A queued outbox message was permanently undeliverable (e.g. the target session was
388− * deleted server-side → 404). Distinct from [postError] (which is titled "Run failed"):
389− * no run failed — a queued reply couldn't be delivered. Uses a distinct title/body so the
390− * user understands the failure mode and recovery action (open the session and re-send). */
391− @SuppressLint("MissingPermission")
392− fun postOutboxDropped(context: Context, sessionId: String, sessionTitle: String, profileId: String? = null) {
393− if (!canPost(context)) return
394− val notifId = notifId(NS_ERROR, sessionId)
395− val notification = NotificationCompat.Builder(context, NotificationChannels.ERROR)
396− .setSmallIcon(R.drawable.ic_stat_notify)
397− .setContentTitle(context.getString(R.string.message_not_delivered))
398− .setContentText(context.getString(R.string.message_not_delivered_body, sessionTitle))
399− .setAutoCancel(true)
400− .setOnlyAlertOnce(true)
401− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
402− .setCategory(NotificationCompat.CATEGORY_ERROR)
403− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
404− .setGroup(GROUP_ERROR)
405− .build()
406− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
407− .onFailure { Log.w(TAG, "Failed to post outbox-dropped notification", it) }
408− runCatching { postGroupSummary(context, NotificationChannels.ERROR, GROUP_ERROR, SUMMARY_ERROR_ID) }
409− .onFailure { Log.w(TAG, "Failed to post error summary notification", it) }
410− }
411−
412− /** The SSE stream hit a non-retryable failure (Failed/AuthFailed) while the app was
413− * backgrounded during an active run, so the in-app banner isn't visible and the run is
414− * effectively stranded. Posts a low-priority notification so a backgrounded user is
415− * signaled that their run is stalled and can tap to reconnect. Distinct from [postError]
416− * (a run error) — this is a connection loss, not a run failure. */
417− @SuppressLint("MissingPermission")
418− fun postConnectionLost(context: Context, profileLabel: String, profileId: String?) {
419− if (!canPost(context)) return
420− val notifId = CONNECTION_LOST_ID
421− // Tap reopens the app at the server list so the user can reconnect / fix credentials.
422− val openIntent = Intent(context, MainActivity::class.java).apply {
423− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
424− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
425− }
426− val openPending = PendingIntent.getActivity(
427− context, notifId, openIntent,
428− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
429− )
430− val notification = NotificationCompat.Builder(context, NotificationChannels.ERROR)
431− .setSmallIcon(R.drawable.ic_stat_notify)
432− .setContentTitle(context.getString(R.string.connection_lost, profileLabel))
433− .setContentText(context.getString(R.string.connection_lost_tap))
434− .setAutoCancel(true)
435− .setOnlyAlertOnce(true)
436− .setContentIntent(openPending)
437− .setCategory(NotificationCompat.CATEGORY_STATUS)
438− .setPriority(NotificationCompat.PRIORITY_LOW)
439− .build()
440− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
441− .onFailure { Log.w(TAG, "Failed to post connection-lost notification", it) }
442− }
443−
444− /** Cancel a previously-posted [postConnectionLost] notification (e.g. on reconnect). */
445− fun cancelConnectionLost(context: Context) {
446− NotificationManagerCompat.from(context).cancel(CONNECTION_LOST_ID)
447− }
448−
449− /** FLAG_MUTABLE where required (Android 12+) so RemoteInput results can be injected. */
450− private fun mutableFlag(): Int =
451− if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
452−
453− /** Cancel a session's completion notification (e.g. when the user opens it). */
454− fun cancel(context: Context, sessionId: String) {
455− NotificationManagerCompat.from(context).cancel(notifId(NS_COMPLETED, sessionId))
456− maybeCancelSummary(context, GROUP_COMPLETED, SUMMARY_COMPLETED_ID)
457− }
458−
459− /**
460− * Reflect the total number of unread sessions as a launcher-icon badge. Android only badges
461− * the launcher icon via a notification on a badge-enabled channel, so this posts a silent,
462− * min-importance notification with [.setNumber] on the [NotificationChannels.UNREAD] channel
463− * when [totalUnread] > 0, and cancels it when it drops to 0. Skipped entirely without
464− * POST_NOTIFICATIONS permission (Android 13+) — the badge just won't show, no error.
465− */
466− @SuppressLint("MissingPermission")
467− fun updateUnreadBadge(context: Context, totalUnread: Int) {
468− val nm = NotificationManagerCompat.from(context)
469− if (totalUnread <= 0) {
470− nm.cancel(UNREAD_BADGE_ID)
471− return
472− }
473− if (!canPost(context)) return
474− val notification = NotificationCompat.Builder(context, NotificationChannels.UNREAD)
475− .setSmallIcon(R.drawable.ic_stat_notify)
476− .setContentTitle(context.getString(R.string.app_name))
477− .setContentText(context.resources.getQuantityString(R.plurals.unread_sessions, totalUnread, totalUnread))
478− .setNumber(totalUnread.coerceAtMost(999))
479− .setOnlyAlertOnce(true)
480− .setSilent(true)
481− .setShowWhen(false)
482− .setPriority(NotificationCompat.PRIORITY_MIN)
483− .build()
484− runCatching { nm.notify(UNREAD_BADGE_ID, notification) }
485− .onFailure { Log.w(TAG, "Failed to post unread badge notification", it) }
486− }
487−
488− /** Cancel a session's permission notification (on reply, or when the user opens it). Also
489− * cancels the auto-rejected-permission notification (posted under notifId + 1) so opening
490− * the session by any route other than tapping that notification clears it too — without
491− * this a stale "auto-rejected" heads-up lingers in the shade (setAutoCancel only dismisses
492− * on a direct tap). */
493− fun cancelPermission(context: Context, sessionId: String) {
494− val nm = NotificationManagerCompat.from(context)
495− val baseId = notifId(NS_PERMISSION, sessionId)
496− nm.cancel(baseId)
497− nm.cancel(baseId + 1) // postPermissionAutoRejected uses baseId + 1
498− maybeCancelSummary(context, GROUP_PERMISSION, SUMMARY_PERMISSION_ID)
499− }
500−
501− /** Cancel a session's error notification (e.g. when the user opens it). Without this a
502− * stale "run failed" notification lingers when the session is opened by any route other
503− * than tapping the notification itself (setAutoCancel only clears it on a direct tap). */
504− fun cancelError(context: Context, sessionId: String) {
505− NotificationManagerCompat.from(context).cancel(notifId(NS_ERROR, sessionId))
506− maybeCancelSummary(context, GROUP_ERROR, SUMMARY_ERROR_ID)
507− }
508−
509− /** Build the lock-screen (public) version of a notification: only a generic title, no
510− * detail line, so sensitive file paths / commands in the real content aren't revealed
511− * while the device is locked. */
512− /** When the last child of a group is dismissed, cancel its lingering summary so it
513− * doesn't sit empty in the shade. NotificationManagerCompat lacks getActiveNotifications,
514− * so reach for the platform NotificationManager. The children/summary are posted without
515− * a tag, so matching by [android.app.Notification.getGroup] (plus excluding the summary
516− * id) is the reliable way to tell if any child remains. */
517− private fun maybeCancelSummary(context: Context, group: String, summaryId: Int) {
518− val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
519− ?: return
520− val active = try {
521− nm.activeNotifications
522− } catch (e: Exception) {
523− Log.w(TAG, "Failed to query active notifications for summary cleanup", e)
524− return
525− }
526− val hasChild = active.any { it.id != summaryId && it.notification?.group == group }
527− if (!hasChild) {
528− runCatching { NotificationManagerCompat.from(context).cancel(summaryId) }
529− .onFailure { Log.w(TAG, "Failed to cancel empty group summary", it) }
530− }
531− }
532−
533− private const val GROUP_COMPLETED = "soy.iko.opencode.COMPLETED"
534− private const val GROUP_PERMISSION = "soy.iko.opencode.PERMISSION"
535− private const val GROUP_ERROR = "soy.iko.opencode.ERROR"
536− private const val SUMMARY_COMPLETED_ID = -1
537− private const val SUMMARY_PERMISSION_ID = -2
538− private const val SUMMARY_ERROR_ID = -3
539−
540− /** Post a summary notification for a group so multiple entries collapse into one stackable
541− * entry in the shade instead of filling it. */
542− @SuppressLint("MissingPermission")
543− private fun postGroupSummary(context: Context, channelId: String, group: String, summaryId: Int) {
544− if (!canPost(context)) return
545− val summary = NotificationCompat.Builder(context, channelId)
546− .setSmallIcon(R.drawable.ic_stat_notify)
547− .setContentTitle(context.getString(R.string.app_name))
548− .setAutoCancel(true)
549− .setGroup(group)
550− .setGroupSummary(true)
551− .build()
552− runCatching {
553− NotificationManagerCompat.from(context).notify(summaryId, summary)
554− }.onFailure { Log.w(TAG, "Failed to post group summary notification", it) }
555− }
556−}
app/src/main/java/soy/iko/opencode/platform/AppShortcuts.ktdeleted−58
@@ -1,58 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.content.Context
4−import android.content.Intent
5−import android.net.Uri
6−import androidx.core.content.pm.ShortcutInfoCompat
7−import androidx.core.content.pm.ShortcutManagerCompat
8−import androidx.core.graphics.drawable.IconCompat
9−import soy.iko.opencode.MainActivity
10−import soy.iko.opencode.R
11−import soy.iko.opencode.data.repo.RecentSession
12−
13−/**
14− * Maintains the app's dynamic launcher shortcuts (long-press the icon): "New session" and
15− * "Resume last". Rebuilt whenever the recent-session list changes so "Resume last" points at
16− * the most recent conversation via the existing `opencode://session/{id}` deep link.
17− */
18−object AppShortcuts {
19−
20− private const val ID_NEW = "new_session"
21− private const val ID_RESUME = "resume_last"
22− private val idRegex = Regex("[^A-Za-z0-9_-]")
23−
24− fun update(context: Context, lastSession: RecentSession?) {
25− val ctx = context.applicationContext
26− val shortcuts = mutableListOf<ShortcutInfoCompat>()
27−
28− shortcuts += ShortcutInfoCompat.Builder(ctx, ID_NEW)
29− .setShortLabel(ctx.getString(R.string.shortcut_new_short))
30− .setLongLabel(ctx.getString(R.string.shortcut_new_long))
31− .setIcon(IconCompat.createWithResource(ctx, R.drawable.ic_launcher_foreground))
32− .setIntent(
33− Intent(ctx, MainActivity::class.java).apply { action = MainActivity.ACTION_NEW_SESSION },
34− )
35− .build()
36−
37− if (lastSession != null) {
38− val safeId = idRegex.replace(lastSession.id, "")
39− if (safeId.isNotEmpty()) {
40− shortcuts += ShortcutInfoCompat.Builder(ctx, ID_RESUME)
41− .setShortLabel(ctx.getString(R.string.shortcut_resume_short))
42− .setLongLabel(
43− lastSession.title.ifBlank { ctx.getString(R.string.shortcut_resume_long) }.take(40),
44− )
45− .setIcon(IconCompat.createWithResource(ctx, R.drawable.ic_launcher_foreground))
46− .setIntent(
47− Intent(ctx, MainActivity::class.java).apply {
48− action = Intent.ACTION_VIEW
49− data = Uri.parse("opencode://session/$safeId")
50− },
51− )
52− .build()
53− }
54− }
55−
56− runCatching { ShortcutManagerCompat.setDynamicShortcuts(ctx, shortcuts) }
57− }
58−}
app/src/main/java/soy/iko/opencode/platform/NewSessionTileService.ktdeleted−33
@@ -1,33 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.app.PendingIntent
4−import android.content.Intent
5−import android.os.Build
6−import android.service.quicksettings.TileService
7−import soy.iko.opencode.MainActivity
8−
9−/**
10− * Quick-settings tile that starts a new opencode session. Tapping launches [MainActivity]
11− * with [MainActivity.ACTION_NEW_SESSION]; the app creates and opens a fresh session once
12− * connected. On Android 14+ [startActivityAndCollapse] requires a PendingIntent.
13− */
14−class NewSessionTileService : TileService() {
15−
16− override fun onClick() {
17− super.onClick()
18− val intent = Intent(this, MainActivity::class.java).apply {
19− action = MainActivity.ACTION_NEW_SESSION
20− addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
21− }
22− if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
23− val pending = PendingIntent.getActivity(
24− this, 0, intent,
25− PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
26− )
27− startActivityAndCollapse(pending)
28− } else {
29− @Suppress("DEPRECATION", "StartActivityAndCollapseDeprecated")
30− startActivityAndCollapse(intent)
31− }
32− }
33−}
app/src/main/java/soy/iko/opencode/platform/SessionsWidgetProvider.ktdeleted−83
@@ -1,83 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.app.PendingIntent
4−import android.appwidget.AppWidgetManager
5−import android.appwidget.AppWidgetProvider
6−import android.content.ComponentName
7−import android.content.Context
8−import android.content.Intent
9−import android.net.Uri
10−import android.os.Build
11−import android.widget.RemoteViews
12−import soy.iko.opencode.MainActivity
13−import soy.iko.opencode.R
14−
15−/**
16− * Home-screen widget listing recent opencode sessions (fed by
17− * [soy.iko.opencode.data.repo.RecentSessionsStore]) with a "New session" action. Each row deep-links
18− * into its session; the header opens the app. The list is backed by [SessionsWidgetService].
19− */
20−class SessionsWidgetProvider : AppWidgetProvider() {
21−
22− override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
23− for (id in appWidgetIds) render(context, appWidgetManager, id)
24− }
25−
26− companion object {
27− /** Re-render all widgets and tell them to reload their list data (call after the
28− * recent-session list changes). No-op when no widget is placed. */
29− fun refresh(context: Context) {
30− val manager = AppWidgetManager.getInstance(context) ?: return
31− val ids = runCatching {
32− manager.getAppWidgetIds(ComponentName(context, SessionsWidgetProvider::class.java))
33− }.getOrNull() ?: return
34− if (ids.isEmpty()) return
35− for (id in ids) render(context, manager, id)
36− manager.notifyAppWidgetViewDataChanged(ids, R.id.widget_list)
37− }
38−
39− private fun render(context: Context, manager: AppWidgetManager, widgetId: Int) {
40− val views = RemoteViews(context.packageName, R.layout.widget_sessions)
41−
42− // Header: title opens the app; the "+" starts a new session.
43− views.setOnClickPendingIntent(
44− R.id.widget_title,
45− activityPending(context, requestCode = 2, Intent(context, MainActivity::class.java)),
46− )
47− views.setOnClickPendingIntent(
48− R.id.widget_new,
49− activityPending(
50− context, requestCode = 1,
51− Intent(context, MainActivity::class.java).apply { action = MainActivity.ACTION_NEW_SESSION },
52− ),
53− )
54−
55− // Bind the list to the RemoteViewsService. A unique data Uri per widget id keeps
56− // the framework from reusing one adapter across widgets.
57− val serviceIntent = Intent(context, SessionsWidgetService::class.java).apply {
58− putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
59− data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))
60− }
61− views.setRemoteAdapter(R.id.widget_list, serviceIntent)
62− views.setEmptyView(R.id.widget_list, R.id.widget_empty)
63−
64− // Template intent filled in per row (fill-in carries EXTRA_SESSION_ID). Must be
65− // mutable on Android 12+ so the row's fill-in can be merged.
66− val templateIntent = Intent(context, MainActivity::class.java).apply { action = Intent.ACTION_VIEW }
67− val mutableFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
68− val templatePending = PendingIntent.getActivity(
69− context, 3, templateIntent, PendingIntent.FLAG_UPDATE_CURRENT or mutableFlag,
70− )
71− views.setPendingIntentTemplate(R.id.widget_list, templatePending)
72−
73− manager.updateAppWidget(widgetId, views)
74− manager.notifyAppWidgetViewDataChanged(widgetId, R.id.widget_list)
75− }
76−
77− private fun activityPending(context: Context, requestCode: Int, intent: Intent): PendingIntent =
78− PendingIntent.getActivity(
79− context, requestCode, intent,
80− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
81− )
82− }
83−}
app/src/main/java/soy/iko/opencode/platform/SessionsWidgetService.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.content.Context
4−import android.content.Intent
5−import android.widget.RemoteViews
6−import android.widget.RemoteViewsService
7−import soy.iko.opencode.MainActivity
8−import soy.iko.opencode.R
9−import soy.iko.opencode.data.repo.RecentSession
10−import soy.iko.opencode.data.repo.RecentSessionsStore
11−import java.security.MessageDigest
12−
13−/** Serves the list rows for [SessionsWidgetProvider] from [RecentSessionsStore]. */
14−class SessionsWidgetService : RemoteViewsService() {
15− override fun onGetViewFactory(intent: Intent): RemoteViewsFactory =
16− SessionsWidgetFactory(applicationContext)
17−}
18−
19−private class SessionsWidgetFactory(private val context: Context) : RemoteViewsService.RemoteViewsFactory {
20−
21− private var items: List<RecentSession> = emptyList()
22−
23− override fun onCreate() { items = RecentSessionsStore.read(context) }
24−
25− // Re-read from disk whenever the app signals the data changed (notifyAppWidgetViewDataChanged).
26− override fun onDataSetChanged() { items = RecentSessionsStore.read(context) }
27−
28− override fun onDestroy() { items = emptyList() }
29−
30− override fun getCount(): Int = items.size
31−
32− override fun getViewAt(position: Int): RemoteViews {
33− val row = RemoteViews(context.packageName, R.layout.widget_session_item)
34− val session = items.getOrNull(position) ?: return row
35− row.setTextViewText(R.id.widget_item_title, session.title.ifBlank { context.getString(R.string.session) })
36− // Fill-in intent merged into the list's template: carries the session id the app opens.
37− row.setOnClickFillInIntent(
38− R.id.widget_item_root,
39− Intent().putExtra(MainActivity.EXTRA_SESSION_ID, session.id),
40− )
41− return row
42− }
43−
44− override fun getLoadingView(): RemoteViews? = null
45− override fun getViewTypeCount(): Int = 1
46− // Derive a stable id from the session id via a collision-resistant SHA-256 digest
47− // (truncated to 63 bits) rather than String.hashCode(), whose 32-bit output can
48− // collide for distinct session ids — with hasStableIds=true the RemoteViews framework
49− // would then mis-recycle two sessions' row content. Mirrors SessionNotifications.notifId.
50− // Falls back to the position for an out-of-range index.
51− override fun getItemId(position: Int): Long {
52− val id = items.getOrNull(position)?.id ?: return position.toLong()
53− val digest = runCatching { MessageDigest.getInstance("SHA-256").digest(id.toByteArray()) }
54− .getOrNull() ?: return position.toLong()
55− // Take the first 8 bytes, mask to 63 bits (always positive) to fit a Long id.
56− // The shl/or/and infix precedence requires parenthesizing each shift individually
57− // (see SessionNotifications.notifId for the rationale).
58− return (((digest[0].toLong() and 0xFF) shl 56) or
59− ((digest[1].toLong() and 0xFF) shl 48) or
60− ((digest[2].toLong() and 0xFF) shl 40) or
61− ((digest[3].toLong() and 0xFF) shl 32) or
62− ((digest[4].toLong() and 0xFF) shl 24) or
63− ((digest[5].toLong() and 0xFF) shl 16) or
64− ((digest[6].toLong() and 0xFF) shl 8) or
65− (digest[7].toLong() and 0xFF)).and(0x7FFFFFFFFFFFFFFF)
66− }
67− override fun hasStableIds(): Boolean = true
68−}
app/src/main/java/soy/iko/opencode/ui/AppLockGate.ktdeleted−310
@@ -1,310 +0,0 @@
1−package soy.iko.opencode.ui
2−
3−import android.content.Context
4−import android.content.ContextWrapper
5−import android.os.Build
6−import androidx.biometric.BiometricManager
7−import androidx.biometric.BiometricPrompt
8−import androidx.compose.foundation.clickable
9−import androidx.compose.foundation.layout.Arrangement
10−import androidx.compose.foundation.layout.Column
11−import androidx.compose.foundation.layout.Spacer
12−import androidx.compose.foundation.layout.fillMaxSize
13−import androidx.compose.foundation.layout.padding
14−import androidx.compose.foundation.layout.size
15−import androidx.compose.material.icons.Icons
16−import androidx.compose.material.icons.filled.Fingerprint
17−import androidx.compose.material.icons.filled.Lock
18−import androidx.compose.material3.Button
19−import androidx.compose.material3.Icon
20−import androidx.compose.material3.MaterialTheme
21−import androidx.compose.material3.Surface
22−import androidx.compose.material3.Text
23−import androidx.compose.runtime.Composable
24−import androidx.compose.runtime.DisposableEffect
25−import androidx.compose.runtime.LaunchedEffect
26−import androidx.compose.runtime.getValue
27−import androidx.compose.runtime.mutableStateOf
28−import androidx.compose.runtime.remember
29−import androidx.compose.runtime.saveable.rememberSaveable
30−import androidx.compose.runtime.saveable.rememberSaveableStateHolder
31−import androidx.compose.runtime.setValue
32−import androidx.compose.ui.Alignment
33−import androidx.compose.ui.Modifier
34−import androidx.compose.ui.platform.LocalContext
35−import androidx.compose.ui.res.stringResource
36−import androidx.compose.ui.semantics.LiveRegionMode
37−import androidx.compose.ui.semantics.Role
38−import androidx.compose.ui.semantics.liveRegion
39−import androidx.compose.ui.semantics.semantics
40−import androidx.compose.ui.unit.dp
41−import androidx.core.content.ContextCompat
42−import androidx.fragment.app.FragmentActivity
43−import androidx.lifecycle.Lifecycle
44−import androidx.lifecycle.LifecycleEventObserver
45−import androidx.lifecycle.compose.LocalLifecycleOwner
46−import soy.iko.opencode.R
47−import soy.iko.opencode.ui.components.LoadingSize
48−import soy.iko.opencode.ui.components.LoadingSpinner
49−
50−/**
51− * The set of authenticators the app lock accepts. Device credential (PIN/pattern/password)
52− * can only be combined with a biometric class from Android 11 (API 30) on; on 26–29 we ask
53− * for a strong biometric alone, so the lock is only offered (in Settings) when one is enrolled.
54− */
55−private val lockAuthenticators: Int
56− get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
57− BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL
58− } else {
59− BiometricManager.Authenticators.BIOMETRIC_STRONG
60− }
61−
62−/** Whether device authentication is currently possible, so Settings can gate the toggle. */
63−fun canAuthenticateForAppLock(context: Context): Boolean =
64− BiometricManager.from(context).canAuthenticate(lockAuthenticators) == BiometricManager.BIOMETRIC_SUCCESS
65−
66−/**
67− * Whether app-lock auth is *permanently* impossible on this device (no hardware, nothing
68− * enrolled, or a pending security update). Only these states may fail the gate open. A transient
69− * error (sensor busy / temporarily unavailable) must NOT fail open — that would unlock the app on
70− * a momentary glitch — so the gate stays locked and lets the user retry.
71− */
72−private fun appLockPermanentlyUnavailable(context: Context): Boolean =
73− when (BiometricManager.from(context).canAuthenticate(lockAuthenticators)) {
74− BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED,
75− BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,
76− BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> true
77− else -> false
78− }
79−
80−/** Unwrap a [FragmentActivity] from a (possibly wrapped) Compose [Context]. */
81−private fun Context.findFragmentActivity(): FragmentActivity? {
82− var ctx: Context? = this
83− while (ctx is ContextWrapper) {
84− if (ctx is FragmentActivity) return ctx
85− ctx = ctx.baseContext
86− }
87− return null
88−}
89−
90−/**
91− * Gates [content] behind device authentication when [enabled]. The content stays composed
92− * underneath an opaque lock overlay (so navigation state survives a re-lock), and the app
93− * re-locks whenever it's sent to the background. If no [FragmentActivity] is available or the
94− * device can't authenticate, the gate is a no-op — the setting is only offered when
95− * [canAuthenticateForAppLock] is true, so this fallback just prevents a hard lock-out.
96− */
97−@Composable
98−fun AppLockGate(enabled: Boolean, reLockDelaySeconds: Int = 0, content: @Composable () -> Unit) {
99− if (!enabled) {
100− content()
101− return
102− }
103− val context = LocalContext.current
104− val activity = remember(context) { context.findFragmentActivity() }
105− if (activity == null) {
106− content()
107− return
108− }
109− // Fail open only if device authentication is *permanently* impossible (e.g. the user enabled
110− // app-lock while a credential was enrolled and later removed their PIN/biometric): authenticate()
111− // would otherwise always hit onAuthenticationError and strand the user on a permanent lockout.
112− // A transient authenticator error keeps the lock up (the user retries) rather than unlocking.
113− if (appLockPermanentlyUnavailable(context)) {
114− // Surface a one-time warning so the user knows their app-lock setting is on but isn't
115− // actually protecting the app — without this they'd have to discover it by opening
116− // Settings and seeing the "unavailable" state. A Toast (not a snackbar) because the
117− // gate sits above the Scaffold/SnackbarHost; the warning is informational, not an action.
118− LaunchedEffect(Unit) {
119− android.widget.Toast.makeText(
120− context,
121− context.getString(R.string.app_lock_disabled_warning),
122− android.widget.Toast.LENGTH_LONG,
123− ).show()
124− }
125− content()
126− return
127− }
128−
129− // Deliberately NOT rememberSaveable: the unlocked flag must never be persisted into the
130− // saved-instance-state Bundle. On API 26-27 onSaveInstanceState runs *before* onStop, so a
131− // saveable `true` would be written to the Bundle before ON_STOP resets it; after a background
132− // process-kill and restore the app would come back unlocked with no biometric prompt — an
133− // app-lock bypass. Rotation is handled by the activity's configChanges (no recreation), so a
134− // plain remember still avoids re-prompting on rotation while re-locking on real recreation.
135− var unlocked by remember { mutableStateOf(false) }
136− // Wall-clock time of the most recent ON_STOP. Used with [reLockDelaySeconds] so a quick
137− // app-switch (e.g. glancing at another app for a few seconds) doesn't re-prompt — the most
138− // common reason users disable biometric locks. A killed process resets unlocked anyway, so the
139− // grace period only governs the in-memory re-lock decision across a surviving background stint.
140− //
141− // rememberSaveable (not plain remember): a config change NOT in the manifest's configChanges
142− // (e.g. a locale change, which recreates the Activity) would otherwise reset this to 0L, and
143− // the new DisposableEffect observer gets ON_START delivered synchronously — the grace check
144− // sees lastStopTimeMs == 0 and re-locks even though the user unlocked 2s ago and only changed
145− // the system language. The stop timestamp is not security-sensitive (it's a wall-clock value),
146− // so persisting it through the Bundle is safe and preserves the grace period across recreation.
147− val lastStopTimeMs = rememberSaveable { longArrayOf(0L) }
148− val reLockDelayMs = reLockDelaySeconds * 1000L
149−
150− val title = stringResource(R.string.app_lock_prompt_title)
151− val subtitle = stringResource(R.string.app_lock_prompt_subtitle)
152−
153− // Track an in-flight prompt so a recomposition (or the retry button) can't stack two
154− // BiometricPrompts, which throws.
155− var authInFlight by remember { mutableStateOf(false) }
156− // Monotonic id for the current prompt. The system dismisses an in-flight BiometricPrompt when
157− // the app backgrounds and posts its onAuthenticationError asynchronously; without this, that
158− // stale error could land after ON_START already started a NEW prompt and clear authInFlight
159− // mid-prompt — letting a recomposition or the "Unlock" button (enabled = !authInFlight) stack
160− // a second prompt. Each prompt captures its id and only mutates state while it's still current.
161− val promptId = remember { intArrayOf(0) }
162−
163− fun authenticate() {
164− if (authInFlight || unlocked) return
165− authInFlight = true
166− val myPrompt = ++promptId[0]
167− val executor = ContextCompat.getMainExecutor(activity)
168− val callback = object : BiometricPrompt.AuthenticationCallback() {
169− override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
170− if (myPrompt != promptId[0]) return
171− authInFlight = false
172− unlocked = true
173− }
174−
175− override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
176− // User cancelled / lockout / hardware error: stay locked and let them retry
177− // via the button rather than looping the system prompt. Ignore a stale error
178− // from a prompt already superseded by a newer one (see promptId above).
179− if (myPrompt != promptId[0]) return
180− authInFlight = false
181− }
182−
183− override fun onAuthenticationFailed() {
184− // A single non-matching attempt; the system UI lets the user try again.
185− }
186− }
187− val info = BiometricPrompt.PromptInfo.Builder()
188− .setTitle(title)
189− .setSubtitle(subtitle)
190− .setAllowedAuthenticators(lockAuthenticators)
191− .build()
192− runCatching { BiometricPrompt(activity, executor, callback).authenticate(info) }
193− .onFailure { if (myPrompt == promptId[0]) authInFlight = false }
194− }
195−
196− // Re-lock when the app is backgrounded, and re-prompt when it returns to the foreground.
197− // The re-prompt fires on ON_START rather than by keying an effect on `unlocked`: ON_STOP
198− // already cleared `unlocked` while backgrounded, so an effect keyed on it would see no
199− // change on return and never re-fire, stranding the user on the manual "Unlock" button.
200− // addObserver also delivers the current state's ON_START to a freshly-added observer, so
201− // this covers the initial prompt on first show too; the authInFlight/unlocked guards in
202− // authenticate() make the overlapping triggers safe.
203− val lifecycleOwner = LocalLifecycleOwner.current
204− DisposableEffect(lifecycleOwner) {
205− val observer = LifecycleEventObserver { _, event ->
206− when (event) {
207− Lifecycle.Event.ON_STOP -> {
208− // Record the stop time but DON'T clear unlocked yet — the re-lock decision is
209− // made on the next ON_START, so a brief background stint under the grace period
210− // returns the user straight to their session without a re-prompt. authInFlight
211− // is still cleared because the system dismisses an in-flight prompt on background.
212− lastStopTimeMs[0] = System.currentTimeMillis()
213− authInFlight = false
214− }
215− Lifecycle.Event.ON_START -> {
216− // Only re-lock (and re-prompt) if more than the grace period elapsed since the
217− // last ON_STOP, or the app is freshly starting (lastStopTimeMs == 0).
218− val elapsed = System.currentTimeMillis() - lastStopTimeMs[0]
219− if (unlocked && lastStopTimeMs[0] != 0L && elapsed < reLockDelayMs) {
220− // Within the grace period — stay unlocked, no re-prompt.
221− } else {
222− unlocked = false
223− authenticate()
224− }
225− }
226− else -> {}
227− }
228− }
229− lifecycleOwner.lifecycle.addObserver(observer)
230− onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
231− }
232−
233− // Compose content ONLY while unlocked. Drawing the lock as an overlay *over* a still-composed
234− // content() cannot cover a Dialog / ModalBottomSheet / DropdownMenu / Popup: those render in
235− // separate windows z-ordered above the Activity content, so an open permission dialog or picker
236− // sheet would stay visible and interactive above the lock — an authentication bypass. Not
237− // composing content while locked removes those sub-windows entirely. The SaveableStateHolder
238− // preserves navigation/scroll/input state across the re-lock so unlocking returns the user where
239− // they were, replacing the previous "keep composed underneath" approach.
240− val stateHolder = rememberSaveableStateHolder()
241− if (unlocked) {
242− stateHolder.SaveableStateProvider(APP_LOCK_CONTENT_KEY) { content() }
243− } else {
244− // A Fingerprint glyph hints at the primary unlock method when a biometric is enrolled;
245− // fall back to the generic lock on credential-only setups. Computed once: enrollment
246− // doesn't change while the gate is shown, and re-prompting on each frame is wasteful.
247− val biometricAvailable = remember(context) {
248− BiometricManager.from(context)
249− .canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) ==
250− BiometricManager.BIOMETRIC_SUCCESS
251− }
252− val unlockLabel = stringResource(R.string.app_unlock)
253− Surface(
254− modifier = Modifier.fillMaxSize(),
255− color = MaterialTheme.colorScheme.background,
256− ) {
257− // The whole surface is tappable to re-trigger the prompt (in addition to the button),
258− // so a user who dismissed the system prompt can retry by tapping anywhere — not just
259− // by finding the Unlock button.
260− Column(
261− modifier = Modifier
262− .fillMaxSize()
263− .clickable(
264− enabled = !authInFlight,
265− role = Role.Button,
266− onClickLabel = unlockLabel,
267− ) { authenticate() }
268− .padding(32.dp),
269− horizontalAlignment = Alignment.CenterHorizontally,
270− verticalArrangement = Arrangement.Center,
271− ) {
272− Icon(
273− if (biometricAvailable) Icons.Filled.Fingerprint else Icons.Filled.Lock,
274− contentDescription = null,
275− modifier = Modifier.size(56.dp),
276− tint = MaterialTheme.colorScheme.primary,
277− )
278− Text(
279− stringResource(R.string.app_locked),
280− style = MaterialTheme.typography.titleMedium,
281− modifier = Modifier
282− .padding(top = 16.dp)
283− .semantics { liveRegion = LiveRegionMode.Polite },
284− )
285− Text(
286− stringResource(R.string.app_locked_hint),
287− style = MaterialTheme.typography.bodyMedium,
288− color = MaterialTheme.colorScheme.onSurfaceVariant,
289− modifier = Modifier.padding(top = 4.dp),
290− )
291− Button(
292− onClick = { authenticate() },
293− enabled = !authInFlight,
294− modifier = Modifier.padding(top = 24.dp),
295− ) {
296− if (authInFlight) {
297− LoadingSpinner(
298− size = LoadingSize.Small,
299− color = MaterialTheme.colorScheme.primary,
300− )
301− Spacer(Modifier.size(8.dp))
302− }
303− Text(unlockLabel)
304− }
305− }
306− }
307− }
308−}
309−
310−private const val APP_LOCK_CONTENT_KEY = "app_lock_content"
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+90−583
@@ -1,617 +1,124 @@
1package soy.iko.opencode.ui
1package soy.iko.opencode.ui
2
2
3−import androidx.compose.animation.EnterTransition
3+import androidx.activity.compose.BackHandler
4−import androidx.compose.animation.ExitTransition
5−import androidx.compose.animation.core.tween
4+import androidx.compose.animation.AnimatedContent
6−import androidx.compose.animation.fadeIn
7−import androidx.compose.animation.fadeOut
8import androidx.compose.animation.slideInHorizontally
5import androidx.compose.animation.slideInHorizontally
9import androidx.compose.animation.slideOutHorizontally
6import androidx.compose.animation.slideOutHorizontally
10−import androidx.compose.foundation.layout.Box
7+import androidx.compose.animation.togetherWith
11−import androidx.compose.foundation.layout.BoxWithConstraints
12−import androidx.compose.foundation.layout.Row
13−import androidx.compose.foundation.layout.fillMaxHeight
14import androidx.compose.foundation.layout.fillMaxSize
8import androidx.compose.foundation.layout.fillMaxSize
9+import androidx.compose.foundation.layout.padding
10+import androidx.compose.material3.AlertDialog
11+import androidx.compose.material3.Scaffold
12+import androidx.compose.material3.SnackbarDuration
13+import androidx.compose.material3.SnackbarHost
14+import androidx.compose.material3.SnackbarHostState
15+import androidx.compose.material3.Text
16+import androidx.compose.material3.TextButton
15import androidx.compose.runtime.Composable
17import androidx.compose.runtime.Composable
16−import androidx.compose.runtime.CompositionLocalProvider
17import androidx.compose.runtime.LaunchedEffect
18import androidx.compose.runtime.LaunchedEffect
18import androidx.compose.runtime.getValue
19import androidx.compose.runtime.getValue
19import androidx.compose.runtime.mutableStateOf
20import androidx.compose.runtime.mutableStateOf
20import androidx.compose.runtime.remember
21import androidx.compose.runtime.remember
21−import androidx.compose.runtime.rememberCoroutineScope
22−import androidx.compose.runtime.saveable.rememberSaveable
23import androidx.compose.runtime.setValue
22import androidx.compose.runtime.setValue
24import androidx.compose.ui.Modifier
23import androidx.compose.ui.Modifier
25−import androidx.compose.ui.input.key.Key
24+import soy.iko.opencode.core.Event
26−import androidx.compose.ui.input.key.KeyEventType
27−import androidx.compose.ui.input.key.isCtrlPressed
28−import androidx.compose.ui.input.key.isAltPressed
29−import androidx.compose.ui.input.key.key
30−import androidx.compose.ui.input.key.onPreviewKeyEvent
31−import androidx.compose.ui.input.key.type
32−import androidx.compose.ui.platform.LocalContext
33−import androidx.compose.ui.platform.LocalDensity
34−import androidx.compose.ui.unit.dp
35−import androidx.compose.ui.unit.LayoutDirection
36−import androidx.compose.ui.platform.LocalLayoutDirection
37−import androidx.navigation.NavType
38−import androidx.navigation.NavGraph.Companion.findStartDestination
39−import androidx.navigation.compose.NavHost
40−import androidx.navigation.compose.composable
41−import androidx.navigation.compose.currentBackStackEntryAsState
42−import androidx.navigation.compose.rememberNavController
43−import androidx.navigation.navArgument
44−import androidx.lifecycle.compose.collectAsStateWithLifecycle
45−import kotlinx.coroutines.launch
46−import soy.iko.opencode.di.AppContainer
25+import soy.iko.opencode.core.Screen
47−import soy.iko.opencode.data.network.NetworkConfig
26+import soy.iko.opencode.core.UiState
48−import soy.iko.opencode.ui.chat.ChatScreen
27+import soy.iko.opencode.ui.screens.ChatScreen
49−import soy.iko.opencode.ui.file.FileBrowserScreen
28+import soy.iko.opencode.ui.screens.ConnectScreen
50−import soy.iko.opencode.ui.file.FileViewScreen
51−import soy.iko.opencode.ui.file.TwoPaneFileBrowser
52−import soy.iko.opencode.ui.server.ServerEditScreen
53−import soy.iko.opencode.ui.server.ServerListScreen
54−import soy.iko.opencode.ui.search.GlobalSearchScreen
55−import androidx.compose.ui.platform.LocalHapticFeedback
56−import soy.iko.opencode.ui.components.LargeScreenNavRail
57−import soy.iko.opencode.ui.components.CompactNavBar
29+import soy.iko.opencode.ui.screens.SessionsScreen
58−import soy.iko.opencode.ui.components.LocalChatTextScale
59−import soy.iko.opencode.ui.components.LocalCodeWrap
60−import soy.iko.opencode.ui.components.LocalReducedMotion
61−import soy.iko.opencode.ui.components.isReducedMotion
62−import soy.iko.opencode.ui.components.rememberGatedHaptics
63−import soy.iko.opencode.ui.session.SessionListScreen
64−import soy.iko.opencode.ui.session.TwoPaneSessionChat
65−import soy.iko.opencode.ui.settings.DiagnosticsScreen
66−import soy.iko.opencode.ui.settings.SettingsScreen
67−import soy.iko.opencode.ui.usage.UsageScreen
68−import soy.iko.opencode.ui.mcp.McpScreen
69−import soy.iko.opencode.util.findActivity
70−import soy.iko.opencode.util.runCatchingCancellable
71
30
72@Composable
31@Composable
73−fun OpencodeApp(container: AppContainer) {
32+fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
74− val navController = rememberNavController()
33+ val snackbar = remember { SnackbarHostState() }
75− val scope = rememberCoroutineScope()
34+ var showStopConfirm by remember { mutableStateOf(false) }
76− val pendingShare by container.pendingShare.collectAsStateWithLifecycle()
35+ var showDisconnectConfirm by remember { mutableStateOf(false) }
77− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
36+
78− val pendingOpenSession by container.pendingOpenSession.collectAsStateWithLifecycle()
37+ LaunchedEffect(state.error) {
79− val pendingNewSession by container.pendingNewSession.collectAsStateWithLifecycle()
38+ state.error?.let {
80− val pendingOpenFile by container.pendingOpenFile.collectAsStateWithLifecycle()
39+ snackbar.showSnackbar(
81− val pendingDiagnostics by container.pendingDiagnostics.collectAsStateWithLifecycle()
40+ message = it,
82− val connection by container.activeConnection.collectAsStateWithLifecycle()
41+ actionLabel = "Dismiss",
83− // Chat presentation preferences, provided to the whole nav graph so the markdown/code
42+ duration = SnackbarDuration.Short,
84− // renderers honor the user's text-size and code-wrap choices everywhere.
43+ )
85− val chatTextScale by container.settingsStore.chatTextScale.collectAsStateWithLifecycle(initialValue = 1f)
44+ // Always clear the error from state after showing.
86− val codeWrap by container.settingsStore.codeWrap.collectAsStateWithLifecycle(initialValue = false)
45+ dispatch(Event.DismissError)
87− // Haptics gating: collected once at the root so the in-app toggle can disable all
88− // performHapticFeedback calls everywhere via a single CompositionLocalProvider, instead
89− // of each call site needing to read the setting. Defaults true (the prior behavior) so
90− // the brief window before DataStore loads still haptics as before.
91− val hapticsEnabled by container.settingsStore.hapticsEnabled.collectAsStateWithLifecycle(initialValue = true)
92−
93− // The foreground service that holds priority while any run is active is driven from the
94− // process-lived AppContainer scope (see AppContainer.observeRunForegroundService), not
95− // from here — a composition-scoped collector pauses while backgrounded, which is exactly
96− // when a run started via the notification reply needs the service to start.
97−
98− // When text is shared into the app, surface the session list so the user can pick
99− // (or create) a conversation to drop it into. The chosen session's draft is set
100− // in [onOpenSession] below. Keyed on `connection` too so a share that arrives
101− // before auto-reconnect completes is retried once the connection is established.
102− // Track the last-handled share payloads (there's no share nonce on the container) so a
103− // *new* share arriving while already connected — a warm start where onNewIntent re-fires
104− // setPendingShare under an unchanged connection id — still navigates, while a re-trigger
105− // carrying no new share (a bare server switch, which routes through a null connection, or
106− // a share the user already navigated for) leaves them where they are.
107− //
108− // Reset the remembered media when the pending list is drained (the chosen ChatScreen
109− // consumes it via consumePendingSharedMedia). Without this, re-sharing the *same* images
110− // after consumption compares equal structurally ([A,B] == [A,B]) and would be treated as
111− // "already handled", silently skipping the session-list navigation the second time.
112− //
113− // rememberSaveable (not remember) so a process-kill restore doesn't reset the dedup
114− // state and re-navigate to SESSIONS for a share the user already handled before the kill.
115− var handledShareText by rememberSaveable { mutableStateOf<String?>(null) }
116− var handledSharedMedia by rememberSaveable { mutableStateOf<List<String>>(emptyList()) }
117− LaunchedEffect(pendingShare, pendingSharedMedia, connection) {
118− // Reset the remembered handled state for each channel independently as it drains,
119− // so re-sharing the same payload after consumption is still recognized as new. A
120− // joint reset (only when both are empty) would drop a text-only re-share that
121− // follows a text+media share of the same text: the text channel matches its
122− // remembered value while the media channel is empty (not "new"), so neither clause
123− // fires and the share is silently swallowed.
124− if (pendingShare == null) handledShareText = null
125− if (pendingSharedMedia.isEmpty()) handledSharedMedia = emptyList()
126− if (pendingShare == null && pendingSharedMedia.isEmpty()) return@LaunchedEffect
127− if (connection == null) return@LaunchedEffect
128− val newShare = (pendingShare != null && pendingShare != handledShareText) ||
129− (pendingSharedMedia.isNotEmpty() && pendingSharedMedia != handledSharedMedia)
130− if (!newShare) return@LaunchedEffect
131− handledShareText = pendingShare
132− handledSharedMedia = pendingSharedMedia
133− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
134− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
135− }
136− }
137−
138− // Crash-relaunch prompt: navigate to the Diagnostics screen when the user taps
139− // "View report" on the cold-start crash dialog. Doesn't require a connection.
140− LaunchedEffect(pendingDiagnostics) {
141− if (!pendingDiagnostics) return@LaunchedEffect
142− container.consumePendingDiagnostics()
143− navController.navigate(Routes.DIAGNOSTICS) { launchSingleTop = true }
144− }
145−
146− // "New session" from a launcher shortcut / QS tile: once connected, create a fresh
147− // session and open it. The pending counter is consumed only *after* createSession
148− // succeeds, so a transient failure leaves the request pending to retry (on the next
149− // connection change or a re-tap that increments the counter) instead of silently
150− // dropping the tap.
151− LaunchedEffect(pendingNewSession, connection) {
152− if (pendingNewSession == 0) return@LaunchedEffect
153− val conn = connection ?: return@LaunchedEffect
154− val session = runCatchingCancellable { conn.repository.createSession() }.getOrNull()
155− ?: return@LaunchedEffect
156− if (!container.consumePendingNewSession()) return@LaunchedEffect
157− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
158− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
159 }
46 }
160− navController.navigate(Routes.chat(session.id)) { launchSingleTop = true }
161− }
162−
163− // The chat text-size preference multiplies on top of the OS font scale (sp already
164− // honors the system setting), so a large system size × large app size can reach ~2×
165− // and break tight layouts. Clamp the provided app scale so the product with the OS
166− // fontScale never exceeds NetworkConfig.maxCombinedFontScale, while never scaling
167− // below the user's chosen value's intent (floor of 1× app scale is preserved when the
168− // system size alone already exceeds the cap).
169− val systemFontScale = LocalDensity.current.fontScale
170− val clampedChatTextScale = if (systemFontScale <= 0f) {
171− chatTextScale
172− } else {
173− chatTextScale.coerceAtMost(
174− (NetworkConfig.maxCombinedFontScale / systemFontScale).coerceAtLeast(1f)
175− )
176 }
47 }
177
48
178− // Capture the reduced-motion preference once (in the composable scope) so the
49+ BackHandler(enabled = state.screen != Screen.Connect) {
179− // non-composable NavHost transition lambdas can use it to skip animations, and provide
50+ when (state.screen) {
180− // it via LocalReducedMotion so in-composition animations (chat row placement, banners,
51+ // Leaving mid-generation would silently drop the reply, so confirm first.
181− // image zoom) honor the same accessibility preference.
52+ Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
182− val reducedMotion = isReducedMotion()
53+ // Disconnecting drops the server session, so guard the back button.
183− CompositionLocalProvider(
54+ Screen.Sessions -> showDisconnectConfirm = true
184− LocalChatTextScale provides clampedChatTextScale,
55+ Screen.Connect -> Unit
185− LocalCodeWrap provides codeWrap,
186− LocalReducedMotion provides reducedMotion,
187− LocalHapticFeedback provides rememberGatedHaptics(hapticsEnabled),
188− ) {
189− // Slide direction for push/pop transitions, mirrored in RTL so the animation reads
190− // naturally instead of "going the wrong way". +1 = LTR (push from right), -1 = RTL.
191− val slideDir = if (LocalLayoutDirection.current == LayoutDirection.Rtl) -1 else 1
192− // Adaptive: on wide screens (tablets / unfolded foldables) show the session list and
193− // the open conversation side by side instead of a single-pane back stack.
194− // Posture-aware: a foldable in HALF_OPENED (tabletop/book) mode has a hinge across the
195− // content area — splitting there would place the list/detail boundary on the hinge, which
196− // is hard to read and interact with. Detect a FoldingFeature and suppress two-pane in
197− // those postures so the app falls back to a single-pane layout that respects the fold.
198− val windowContext = LocalContext.current
199− var foldState by remember { mutableStateOf<androidx.window.layout.FoldingFeature?>(null) }
200− androidx.compose.runtime.LaunchedEffect(windowContext) {
201− val activity = windowContext.findActivity()
202− if (activity != null) {
203− androidx.window.layout.WindowInfoTracker.getOrCreate(windowContext)
204− .windowLayoutInfo(activity)
205− .collect { info ->
206− foldState = info.displayFeatures
207− .filterIsInstance<androidx.window.layout.FoldingFeature>()
208− .firstOrNull()
209− }
210 }
56 }
211 }
57 }
212− val isHalfOpened = foldState?.state == androidx.window.layout.FoldingFeature.State.HALF_OPENED
213− BoxWithConstraints(
214− modifier = Modifier.onPreviewKeyEvent { ev ->
215− // Global keyboard shortcuts for hardware-keyboard users (tablets, DeX, Chromebook):
216− // Ctrl+1..6 switches between top-level destinations. Only fires on KeyDown so a
217− // held Ctrl doesn't re-trigger on every repeat. Per-screen shortcuts (Ctrl+K palette,
218− // Esc stop, Ctrl+F find) are handled in each screen's own onPreviewKeyEvent and take
219− // precedence (they're closer to the focused composable in the tree).
220− if (ev.type != KeyEventType.KeyDown || !ev.isCtrlPressed) {
221− // Alt+Left (a familiar desktop "Back" gesture) pops the back stack. Not gated
222− // on Ctrl so it works as a standalone modifier. Per-screen shortcuts (Esc
223− // stop, Ctrl+F find, Ctrl+K palette) register their own onPreviewKeyEvent
224− // closer to the focused composable and consume first, so this only pops when
225− // nothing nearer handled the key — avoiding conflicts with open dialogs and
226− // text fields. Esc is deliberately NOT mapped to back here for that reason.
227− if (ev.type == KeyEventType.KeyDown &&
228− ev.key == Key.DirectionLeft &&
229− ev.isAltPressed
230− ) {
231− if (navController.previousBackStackEntry != null) {
232− navController.popBackStack()
233− return@onPreviewKeyEvent true
234− }
235− }
236− return@onPreviewKeyEvent false
237− }
238− val route = when (ev.key) {
239− Key.NumPad1, Key.One -> Routes.SESSIONS
240− Key.NumPad2, Key.Two -> Routes.SEARCH
241− Key.NumPad3, Key.Three -> Routes.FILES
242− Key.NumPad4, Key.Four -> Routes.USAGE
243− Key.NumPad5, Key.Five -> Routes.MCP
244− Key.NumPad6, Key.Six -> Routes.SETTINGS
245− // Ctrl+7 navigates to the server list (the 7th nav-rail destination).
246− // Previously Ctrl+1..6 covered the other destinations but Servers was
247− // missing, an inconsistency since the nav rail shows 7 destinations.
248− Key.NumPad7, Key.Seven -> Routes.SERVERS
249− else -> null
250− }
251− if (route != null) {
252− // Servers is reachable even without an active connection (it's the start
253− // destination and handles the not-connected state); the other routes
254− // require a connection to be meaningful.
255− if (route == Routes.SERVERS || connection != null) {
256− navController.navigate(route) {
257− popUpTo(navController.graph.findStartDestination().id) { saveState = true }
258− launchSingleTop = true
259− restoreState = true
260− }
261− true
262− } else false
263− } else false
264− },
265− ) {
266− val isTwoPane = maxWidth >= NetworkConfig.twoPaneWidthThresholdDp.dp &&
267− connection != null &&
268− !isHalfOpened
269− // On large screens, surface a navigation rail alongside the content so top-level
270− // destinations (Sessions, Files, Search, …) are one tap away instead of buried in a
271− // screen's overflow menu. Mirrors the standard large-screen M3 layout.
272− val showNavRail = maxWidth >= NetworkConfig.navigationRailThresholdDp.dp
273− // Observe the current destination reactively so the rail's selected item tracks navigation
274− // (reading currentDestination once would go stale after the first composition).
275− val currentEntry by navController.currentBackStackEntryAsState()
276− val currentRoute = currentEntry?.destination?.route
277−
278− // Open a session requested by a notification tap or deep link, once connected.
279− LaunchedEffect(pendingOpenSession, connection, isTwoPane) {
280− val pending = pendingOpenSession ?: return@LaunchedEffect
281− if (connection == null) return@LaunchedEffect
282− // If the notification body-tap carries a profile id from a different server,
283− // switch to it first so the session opens under the server that ran it, not
284− // whichever is active. The effect re-runs when connection changes (keyed on it),
285− // so on the second run the profile matches and the open proceeds.
286− if (pending.profileId != null && connection?.profile?.id != pending.profileId) {
287− if (!container.connectByProfileId(pending.profileId)) return@LaunchedEffect
288− return@LaunchedEffect // re-run on the new connection
289− }
290− // In two-pane mode the detail pane (TwoPaneSessionChat, hosted on the SESSIONS
291− // route) consumes the request and opens it in the detail pane. But it only
292− // exists while the NavHost is on SESSIONS, so if the user is currently on
293− // Files/Settings/FileView bring SESSIONS back to front first — otherwise the
294− // pending request is never consumed and the session never opens. Don't consume
295− // here; let TwoPaneSessionChat's effect do it once it's composed.
296− if (isTwoPane) {
297− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
298− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
299− }
300− return@LaunchedEffect
301− }
302− container.consumePendingOpenSession()
303− // Ensure SESSIONS sits on the back stack below the chat destination so backing
304− // out of the chat lands on the session list (not the server list). Bring SESSIONS
305− // to front (or push it if a cold-start deep link left only SERVERS on the stack),
306− // then push chat on top — yielding SERVERS -> SESSIONS -> chat.
307− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
308− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
309− }
310− navController.navigate(Routes.chat(pending.sessionId)) { launchSingleTop = true }
311− }
312
58
313− // Deep-linked file open (opencode://file/{path}): navigate to the file viewer once a
59+ if (showStopConfirm) {
314− // connection exists (the viewer fetches content from the server). Path comes pre-validated
60+ AlertDialog(
315− // by MainActivity's deep-link guard. In two-pane mode the detail pane (TwoPaneFileBrowser,
61+ onDismissRequest = { showStopConfirm = false },
316− // hosted on the FILES route) consumes the request into its detail pane, mirroring how
62+ title = { Text("Stop generation?") },
317− // session deep links are routed — so don't consume or push the full-screen viewer here.
63+ text = { Text("Leaving will stop the current generation.") },
318− LaunchedEffect(pendingOpenFile, connection, isTwoPane) {
64+ confirmButton = {
319− val path = pendingOpenFile ?: return@LaunchedEffect
65+ TextButton(onClick = {
320− if (connection == null) return@LaunchedEffect
66+ showStopConfirm = false
321− if (isTwoPane) {
67+ dispatch(Event.CancelGeneration)
322− if (!navController.popBackStack(Routes.FILES, inclusive = false)) {
68+ dispatch(Event.NavigateToSessions)
323− navController.navigate(Routes.FILES) { launchSingleTop = true }
69+ }) {
70+ Text("Stop and leave")
324 }
71 }
325− return@LaunchedEffect
326− }
72+ },
327− container.consumePendingOpenFile()
73+ dismissButton = {
328− if (!navController.popBackStack(Routes.FILES, inclusive = false)) {
74+ TextButton(onClick = { showStopConfirm = false }) {
329− navController.navigate(Routes.FILES) { launchSingleTop = true }
75+ Text("Stay")
330− }
331− navController.navigate(Routes.fileView(path)) { launchSingleTop = true }
332− }
333−
334− val navHost = @Composable {
335− NavHost(
336− modifier = Modifier.fillMaxSize(),
337− navController = navController,
338− startDestination = Routes.SERVERS,
339− // Motion-aware transitions: respect the user's reduced-motion setting
340− // (Developer Options → animator scale 0) by skipping animations entirely.
341− // Per-destination tuning: a chat→chat navigation (switching peer conversations
342− // within the same surface) crossfades instead of sliding, so it reads as a peer
343− // switch rather than drilling into a new section. Top-level destinations and
344− // detail pushes keep the horizontal slide.
345− enterTransition = {
346− if (reducedMotion) {
347− EnterTransition.None
348− } else if (targetState.destination.route?.startsWith("${Routes.CHAT}/") == true) {
349− fadeIn(tween(NetworkConfig.motionFadeDurationMs))
350− } else {
351− slideInHorizontally(animationSpec = tween(NetworkConfig.motionSlideDurationMs)) { it * slideDir } +
352− fadeIn(tween(NetworkConfig.motionFadeDurationMs))
353 }
76 }
354 },
77 },
355− exitTransition = {
78+ )
356− if (reducedMotion) {
79+ }
357− ExitTransition.None
80+
358− } else {
81+ if (showDisconnectConfirm) {
359− fadeOut(tween(NetworkConfig.motionFadeDurationMs))
82+ AlertDialog(
83+ onDismissRequest = { showDisconnectConfirm = false },
84+ title = { Text("Disconnect?") },
85+ text = { Text("You will be disconnected from the server.") },
86+ confirmButton = {
87+ TextButton(onClick = {
88+ showDisconnectConfirm = false
89+ dispatch(Event.NavigateToConnect)
90+ }) {
91+ Text("Disconnect")
360 }
92 }
361 },
93 },
362− popEnterTransition = {
94+ dismissButton = {
363− if (reducedMotion) {
95+ TextButton(onClick = { showDisconnectConfirm = false }) {
364− EnterTransition.None
96+ Text("Cancel")
365− } else {
366− fadeIn(tween(NetworkConfig.motionFadeDurationMs))
367 }
97 }
368 },
98 },
369− popExitTransition = {
99+ )
370− if (reducedMotion) {
100+ }
371− ExitTransition.None
101+
102+ Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
103+ AnimatedContent(
104+ targetState = state.screen,
105+ modifier = Modifier.fillMaxSize().padding(padding),
106+ transitionSpec = {
107+ // Compare screen ordinals to decide slide direction: forward navigation
108+ // (Connect → Sessions → Chat) slides in from the right, back slides from the left.
109+ if (targetState.ordinal > initialState.ordinal) {
110+ slideInHorizontally { it } togetherWith slideOutHorizontally { -it }
372 } else {
111 } else {
373− slideOutHorizontally(animationSpec = tween(NetworkConfig.motionSlideDurationMs)) { it * slideDir } +
112+ slideInHorizontally { -it } togetherWith slideOutHorizontally { it }
374− fadeOut(tween(NetworkConfig.motionFadeDurationMs))
375 }
113 }
376 },
114 },
377− ) {
115+ label = "screen",
378−
116+ ) { screen ->
379− composable(Routes.SERVERS) {
117+ when (screen) {
380− ServerListScreen(
118+ Screen.Connect -> ConnectScreen(state, dispatch)
381− container = container,
119+ Screen.Sessions -> SessionsScreen(state, dispatch)
382− onConnected = {
120+ Screen.Chat -> ChatScreen(state, dispatch)
383− // Only leave the server list if we're still on it. A pending deep-link /
384− // notification open sets activeConnection (which drives the open-session
385− // effect: SERVERS -> SESSIONS -> chat) *before* autoConnectDone fires this
386− // callback, so a blind navigate(SESSIONS) here would slam a second SESSIONS
387− // on top of the chat it just opened, burying it. Order-independent: if the
388− // deep link already navigated away from SERVERS, this is a no-op.
389− if (navController.currentDestination?.route == Routes.SERVERS) {
390− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
391− }
392− },
393− onAddProfile = { navController.navigate(Routes.serverEdit()) },
394− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
395− onDuplicateProfile = { id -> navController.navigate(Routes.serverEditDuplicate(id)) },
396− )
397− }
398−
399− composable(
400− route = "${Routes.SERVER_EDIT}?id={id}&dup={dup}",
401− arguments = listOf(
402− navArgument("id") { type = NavType.StringType; nullable = true; defaultValue = null },
403− navArgument("dup") { type = NavType.StringType; nullable = true; defaultValue = null },
404− ),
405− ) { entry ->
406− ServerEditScreen(
407− container = container,
408− profileId = entry.arguments?.getString("id"),
409− sourceId = entry.arguments?.getString("dup"),
410− onDone = { navController.popBackStack() },
411− )
412− }
413−
414− composable(Routes.SESSIONS) {
415− if (isTwoPane) {
416− TwoPaneSessionChat(
417− container = container,
418− onOpenFiles = { navController.navigate(Routes.FILES) },
419− onOpenFile = { path -> navController.navigate(Routes.fileView(path)) },
420− onOpenSettings = { navController.navigate(Routes.SETTINGS) },
421− onOpenSearch = { navController.navigate(Routes.SEARCH) },
422− onDisconnect = {
423− scope.launch { runCatchingCancellable { container.disconnect() } }
424− navController.popBackStack(Routes.SERVERS, inclusive = false)
425− },
426− onAddServer = { navController.navigate(Routes.serverEdit()) },
427− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
428− )
429− } else {
430− SessionListScreen(
431− container = container,
432− onOpenSession = { id ->
433− // Set the draft synchronously in-memory before navigating so the
434− // ChatScreen sees it on first composition. The async persistence
435− // to disk happens in the background via draftStore.set.
436− container.consumePendingShare()?.let { shareText ->
437− container.draftStore.setImmediate(id, shareText)
438− scope.launch { runCatchingCancellable { container.draftStore.set(id, shareText) } }
439− }
440− navController.navigate(Routes.chat(id))
441− },
442− onDisconnect = {
443− scope.launch { runCatchingCancellable { container.disconnect() } }
444− navController.popBackStack(Routes.SERVERS, inclusive = false)
445− },
446− onOpenFiles = { navController.navigate(Routes.FILES) },
447− onOpenSettings = { navController.navigate(Routes.SETTINGS) },
448− onOpenSearch = { navController.navigate(Routes.SEARCH) },
449− onAddServer = { navController.navigate(Routes.serverEdit()) },
450− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
451− )
452− }
453− }
454−
455− composable(
456− route = "${Routes.CHAT}/{sessionId}?focus={focus}",
457− arguments = listOf(
458− navArgument("sessionId") { type = NavType.StringType },
459− navArgument("focus") { type = NavType.StringType; nullable = true; defaultValue = null },
460− ),
461− ) { entry ->
462− ChatScreen(
463− container = container,
464− sessionId = entry.arguments?.getString("sessionId").orEmpty(),
465− focusMessageId = entry.arguments?.getString("focus"),
466− onBack = { navController.popBackStack() },
467− onOpenFile = { path -> navController.navigate(Routes.fileView(path)) },
468− onOpenSession = { id ->
469− navController.navigate(Routes.chat(id)) {
470− // Prevent the same chat from being pushed twice when re-tapping a
471− // session deep link, and keep the back stack bounded when chaining
472− // chat → linked chat → … (otherwise every hop piles a new entry).
473− launchSingleTop = true
474− }
475− },
476− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
477− )
478− }
479−
480− composable(Routes.FILES) {
481− if (isTwoPane) {
482− TwoPaneFileBrowser(
483− container = container,
484− onBack = { navController.popBackStack() },
485− )
486− } else {
487− FileBrowserScreen(
488− container = container,
489− onOpenFile = { path, line -> navController.navigate(Routes.fileView(path, line)) },
490− onBack = { navController.popBackStack() },
491− )
492− }
493− }
494−
495− composable(
496− route = "${Routes.FILE_VIEW}?path={path}&line={line}",
497− arguments = listOf(
498− navArgument("path") { type = NavType.StringType; defaultValue = "" },
499− navArgument("line") { type = NavType.IntType; defaultValue = -1 },
500− ),
501− ) { entry ->
502− val line = entry.arguments?.getInt("line") ?: -1
503− FileViewScreen(
504− container = container,
505− path = entry.arguments?.getString("path").orEmpty(),
506− initialLine = line.takeIf { it > 0 },
507− onBack = { navController.popBackStack() },
508− )
509− }
510−
511− composable(Routes.SETTINGS) {
512− SettingsScreen(
513− container = container,
514− onBack = { navController.popBackStack() },
515− // Navigate to the server list as a new entry on top of Sessions so the
516− // user can back out to their conversations. Previously this popped back
517− // to the root SERVERS destination, which removed Sessions from the stack
518− // and left the user unable to return to their conversations without
519− // reconnecting. Pop only Settings, then push SERVERS; back from the
520− // server list lands on Sessions (the screen the user was on before
521− // Settings), and connecting pushes a fresh SESSIONS as usual.
522− onManageServers = {
523− navController.navigate(Routes.SERVERS) {
524− popUpTo(Routes.SETTINGS) { inclusive = true }
525− launchSingleTop = true
526− }
527− },
528− onOpenDiagnostics = { navController.navigate(Routes.DIAGNOSTICS) },
529− onOpenUsage = { navController.navigate(Routes.USAGE) },
530− onOpenMcp = { navController.navigate(Routes.MCP) },
531− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
532− )
533− }
534−
535− composable(Routes.DIAGNOSTICS) {
536− DiagnosticsScreen(onBack = { navController.popBackStack() })
537− }
538−
539− composable(Routes.USAGE) {
540− UsageScreen(
541− container = container,
542− onBack = { navController.popBackStack() },
543− onOpenSession = { id -> navController.navigate(Routes.chat(id)) },
544− )
545− }
546−
547− composable(Routes.MCP) {
548− McpScreen(container = container, onBack = { navController.popBackStack() })
549− }
550−
551− composable(Routes.SEARCH) {
552− GlobalSearchScreen(
553− container = container,
554− onOpenSession = { id, focusMessageId -> navController.navigate(Routes.chat(id, focusMessageId)) },
555− onBack = { navController.popBackStack() },
556− )
557− }
558− }
559− }
560−
561− // Collect unread/run state for nav badges (rail on large screens, bottom bar on
562− // compact screens), so a user on Files/Settings sees pending activity at a glance.
563− val unread by container.unread.collectAsStateWithLifecycle()
564− val anyRunActive by container.anyRunActive.collectAsStateWithLifecycle()
565− val totalUnread = remember(unread) { unread.values.sum() }
566−
567− if (showNavRail) {
568− Row(modifier = Modifier.fillMaxSize()) {
569− LargeScreenNavRail(
570− currentRoute = currentRoute,
571− connected = connection != null,
572− unreadCount = totalUnread,
573− runActive = anyRunActive,
574− // Use the standard M3 nav-bar pattern: popUpTo the start destination
575− // saving state, and restoreState on re-entry, so switching between
576− // top-level tabs via the rail preserves each tab's scroll/selection
577− // state and back always exits cleanly instead of popping through
578− // every sibling tab the user visited.
579− onNavigate = { route ->
580− navController.navigate(route) {
581− popUpTo(navController.graph.findStartDestination().id) {
582− saveState = true
583− }
584− launchSingleTop = true
585− restoreState = true
586− }
587− },
588− )
589− Box(modifier = Modifier.weight(1f).fillMaxHeight()) { navHost() }
590− }
591− } else {
592− // Compact screens: a bottom NavigationBar surfaces the top-level destinations one
593− // tap away (Sessions/Search/Files/Settings/Servers) instead of buried in each
594− // screen's overflow menu. The navHost fills the space above the bar; the bar's
595− // own height is accounted for by the NavigationBar's intrinsic measurement.
596− androidx.compose.foundation.layout.Column(modifier = Modifier.fillMaxSize()) {
597− Box(modifier = Modifier.weight(1f).fillMaxHeight()) { navHost() }
598− CompactNavBar(
599− currentRoute = currentRoute,
600− connected = connection != null,
601− unreadCount = totalUnread,
602− runActive = anyRunActive,
603− onNavigate = { route ->
604− navController.navigate(route) {
605− popUpTo(navController.graph.findStartDestination().id) {
606− saveState = true
607− }
608− launchSingleTop = true
609− restoreState = true
610− }
611− },
612− )
613 }
121 }
614 }
122 }
615 }
123 }
616− }
617}
124}
app/src/main/java/soy/iko/opencode/ui/Routes.ktdeleted−39
@@ -1,39 +0,0 @@
1−package soy.iko.opencode.ui
2−
3−/** String routes for the app's NavHost. Kept simple and centralized. */
4−object Routes {
5− const val SERVERS = "servers"
6− const val SESSIONS = "sessions"
7− const val SETTINGS = "settings"
8− const val DIAGNOSTICS = "diagnostics"
9− const val USAGE = "usage"
10− const val MCP = "mcp"
11− const val FILES = "files"
12− const val SEARCH = "search"
13−
14− const val SERVER_EDIT = "server_edit"
15− fun serverEdit(id: String? = null) =
16− if (id.isNullOrEmpty()) SERVER_EDIT else "$SERVER_EDIT?id=${android.net.Uri.encode(id)}"
17−
18− /** Open the editor seeded with [sourceId]'s fields but creating a new profile. */
19− fun serverEditDuplicate(sourceId: String) = "$SERVER_EDIT?dup=${android.net.Uri.encode(sourceId)}"
20−
21− const val CHAT = "chat"
22− fun chat(sessionId: String, focusMessageId: String? = null): String {
23− val base = "$CHAT/${android.net.Uri.encode(sessionId)}"
24− // An optional focusMessageId scrolls the chat to (and briefly highlights) that message,
25− // used by global search to jump directly to the matched message instead of the tail.
26− return if (focusMessageId != null && focusMessageId.isNotBlank()) {
27− "$base?focus=${android.net.Uri.encode(focusMessageId)}"
28− } else {
29− base
30− }
31− }
32−
33− const val FILE_VIEW = "file_view"
34− fun fileView(path: String, line: Int? = null): String {
35− val base = "$FILE_VIEW?path=${android.net.Uri.encode(path)}"
36− // A positive [line] scrolls the viewer to that 1-based line (from a search hit).
37− return if (line != null && line > 0) "$base&line=$line" else base
38− }
39−}
app/src/main/java/soy/iko/opencode/ui/VmFactory.ktdeleted−16
@@ -1,16 +0,0 @@
1−package soy.iko.opencode.ui
2−
3−import androidx.lifecycle.ViewModel
4−import androidx.lifecycle.viewmodel.CreationExtras
5−import androidx.lifecycle.viewmodel.initializer
6−import androidx.lifecycle.viewmodel.viewModelFactory
7−
8−/**
9− * Tiny bridge between manual DI and Compose's `viewModel()`. Builds a
10− * [androidx.lifecycle.ViewModelProvider.Factory] from a plain constructor lambda.
11− */
12−inline fun <reified VM : ViewModel> vmFactory(
13− crossinline create: (CreationExtras) -> VM,
14−) = viewModelFactory {
15− initializer { create(this) }
16−}
app/src/main/java/soy/iko/opencode/ui/chat/AgentPickerSheet.ktdeleted−318
@@ -1,318 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import androidx.compose.foundation.clickable
4−import androidx.compose.foundation.layout.Column
5−import androidx.compose.foundation.layout.Row
6−import androidx.compose.foundation.layout.fillMaxWidth
7−import androidx.compose.foundation.layout.heightIn
8−import androidx.compose.foundation.layout.imePadding
9−import androidx.compose.foundation.layout.navigationBarsPadding
10−import androidx.compose.foundation.layout.padding
11−import androidx.compose.foundation.layout.size
12−import androidx.compose.foundation.lazy.LazyColumn
13−import androidx.compose.foundation.lazy.items
14−import androidx.compose.foundation.lazy.rememberLazyListState
15−import androidx.compose.foundation.text.KeyboardActions
16−import androidx.compose.foundation.text.KeyboardOptions
17−import androidx.compose.material.icons.Icons
18−import androidx.compose.material.icons.filled.Check
19−import androidx.compose.material.icons.filled.Close
20−import androidx.compose.material.icons.filled.Search
21−import androidx.compose.material3.CircularProgressIndicator
22−import androidx.compose.material3.ExperimentalMaterial3Api
23−import androidx.compose.material3.Icon
24−import androidx.compose.material3.IconButton
25−import androidx.compose.material3.MaterialTheme
26−import androidx.compose.material3.ModalBottomSheet
27−import androidx.compose.material3.OutlinedTextField
28−import androidx.compose.material3.Text
29−import androidx.compose.material3.TextButton
30−import androidx.compose.material3.rememberModalBottomSheetState
31−import androidx.compose.runtime.Composable
32−import androidx.compose.runtime.LaunchedEffect
33−import androidx.compose.runtime.getValue
34−import androidx.compose.runtime.mutableStateOf
35−import androidx.compose.runtime.remember
36−import androidx.compose.runtime.rememberCoroutineScope
37−import androidx.compose.runtime.saveable.rememberSaveable
38−import androidx.compose.runtime.setValue
39−import androidx.compose.ui.Alignment
40−import androidx.compose.ui.Modifier
41−import androidx.compose.ui.focus.FocusRequester
42−import androidx.compose.ui.focus.focusRequester
43−import androidx.compose.ui.hapticfeedback.HapticFeedbackType
44−import androidx.compose.ui.platform.LocalHapticFeedback
45−import androidx.compose.ui.platform.LocalSoftwareKeyboardController
46−import androidx.compose.ui.res.stringResource
47−import androidx.compose.ui.semantics.Role
48−import androidx.compose.ui.semantics.contentDescription
49−import androidx.compose.ui.semantics.role
50−import androidx.compose.ui.semantics.selectableGroup
51−import androidx.compose.ui.semantics.selected
52−import androidx.compose.ui.semantics.semantics
53−import androidx.compose.ui.text.input.ImeAction
54−import androidx.compose.ui.text.style.TextOverflow
55−import androidx.compose.ui.unit.dp
56−import androidx.compose.foundation.layout.Box
57−import kotlinx.coroutines.launch
58−import soy.iko.opencode.data.model.Agent
59−import soy.iko.opencode.data.network.NetworkConfig
60−import soy.iko.opencode.R
61−
62−/**
63− * Flat LazyColumn index of the selected agent, offset by the leading "Default" row when it's
64− * shown. A null selection targets that Default row (index 0). -1 when the selection isn't in
65− * the current list.
66− */
67−/** Whether the synthetic "Default" agent row matches the current search query. */
68−private fun defaultAgentMatches(query: String, label: String, desc: String): Boolean =
69− query.isEmpty() ||
70− label.contains(query, ignoreCase = true) ||
71− desc.contains(query, ignoreCase = true)
72−
73−private fun selectedAgentIndex(
74− distinctAgents: List<Agent>,
75− selected: String?,
76− defaultMatches: Boolean,
77−): Int {
78− if (selected == null) return if (defaultMatches) 0 else -1
79− val base = if (defaultMatches) 1 else 0
80− val pos = distinctAgents.indexOfFirst { it.name == selected }
81− return if (pos >= 0) base + pos else -1
82−}
83−
84−/** Bottom sheet that lists every agent and lets the user pick one. */
85−@OptIn(ExperimentalMaterial3Api::class)
86−@Composable
87−fun AgentPickerSheet(
88− agents: List<Agent>,
89− selected: String?,
90− loading: Boolean,
91− error: Boolean,
92− onSelect: (Agent?) -> Unit,
93− onRetry: () -> Unit,
94− onDismiss: () -> Unit,
95−) {
96− // Hoist the SheetState so selection can animate the sheet out (slide) instead of
97− // snap-dismissing by tearing down the composition. skipPartiallyExpanded = true so the
98− // sheet opens at full height and the list's heightIn cap resolves against a stable sheet,
99− // not the half-height partial state (which previously left the list at ~25% of the screen
100− // until the user dragged up).
101− val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
102− val scope = rememberCoroutineScope()
103− ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
104− Text(
105− stringResource(R.string.agent),
106− style = MaterialTheme.typography.titleMedium,
107− modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
108− )
109− if (loading) {
110− val loadingLabel = stringResource(R.string.loading_agents)
111− Column(
112− modifier = Modifier.fillMaxWidth().padding(vertical = 24.dp).imePadding(),
113− horizontalAlignment = Alignment.CenterHorizontally,
114− ) {
115− CircularProgressIndicator(Modifier.semantics { contentDescription = loadingLabel })
116− Text(
117− stringResource(R.string.loading_agents),
118− style = MaterialTheme.typography.bodyMedium,
119− color = MaterialTheme.colorScheme.onSurfaceVariant,
120− modifier = Modifier.padding(top = 8.dp),
121− )
122− }
123− } else if (error && agents.isEmpty()) {
124− Column(
125− modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 16.dp),
126− horizontalAlignment = Alignment.CenterHorizontally,
127− ) {
128− Text(
129− stringResource(R.string.load_failed),
130− style = MaterialTheme.typography.bodyMedium,
131− color = MaterialTheme.colorScheme.error,
132− )
133− TextButton(onClick = onRetry) { Text(stringResource(R.string.retry)) }
134− }
135− } else if (agents.isEmpty()) {
136− Text(
137− stringResource(R.string.no_agents),
138− style = MaterialTheme.typography.bodyMedium,
139− color = MaterialTheme.colorScheme.onSurfaceVariant,
140− modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp),
141− )
142− } else {
143− var query by rememberSaveable { mutableStateOf("") }
144− val keyboardController = LocalSoftwareKeyboardController.current
145− val haptics = LocalHapticFeedback.current
146− // Auto-focus the search field (and raise the keyboard) when the sheet opens, but skip
147− // it for a short catalog that's faster to scan by eye than to filter.
148− val searchFocus = remember { FocusRequester() }
149− LaunchedEffect(Unit) {
150− if (agents.size > NetworkConfig.pickerSearchAutofocusThreshold) {
151− runCatching { searchFocus.requestFocus() }
152− }
153− }
154− OutlinedTextField(
155− value = query,
156− onValueChange = { query = it },
157− modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp).focusRequester(searchFocus),
158− placeholder = { Text(stringResource(R.string.search_agents)) },
159− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
160− trailingIcon = if (query.isNotEmpty()) {
161− {
162− IconButton(onClick = { query = "" }) {
163− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
164− }
165− }
166− } else null,
167− singleLine = true,
168− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
169− keyboardActions = KeyboardActions(onSearch = { keyboardController?.hide() }),
170− )
171− // Dedupe the source list once (keyed on `agents`, not the per-keystroke `filtered`),
172− // so distinctBy doesn't re-walk the catalog on every character typed.
173− val distinctAgents = remember(agents) { agents.distinctBy { it.name } }
174− val filtered = remember(distinctAgents, query) {
175− val q = query.trim()
176− if (q.isEmpty()) distinctAgents
177− else distinctAgents.filter {
178− it.name.contains(q, ignoreCase = true) ||
179− it.displayDescription.contains(q, ignoreCase = true)
180− }
181− }
182− // The "Default" option participates in the search too: show it when the query is
183− // empty or matches its label/description. Without this it either always showed
184− // (ignoring the filter) or, when a query matched no named agent, disappeared with
185− // the whole list — leaving the default unselectable.
186− val defaultLabel = stringResource(R.string.default_agent)
187− val defaultDesc = stringResource(R.string.default_agent_desc)
188− val q = query.trim()
189− val defaultMatches = defaultAgentMatches(q, defaultLabel, defaultDesc)
190− if (filtered.isEmpty() && !defaultMatches) {
191− Text(
192− stringResource(R.string.no_agents_match, query.trim()),
193− style = MaterialTheme.typography.bodyMedium,
194− color = MaterialTheme.colorScheme.onSurfaceVariant,
195− modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp),
196− )
197− } else {
198− val listState = rememberLazyListState()
199− // Flat index of the selected agent, offset by the leading "Default" row when
200− // it's shown. selected == null targets that Default row (index 0). -1 when the
201− // selection isn't in the current list. Computed against `filtered` (not the
202− // unfiltered distinctAgents) so a query that hides agents before the selection
203− // still maps to the right visible row.
204− val selectedIndex = remember(filtered, selected, defaultMatches) {
205− selectedAgentIndex(filtered, selected, defaultMatches)
206− }
207− // Re-scroll to the selected item whenever the filter changes (not just once on
208− // open), so clearing a filter that had hidden the selection brings it back into
209− // view instead of leaving the list at the top.
210− LaunchedEffect(filtered, defaultMatches) {
211− if (selectedIndex >= 0) listState.scrollToItem(selectedIndex)
212− }
213− // Cap the list height against the screen, not the (partial) sheet, so the list
214− // is a predictable height regardless of drag position. weight(1f) would also
215− // work but heightIn keeps the sheet compact for short catalogs.
216− LazyColumn(
217− state = listState,
218− modifier = Modifier
219− .heightIn(max = NetworkConfig.pickerSheetMaxHeightDp.dp)
220− .imePadding()
221− .navigationBarsPadding()
222− .semantics { selectableGroup() },
223− ) {
224− if (defaultMatches) {
225− item(key = "__default") {
226− Column(
227− modifier = Modifier
228− .fillMaxWidth()
229− .semantics(mergeDescendants = true) {
230− this.selected = (selected == null)
231− }
232− .clickable(role = Role.RadioButton) {
233− haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)
234− // Animate the sheet out before tearing down, so the selection
235− // reads as a smooth transition instead of a snap disappearance.
236− scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() }
237− onSelect(null)
238− }
239− .padding(horizontal = 24.dp, vertical = 12.dp),
240− ) {
241− Row(verticalAlignment = Alignment.CenterVertically) {
242− Text(
243− stringResource(R.string.default_agent),
244− style = MaterialTheme.typography.bodyLarge,
245− color = if (selected == null) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
246− modifier = Modifier.weight(1f),
247− )
248− if (selected == null) {
249− Icon(
250− Icons.Filled.Check,
251− contentDescription = null,
252− tint = MaterialTheme.colorScheme.primary,
253− modifier = Modifier.size(20.dp),
254− )
255− }
256− }
257− Text(
258− stringResource(R.string.default_agent_desc),
259− style = MaterialTheme.typography.bodySmall,
260− color = MaterialTheme.colorScheme.onSurfaceVariant,
261− )
262− }
263− }
264− }
265− // distinctBy the name so a server that returns two agents with the same name
266− // (e.g. a built-in colliding with a project-level one) can't crash the list
267− // with LazyColumn's "Key was already used".
268− // Namespace the agent keys so an agent literally named "__default" can't
269− // collide with the sentinel key of the default item above (a duplicate key
270− // crashes LazyColumn).
271− items(filtered, key = { "agent_" + it.name }) { agent ->
272− val isSelected = agent.name == selected
273− Column(
274− modifier = Modifier
275− .fillMaxWidth()
276− .semantics(mergeDescendants = true) {
277− this.selected = isSelected
278− }
279− .clickable(role = Role.RadioButton) {
280− haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)
281− scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() }
282− onSelect(agent)
283− }
284− .padding(horizontal = 24.dp, vertical = 12.dp),
285− ) {
286− Row(verticalAlignment = Alignment.CenterVertically) {
287− Text(
288− agent.name,
289− style = MaterialTheme.typography.bodyLarge,
290− color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
291− modifier = Modifier.weight(1f),
292− )
293− if (isSelected) {
294− Icon(
295− Icons.Filled.Check,
296− contentDescription = null,
297− tint = MaterialTheme.colorScheme.primary,
298− modifier = Modifier.size(20.dp),
299− )
300− }
301− }
302− Text(
303− agent.displayDescription,
304− style = MaterialTheme.typography.bodySmall,
305− color = MaterialTheme.colorScheme.onSurfaceVariant,
306− // Cap at 2 lines (matching the command picker) so a verbose
307− // description doesn't make the row arbitrarily tall and push the
308− // radio affordance out of alignment across the list.
309− maxLines = 2,
310− overflow = TextOverflow.Ellipsis,
311− )
312− }
313− }
314− }
315− }
316− }
317− }
318−}
app/src/main/java/soy/iko/opencode/ui/chat/AttachmentResult.ktdeleted−12
@@ -1,12 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−/** Outcome of turning a picked Uri into a [PendingAttachment] (see `Uri.toAttachmentResult`). */
4−sealed interface AttachmentResult {
5− data class Ok(val attachment: PendingAttachment) : AttachmentResult
6−
7− /** The file exceeded the size cap ([soy.iko.opencode.data.network.NetworkConfig.maxAttachmentBytes]). */
8− data object TooLarge : AttachmentResult
9−
10− /** The file couldn't be read/resolved. */
11− data object Failed : AttachmentResult
12−}
app/src/main/java/soy/iko/opencode/ui/chat/Attachments.ktdeleted−117
@@ -1,117 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import android.content.Context
4−import android.net.Uri
5−import android.provider.OpenableColumns
6−import android.util.Base64
7−import androidx.core.content.FileProvider
8−import soy.iko.opencode.data.model.FilePromptPart
9−import soy.iko.opencode.data.network.NetworkConfig
10−import soy.iko.opencode.util.runCatchingCancellable
11−import kotlinx.coroutines.Dispatchers
12−import kotlinx.coroutines.withContext
13−import java.io.File
14−
15−/**
16− * Read [uri]'s bytes off the main thread, base64-encode them into a `data:` URL, and wrap
17− * the result as a [PendingAttachment] ready to send. Enforces the size cap. The original
18− * [uri] is kept as the thumbnail model for images (Coil loads content Uris directly).
19− */
20−suspend fun Uri.toAttachmentResult(context: Context): AttachmentResult = withContext(Dispatchers.IO) {
21− val resolver = context.contentResolver
22− val mime = resolver.getType(this@toAttachmentResult) ?: "application/octet-stream"
23− val name = displayName(context) ?: defaultName(mime)
24− val max = NetworkConfig.maxAttachmentBytes
25− // Cheap pre-check: if the provider reports a size, reject an oversize file before reading
26− // a single byte into memory. The picker can hand back arbitrarily large files (e.g. a
27− // multi-hundred-MB video), so reading first and checking after would OOM the app.
28− val declaredSize = fileSize(context)
29− if (declaredSize != null && declaredSize > max) return@withContext AttachmentResult.TooLarge
30− // Read with a hard cap so a provider that under-reports or omits its size still can't OOM
31− // us: stop as soon as we've read one byte past the cap, then reject.
32− val bytes = runCatchingCancellable {
33− resolver.openInputStream(this@toAttachmentResult)?.use { it.readAtMost(max + 1) }
34− }.getOrNull() ?: return@withContext AttachmentResult.Failed
35− if (bytes.size > max) return@withContext AttachmentResult.TooLarge
36− val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
37− val dataUrl = "data:$mime;base64,$b64"
38− AttachmentResult.Ok(
39− PendingAttachment(
40− id = java.util.UUID.randomUUID().toString(),
41− name = name,
42− mime = mime,
43− previewModel = if (mime.startsWith("image/")) this@toAttachmentResult.toString() else null,
44− part = FilePromptPart(mime = mime, url = dataUrl, filename = name),
45− ),
46− )
47−}
48−
49−/** The provider-reported byte size of the content [uri], or null if it isn't exposed. */
50−private fun Uri.fileSize(context: Context): Long? = runCatching {
51− context.contentResolver.query(this, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { cursor ->
52− val idx = cursor.getColumnIndex(OpenableColumns.SIZE)
53− if (idx >= 0 && cursor.moveToFirst() && !cursor.isNull(idx)) cursor.getLong(idx) else null
54− }
55−}.getOrNull()
56−
57−/** Read up to [limit] bytes from the stream without materializing the whole file, so an
58− * oversize source can be rejected on a bounded amount of memory. Reaching [limit] bytes is
59− * the caller's signal that the source exceeds the cap. */
60−private fun java.io.InputStream.readAtMost(limit: Long): ByteArray {
61− val out = java.io.ByteArrayOutputStream()
62− val chunk = ByteArray(8 * 1024)
63− var total = 0L
64− while (total < limit) {
65− val want = minOf(chunk.size.toLong(), limit - total).toInt()
66− val read = read(chunk, 0, want)
67− if (read < 0) break
68− out.write(chunk, 0, read)
69− total += read
70− }
71− return out.toByteArray()
72−}
73−
74−/** The raw (pre-base64) byte size encoded in a `data:<mime>;base64,<payload>` URL, derived from
75− * the payload length (len / 4 * 3, less any '=' padding) without allocating or decoding the
76− * payload — important since the payload can be many MB. Returns 0 when the URL has no base64
77− * payload. Lets the cumulative attachment-size cap use the same raw-byte measure as the per-file
78− * [NetworkConfig.maxAttachmentBytes] check above (which counts raw `bytes.size`). */
79−internal fun base64DataUrlByteSize(dataUrl: String): Long {
80− val marker = "base64,"
81− val start = dataUrl.indexOf(marker)
82− if (start < 0) return 0L
83− val payloadLen = dataUrl.length - (start + marker.length)
84− if (payloadLen <= 0) return 0L
85− val padding = when {
86− dataUrl.endsWith("==") -> 2
87− dataUrl.endsWith("=") -> 1
88− else -> 0
89− }
90− return payloadLen.toLong() / 4 * 3 - padding
91−}
92−
93−/** Resolve a human-readable display name for the content [uri], if the provider exposes one. */
94−private fun Uri.displayName(context: Context): String? = runCatching {
95− context.contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
96− val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
97− if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
98− }
99−}.getOrNull()?.takeIf { it.isNotBlank() }
100−
101−private fun defaultName(mime: String): String {
102− val ext = mime.substringAfterLast('/', "bin").takeIf { it.isNotBlank() } ?: "bin"
103− return "attachment.$ext"
104−}
105−
106−/**
107− * Create a temp file in the cache and a shareable content [Uri] for it (via the app's
108− * [FileProvider]) to hand to the camera as the capture target. Returns null if it can't be
109− * created. Uses a fixed filename so each capture overwrites the prior (the OS also evicts
110− * cache under storage pressure); a unique-per-capture timestamped name would leak a .jpg
111− * per canceled capture in cacheDir/captures/ with no cleanup path.
112− */
113−fun newCameraCaptureUri(context: Context): Uri? = runCatching {
114− val dir = File(context.cacheDir, "captures").apply { mkdirs() }
115− val file = File(dir, "capture.jpg")
116− FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
117−}.getOrNull()
app/src/main/java/soy/iko/opencode/ui/chat/ChatAttachments.ktdeleted−258
@@ -1,258 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import androidx.compose.foundation.layout.Arrangement
4−import androidx.compose.foundation.layout.Box
5−import androidx.compose.foundation.layout.Column
6−import androidx.compose.foundation.layout.Row
7−import androidx.compose.foundation.layout.fillMaxSize
8−import androidx.compose.foundation.layout.fillMaxWidth
9−import androidx.compose.foundation.layout.padding
10−import androidx.compose.foundation.layout.size
11−import androidx.compose.foundation.layout.widthIn
12−import androidx.compose.foundation.clickable
13−import androidx.compose.foundation.combinedClickable
14−import androidx.compose.foundation.horizontalScroll
15−import androidx.compose.foundation.rememberScrollState
16−import androidx.compose.material.icons.Icons
17−import androidx.compose.material.icons.filled.Close
18−import androidx.compose.material.icons.filled.Description
19−import androidx.compose.material3.AlertDialog
20−import androidx.compose.material3.CircularProgressIndicator
21−import androidx.compose.material3.Icon
22−import androidx.compose.material3.IconButton
23−import androidx.compose.material3.MaterialTheme
24−import androidx.compose.material3.Surface
25−import androidx.compose.material3.Text
26−import androidx.compose.runtime.Composable
27−import androidx.compose.runtime.getValue
28−import androidx.compose.runtime.mutableStateOf
29−import androidx.compose.runtime.remember
30−import androidx.compose.runtime.setValue
31−import androidx.compose.ui.Alignment
32−import androidx.compose.ui.Modifier
33−import androidx.compose.ui.draw.clip
34−import androidx.compose.ui.layout.ContentScale
35−import androidx.compose.ui.res.stringResource
36−import androidx.compose.ui.semantics.Role
37−import androidx.compose.ui.semantics.contentDescription
38−import androidx.compose.ui.semantics.semantics
39−import androidx.compose.ui.text.style.TextOverflow
40−import androidx.compose.ui.unit.dp
41−import androidx.compose.ui.window.Dialog
42−import androidx.compose.ui.window.DialogProperties
43−import coil3.compose.AsyncImage
44−import soy.iko.opencode.R
45−import soy.iko.opencode.data.network.NetworkConfig
46−import java.util.Locale
47−
48−/**
49− * The staged-attachment UI for the chat composer — extracted from ChatScreen so that (large)
50− * file stays focused on the conversation surface. `internal` so ChatScreen can call it.
51− *
52− * When at least one attachment is staged, a muted total-size label is rendered at the end of
53− * the strip so the user can see how close they are to the cumulative [NetworkConfig.maxTotalAttachmentBytes]
54− * cap — a bare per-file cap doesn't surface the combined total, and a failed send is the only
55− * other feedback.
56− */
57−@Composable
58−internal fun AttachmentStrip(
59− attachments: List<PendingAttachment>,
60− onRemove: (String) -> Unit,
61− staging: Boolean = false,
62− stagingFileCount: Int = 0,
63−) {
64− // Show the strip while an encode is in flight even before the first chip exists, so the
65− // user gets immediate feedback that their pick is being processed.
66− if (attachments.isEmpty() && !staging) return
67− // Horizontally-scrollable strip of staged attachment thumbnails/chips, each removable.
68− Row(
69− modifier = Modifier
70− .fillMaxWidth()
71− .horizontalScroll(rememberScrollState())
72− .padding(start = 8.dp, end = 8.dp, top = 8.dp),
73− horizontalArrangement = Arrangement.spacedBy(8.dp),
74− verticalAlignment = Alignment.CenterVertically,
75− ) {
76− attachments.forEach { att ->
77− AttachmentChip(att, onRemove = { onRemove(att.id) })
78− }
79− // A placeholder chip with an indeterminate spinner while any pick is still being
80− // read + base64-encoded off the main thread (chips only materialize once done).
81− if (staging) StagingChip(stagingFileCount)
82− // Total staged size label — surfaced so the user can see how close they are to the
83− // cumulative cap before a send fails. Hidden while staging (the total is in flux).
84− if (!staging && attachments.isNotEmpty()) {
85− val totalBytes = remember(attachments) {
86− attachments.sumOf { base64DataUrlByteSize(it.part.url) }
87− }
88− val maxBytes = NetworkConfig.maxTotalAttachmentBytes
89− val label = remember(totalBytes, maxBytes) { formatAttachmentTotal(totalBytes, maxBytes) }
90− val over = totalBytes > maxBytes
91− Text(
92− label,
93− style = MaterialTheme.typography.labelSmall,
94− color = if (over) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
95− modifier = Modifier.padding(start = 4.dp, end = 4.dp),
96− )
97− }
98− }
99−}
100−
101−/** Format the staged-attachment total as "N.N MB / max" (or KB when small), for the strip label. */
102−private fun formatAttachmentTotal(bytes: Long, max: Long): String {
103− val mb = 1024.0 * 1024.0
104− val kb = 1024.0
105− val used = when {
106− bytes >= mb -> String.format(Locale.US, "%.1f MB", bytes / mb)
107− bytes >= kb -> String.format(Locale.US, "%.0f KB", bytes / kb)
108− else -> "$bytes B"
109− }
110− val maxStr = when {
111− max >= mb -> String.format(Locale.US, "%.0f MB", max / mb)
112− max >= kb -> String.format(Locale.US, "%.0f KB", max / kb)
113− else -> "$max B"
114− }
115− return "$used / $maxStr"
116−}
117−
118−/** A placeholder chip shown while an attachment is being encoded. */
119−@Composable
120−private fun StagingChip(stagingFileCount: Int) {
121− // Show "Staging N files…" when a multi-file count is known; fall back to the generic
122− // "Attaching…" for the single/unknown case so the label never reads "Staging 1 files".
123− val label = if (stagingFileCount > 1) {
124− stringResource(R.string.staging_n_files, stagingFileCount)
125− } else {
126− stringResource(R.string.attachment_staging)
127− }
128− Surface(
129− shape = MaterialTheme.shapes.small,
130− color = MaterialTheme.colorScheme.surfaceVariant,
131− tonalElevation = 1.dp,
132− ) {
133− Row(
134− verticalAlignment = Alignment.CenterVertically,
135− modifier = Modifier.padding(horizontal = 10.dp),
136− ) {
137− CircularProgressIndicator(
138− Modifier.size(18.dp).semantics { contentDescription = label },
139− strokeWidth = 2.dp,
140− )
141− Text(
142− label,
143− style = MaterialTheme.typography.labelMedium,
144− maxLines = 1,
145− modifier = Modifier.padding(start = 8.dp, top = 10.dp, bottom = 10.dp),
146− )
147− }
148− }
149−}
150−
151−/** A single staged attachment: an image thumbnail (or a generic file icon) with its name
152− * and a remove button. Tapping the thumbnail/name of an image attachment opens a fullscreen
153− * preview so the user can verify it before sending (a sent image costs tokens and can't be
154− * unsent). */
155−@Composable
156−private fun AttachmentChip(attachment: PendingAttachment, onRemove: () -> Unit) {
157− var showPreview by remember { mutableStateOf(false) }
158− var showNameDialog by remember { mutableStateOf(false) }
159− val previewLabel = stringResource(R.string.preview_attachment)
160− val haptics = androidx.compose.ui.platform.LocalHapticFeedback.current
161− Surface(
162− shape = MaterialTheme.shapes.small,
163− color = MaterialTheme.colorScheme.surfaceVariant,
164− tonalElevation = 1.dp,
165− ) {
166− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 6.dp)) {
167− if (attachment.previewModel != null) {
168− AsyncImage(
169− model = attachment.previewModel,
170− contentDescription = attachment.name,
171− contentScale = ContentScale.Crop,
172− modifier = Modifier
173− .size(36.dp)
174− .clip(MaterialTheme.shapes.extraSmall)
175− .semantics { contentDescription = previewLabel }
176− .clickable(role = Role.Image) { showPreview = true },
177− )
178− } else {
179− // Long-press the file icon to see the full filename (it's truncated to 120dp
180− // in the chip, so a long name can't be read in full otherwise). Mirrors the
181− // image chip's tap-to-preview pattern for non-image files.
182− Icon(
183− Icons.Filled.Description,
184− contentDescription = null,
185− modifier = Modifier
186− .size(24.dp)
187− .combinedClickable(
188− role = Role.Image,
189− onLongClick = {
190− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
191− showNameDialog = true
192− },
193− onClick = {},
194− ),
195− tint = MaterialTheme.colorScheme.onSurfaceVariant,
196− )
197− }
198− Text(
199− attachment.name,
200− style = MaterialTheme.typography.labelMedium,
201− maxLines = 1,
202− overflow = TextOverflow.Ellipsis,
203− modifier = Modifier.widthIn(max = 120.dp).padding(horizontal = 6.dp),
204− )
205− // No .size() override so the IconButton keeps its default 48dp touch target
206− // (a11y minimum) while the visual X stays small (16dp).
207− IconButton(onClick = onRemove) {
208− Icon(
209− Icons.Filled.Close,
210− contentDescription = stringResource(R.string.remove),
211− modifier = Modifier.size(16.dp),
212− )
213− }
214− }
215− }
216− if (showPreview && attachment.previewModel != null) {
217− Dialog(
218− onDismissRequest = { showPreview = false },
219− properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
220− ) {
221− Box(
222− modifier = Modifier.fillMaxSize().padding(16.dp),
223− contentAlignment = Alignment.Center,
224− ) {
225− AsyncImage(
226− model = attachment.previewModel,
227− contentDescription = attachment.name,
228− contentScale = ContentScale.Fit,
229− modifier = Modifier.fillMaxWidth().clickable(role = Role.Image) { showPreview = false },
230− )
231− IconButton(
232− onClick = { showPreview = false },
233− modifier = Modifier.align(Alignment.TopEnd),
234− ) {
235− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close))
236− }
237− }
238− }
239− }
240− if (showNameDialog) {
241− AlertDialog(
242− onDismissRequest = { showNameDialog = false },
243− title = { Text(stringResource(R.string.attachment_name)) },
244− text = {
245− Text(
246− attachment.name,
247− style = MaterialTheme.typography.bodyMedium,
248− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
249− )
250− },
251− confirmButton = {
252− androidx.compose.material3.TextButton(onClick = { showNameDialog = false }) {
253− Text(stringResource(R.string.close))
254− }
255− },
256− )
257− }
258−}
app/src/main/java/soy/iko/opencode/ui/chat/ChatScreen.ktdeleted−3343
@@ -1,3343 +0,0 @@
1−@file:Suppress("TooManyFunctions")
2−
3−package soy.iko.opencode.ui.chat
4−
5−import android.app.Activity
6−import android.content.Intent
7−import android.net.Uri
8−import android.speech.RecognizerIntent
9−import androidx.activity.compose.BackHandler
10−import androidx.activity.compose.rememberLauncherForActivityResult
11−import androidx.activity.result.PickVisualMediaRequest
12−import androidx.activity.result.contract.ActivityResultContracts
13−import androidx.compose.animation.AnimatedVisibility
14−import androidx.compose.animation.core.RepeatMode
15−import androidx.compose.animation.core.animateFloat
16−import androidx.compose.animation.core.infiniteRepeatable
17−import androidx.compose.animation.core.rememberInfiniteTransition
18−import androidx.compose.animation.core.tween
19−import androidx.compose.foundation.background
20−import androidx.compose.foundation.clickable
21−import androidx.compose.foundation.content.contentReceiver
22−import androidx.compose.foundation.layout.Arrangement
23−import androidx.compose.foundation.layout.Box
24−import androidx.compose.foundation.layout.Column
25−import androidx.compose.foundation.layout.FlowRow
26−import androidx.compose.foundation.layout.PaddingValues
27−import androidx.compose.foundation.layout.Row
28−import androidx.compose.foundation.layout.Spacer
29−import androidx.compose.foundation.layout.WindowInsets
30−import androidx.compose.foundation.layout.fillMaxSize
31−import androidx.compose.foundation.layout.fillMaxWidth
32−import androidx.compose.foundation.layout.heightIn
33−import androidx.compose.foundation.layout.height
34−import androidx.compose.foundation.layout.imePadding
35−import androidx.compose.foundation.layout.ime
36−import androidx.compose.foundation.layout.navigationBars
37−import androidx.compose.foundation.layout.padding
38−import androidx.compose.foundation.layout.size
39−import androidx.compose.foundation.layout.union
40−import androidx.compose.foundation.layout.widthIn
41−import androidx.compose.foundation.layout.windowInsetsPadding
42−import androidx.compose.foundation.layout.wrapContentWidth
43−import androidx.compose.foundation.lazy.LazyColumn
44−import androidx.compose.foundation.lazy.items
45−import androidx.compose.foundation.lazy.rememberLazyListState
46−import androidx.compose.foundation.shape.RoundedCornerShape
47−import androidx.compose.material.icons.Icons
48−import androidx.compose.material.icons.automirrored.filled.ArrowBack
49−import androidx.compose.material.icons.automirrored.filled.Send
50−import androidx.compose.material.icons.filled.ErrorOutline
51−import androidx.compose.material.icons.filled.Add
52−import androidx.compose.material.icons.filled.AutoAwesome
53−import androidx.compose.material.icons.filled.Delete
54−import androidx.compose.material.icons.filled.Description
55−import androidx.compose.material.icons.filled.Close
56−import androidx.compose.material.icons.filled.Edit
57−import androidx.compose.material.icons.filled.Expand
58−import androidx.compose.material.icons.filled.FormatQuote
59−import androidx.compose.material.icons.filled.ExpandLess
60−import androidx.compose.material.icons.filled.ExpandMore
61−import androidx.compose.material.icons.filled.Search
62−import androidx.compose.material.icons.filled.KeyboardArrowDown
63−import androidx.compose.material.icons.filled.KeyboardArrowUp
64−import androidx.compose.material.icons.filled.Mic
65−import androidx.compose.material.icons.filled.MoreVert
66−import androidx.compose.material.icons.filled.PhotoCamera
67−import androidx.compose.material.icons.filled.PhotoLibrary
68−import androidx.compose.material.icons.filled.Refresh
69−import androidx.compose.material.icons.filled.Restore
70−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
71−import androidx.compose.material.icons.automirrored.filled.Reply
72−import androidx.compose.material.icons.filled.Schedule
73−import androidx.compose.material.icons.filled.Stop
74−import androidx.compose.material3.AlertDialog
75−import androidx.compose.material3.Badge
76−import androidx.compose.material3.BadgedBox
77−import androidx.compose.material3.Button
78−import androidx.compose.material3.CircularProgressIndicator
79−import androidx.compose.material3.SmallFloatingActionButton
80−import androidx.compose.material3.DropdownMenu
81−import androidx.compose.material3.DropdownMenuItem
82−import androidx.compose.material3.ExperimentalMaterial3Api
83−import androidx.compose.material3.ExtendedFloatingActionButton
84−import androidx.compose.material3.FloatingActionButton
85−import androidx.compose.material3.Icon
86−import androidx.compose.material3.IconButton
87−import androidx.compose.material3.MaterialTheme
88−import androidx.compose.material3.OutlinedTextField
89−import androidx.compose.material3.Scaffold
90−import androidx.compose.material3.SnackbarDuration
91−import androidx.compose.material3.SwipeToDismissBox
92−import androidx.compose.material3.SwipeToDismissBoxValue
93−import androidx.compose.material3.rememberSwipeToDismissBoxState
94−import androidx.compose.material3.SnackbarHost
95−import androidx.compose.material3.SnackbarHostState
96−import androidx.compose.material3.SnackbarResult
97−import androidx.compose.material3.Surface
98−import androidx.compose.material3.Text
99−import androidx.compose.material3.TextButton
100−import androidx.compose.material3.TopAppBar
101−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
102−import androidx.compose.runtime.Composable
103−import androidx.compose.runtime.CompositionLocalProvider
104−import androidx.compose.runtime.DisposableEffect
105−import androidx.compose.runtime.LaunchedEffect
106−import androidx.compose.runtime.derivedStateOf
107−import androidx.compose.runtime.getValue
108−import androidx.compose.runtime.mutableIntStateOf
109−import androidx.compose.runtime.mutableLongStateOf
110−import androidx.compose.runtime.mutableStateOf
111−import androidx.compose.runtime.produceState
112−import androidx.compose.runtime.remember
113−import androidx.compose.runtime.rememberCoroutineScope
114−import androidx.compose.runtime.rememberUpdatedState
115−import androidx.compose.runtime.saveable.rememberSaveable
116−import androidx.compose.runtime.setValue
117−import androidx.compose.runtime.snapshotFlow
118−import androidx.compose.foundation.text.KeyboardActions
119−import androidx.compose.foundation.text.KeyboardOptions
120−import androidx.compose.ui.text.input.KeyboardCapitalization
121−import androidx.compose.ui.Alignment
122−import androidx.compose.ui.Modifier
123−import androidx.compose.ui.draw.alpha
124−import androidx.compose.ui.draw.clip
125−import androidx.compose.ui.focus.focusRequester
126−import androidx.compose.ui.input.key.Key
127−import androidx.compose.ui.input.key.KeyEventType
128−import androidx.compose.ui.input.key.isCtrlPressed
129−import androidx.compose.ui.input.key.isShiftPressed
130−import androidx.compose.ui.input.key.key
131−import androidx.compose.ui.input.key.onPreviewKeyEvent
132−import androidx.compose.ui.input.key.type
133−import androidx.compose.ui.layout.onSizeChanged
134−import androidx.compose.ui.platform.LocalContext
135−import androidx.compose.ui.platform.LocalDensity
136−import androidx.compose.ui.platform.LocalHapticFeedback
137−import androidx.compose.ui.platform.LocalLayoutDirection
138−import androidx.compose.ui.platform.LocalView
139−import androidx.compose.ui.platform.testTag
140−import androidx.compose.ui.unit.LayoutDirection
141−import androidx.compose.ui.res.pluralStringResource
142−import androidx.compose.ui.res.stringResource
143−import androidx.compose.ui.semantics.Role
144−import androidx.compose.ui.semantics.contentDescription
145−import androidx.compose.ui.semantics.heading
146−import androidx.compose.ui.semantics.liveRegion
147−import androidx.compose.ui.semantics.LiveRegionMode
148−import androidx.compose.ui.semantics.invisibleToUser
149−import androidx.compose.ui.semantics.semantics
150−import androidx.compose.ui.text.input.ImeAction
151−import androidx.compose.ui.text.style.TextOverflow
152−import androidx.compose.ui.unit.dp
153−import androidx.lifecycle.compose.collectAsStateWithLifecycle
154−import androidx.lifecycle.viewmodel.compose.viewModel
155−import kotlinx.coroutines.Dispatchers
156−import kotlinx.coroutines.coroutineScope
157−import kotlinx.coroutines.delay
158−import kotlinx.coroutines.flow.distinctUntilChanged
159−import kotlinx.coroutines.launch
160−import kotlinx.coroutines.withContext
161−import soy.iko.opencode.data.model.Part
162−import soy.iko.opencode.data.model.MessageWithParts
163−import soy.iko.opencode.data.model.AssistantMessage
164−import soy.iko.opencode.data.model.Command
165−import soy.iko.opencode.data.model.ReasoningPart
166−import soy.iko.opencode.data.model.TextPart
167−import soy.iko.opencode.data.model.ToolCompleted
168−import soy.iko.opencode.data.model.ToolError
169−import soy.iko.opencode.data.model.ToolPart
170−import soy.iko.opencode.data.model.ToolRunning
171−import soy.iko.opencode.data.model.FilePart
172−import soy.iko.opencode.data.model.sourcePath
173−import soy.iko.opencode.data.model.inputElement
174−import soy.iko.opencode.data.network.EventStreamClient
175−import soy.iko.opencode.data.network.NetworkConfig
176−import soy.iko.opencode.di.AppContainer
177−import soy.iko.opencode.R
178−import soy.iko.opencode.ui.components.CommandPalette
179−import soy.iko.opencode.ui.components.ConnectionBanner
180−import soy.iko.opencode.ui.components.DiffView
181−import soy.iko.opencode.ui.components.PaletteAction
182−import soy.iko.opencode.ui.components.LocalReducedMotion
183−import soy.iko.opencode.ui.components.LocalSearchHighlight
184−import soy.iko.opencode.ui.components.reducedMotionAnimateItem
185−import soy.iko.opencode.ui.components.copyToClipboard
186−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
187−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
188−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
189−import soy.iko.opencode.ui.components.showToast
190−import soy.iko.opencode.ui.components.toImageContext
191−import soy.iko.opencode.ui.vmFactory
192−import soy.iko.opencode.util.runCatchingCancellable
193−
194−// Optional message id to scroll to and briefly highlight on first load (from global search).
195−// Consumed once: after the message is scrolled into view and highlighted, the focus is
196−// cleared so subsequent recompositions don't re-trigger the scroll.
197−@OptIn(ExperimentalMaterial3Api::class)
198−@Composable
199−fun ChatScreen(
200− container: AppContainer,
201− sessionId: String,
202− onBack: () -> Unit,
203− onOpenFile: ((String) -> Unit)? = null,
204− onOpenSession: ((String) -> Unit)? = null,
205− focusMessageId: String? = null,
206− onEditProfile: ((String) -> Unit)? = null,
207−) {
208− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
209− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
210− val running by vm.running.collectAsStateWithLifecycle()
211− val streamInterrupted by vm.streamInterrupted.collectAsStateWithLifecycle()
212− val aborting by vm.aborting.collectAsStateWithLifecycle()
213− val loading by vm.loading.collectAsStateWithLifecycle()
214− val loadError by vm.loadError.collectAsStateWithLifecycle()
215− val loadErrorInline by vm.loadErrorInline.collectAsStateWithLifecycle()
216− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
217− val models by vm.models.collectAsStateWithLifecycle()
218− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
219− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
220− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
221− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
222− val reconnectAttempts by vm.reconnectAttempts.collectAsStateWithLifecycle()
223− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
224− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
225− val agents by vm.agents.collectAsStateWithLifecycle()
226− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
227− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
228− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
229− val commands by vm.commands.collectAsStateWithLifecycle()
230− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
231− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
232− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
233− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
234− val draft by vm.draft.collectAsStateWithLifecycle()
235− val pendingQuote by vm.pendingQuote.collectAsStateWithLifecycle()
236− val attachments by vm.attachments.collectAsStateWithLifecycle()
237− val reverted by vm.reverted.collectAsStateWithLifecycle()
238− val editing by vm.editing.collectAsStateWithLifecycle()
239− val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
240− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
241− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
242− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
243− val preferredModelId by container.settingsStore.preferredModelId.collectAsStateWithLifecycle(initialValue = "")
244− val recentModelEntries by container.recentModelsStore.entries.collectAsStateWithLifecycle()
245− val compactSpacing by container.settingsStore.compactMessageSpacing.collectAsStateWithLifecycle(initialValue = false)
246− val notifPermission by container.settingsStore.notifPermission.collectAsStateWithLifecycle(initialValue = true)
247− val isOnline by container.isOnline.collectAsStateWithLifecycle()
248− val haptics = LocalHapticFeedback.current
249− val layoutDirection = LocalLayoutDirection.current
250− val scope = rememberCoroutineScope()
251− val shareContext = LocalContext.current
252− val defaultShareSubject = stringResource(R.string.share_subject)
253− val sessionLabel = stringResource(R.string.session)
254− val defaultModelLabel = stringResource(R.string.default_model)
255− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
256− buildString {
257− append(selectedModel?.modelLabel ?: defaultModelLabel)
258− selectedAgent?.let { append(" · $it") }
259− }
260− }
261−
262− // Connection profile (with auth) for rendering inline image attachments.
263− // Collect as state so a server switch recomposes the image context.
264− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
265− val imageContext = remember(activeConnection?.profile) {
266− activeConnection?.profile?.toImageContext()
267− }
268−
269− // Mark this session as read while the user is viewing it; clear on leave so new
270− // background activity can badge it again.
271− DisposableEffect(sessionId) {
272− container.setCurrentSession(sessionId)
273− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
274− }
275−
276− // Navigate away when the session is deleted via SSE so the user isn't left
277− // on a zombie screen showing a conversation that no longer exists. Surface a
278− // toast (not a snackbar) because the screen is about to be popped — a snackbar
279− // would be torn down before the user could read it, while a toast survives.
280− // Covers both SSE-driven deletion (deleted on another device) and a user-
281− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
282− // sets the same flag on success).
283− val deletedContext = LocalContext.current
284− LaunchedEffect(sessionDeleted) {
285− if (sessionDeleted) {
286− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
287− onBack()
288− }
289− }
290−
291− val snackbar = remember { SnackbarHostState() }
292− val retryLabel = stringResource(R.string.retry)
293− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
294− // Dedicated focus requester for the in-conversation search field. The overflow menu's
295− // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
296− // (the composer), so typing went to the composer instead of the search field.
297− val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
298− var showModelPicker by rememberSaveable { mutableStateOf(false) }
299− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
300− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
301− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
302− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
303− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
304− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
305− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
306− var showShellDialog by rememberSaveable { mutableStateOf(false) }
307− var showPalette by rememberSaveable { mutableStateOf(false) }
308− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
309− var searchActive by rememberSaveable { mutableStateOf(false) }
310− var chatSearch by rememberSaveable { mutableStateOf("") }
311− // Index of the currently-focused in-conversation search match (into the filtered list).
312− // Drives the up/down navigation: the search bar's arrows step through matches and scroll
313− // the list to each one, mirroring desktop chat apps (the bare filtered list previously
314− // required reading each message to find the term).
315− var searchPos by rememberSaveable { mutableIntStateOf(0) }
316− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
317− // a confirmation dialog (from both the overflow menu and the command palette).
318− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
319− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
320−
321− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
322− // action list doesn't need a Composable context. Actions map to the same handlers the
323− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
324− val paletteModelLabel = stringResource(R.string.palette_switch_model)
325− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
326− val paletteCommandLabel = stringResource(R.string.palette_run_command)
327− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
328− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
329− val paletteShellLabel = stringResource(R.string.run_shell_command)
330− val paletteActions = remember(
331− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
332− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
333− ) {
334− buildList {
335− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
336− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
337− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
338− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
339− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
340− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
341− }
342− }
343−
344− // Keep the screen awake while the agent is working in *this* session. The foreground
345− // service that holds process priority during a run is managed app-wide off
346− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
347− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
348− // SSE stream before the completion notification fires.
349− val currentView = LocalView.current
350− val appContext = LocalContext.current.applicationContext
351− DisposableEffect(running) {
352− currentView.keepScreenOn = running
353− onDispose { currentView.keepScreenOn = false }
354− }
355−
356− LaunchedEffect(Unit) {
357− vm.errorEvents.collect { event ->
358− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
359− // message-load failure) would silently re-submit the last prompt on tap.
360− val result = if (event.retryable) {
361− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
362− } else {
363− snackbar.showSnackbar(event.message)
364− }
365− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
366− }
367− }
368−
369− // Stop-undo: abort() emits the last-sent prompt here so this collector can show a
370− // "Stopped — Undo" snackbar. Tapping Undo re-sends the prompt, recovering an accidental
371− // Stop without a confirmation dialog (Stop now happens on first tap).
372− val undoStopLabel = stringResource(R.string.undo)
373− val stoppedLabel = stringResource(R.string.run_stopped_undo)
374− LaunchedEffect(Unit) {
375− vm.stopUndoEvents.collect { prompt ->
376− if (prompt != null) {
377− val result = snackbar.showSnackbar(message = stoppedLabel, actionLabel = undoStopLabel)
378− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.resendLastPrompt()
379− }
380− }
381− }
382−
383− // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
384− // window on the container; show the snackbar over the conversation the user is viewing so
385− // they can cancel without being navigated to the session list first. If the window expires
386− // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
387− val undoLabel = stringResource(R.string.undo)
388− val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
389− LaunchedEffect(Unit) {
390− vm.deleteUndoEvents.collect {
391− coroutineScope {
392− val dismisser = launch {
393− delay(NetworkConfig.undoDeleteDelayMs)
394− snackbar.currentSnackbarData?.dismiss()
395− }
396− val result = snackbar.showSnackbar(
397− message = sessionDeletedLabel,
398− actionLabel = undoLabel,
399− duration = SnackbarDuration.Indefinite,
400− )
401− dismisser.cancel()
402− if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
403− }
404− }
405− }
406−
407− // --- Attachments, voice, and share-link plumbing ---
408− val attachFailedMsg = stringResource(R.string.attachment_failed)
409− val noCameraMsg = stringResource(R.string.no_camera_app)
410− val noVoiceMsg = stringResource(R.string.no_voice_app)
411− val voicePrompt = stringResource(R.string.voice_prompt)
412− val linkCopiedMsg = stringResource(R.string.link_copied)
413− val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
414−
415− // Count of picks currently being read + base64-encoded off the main thread, so the
416− // composer can show a staging placeholder immediately (chips only materialize once done).
417− // Backed by the ViewModel (vm.stagingCount / vm.stagingFileTotal) so the staging state
418− // survives a configuration change: the encode work runs on viewModelScope (which
419− // survives rotation), so the counters must live on the VM too — remember { mutableStateOf
420− // } in the composable would reset to 0 on rotation and lose the staging chip mid-encode.
421− val stagingCount by vm.stagingCount.collectAsStateWithLifecycle()
422− val stagingFileTotal by vm.stagingFileTotal.collectAsStateWithLifecycle()
423−
424− // Convert each picked Uri to a base64 attachment on the VM's scope (survives rotation),
425− // honoring the per-prompt count cap and surfacing per-file errors via the VM's errorEvents.
426− fun stageUris(uris: List<Uri>) {
427− vm.stageUris(uris, appContext)
428− }
429−
430− val photoPicker = rememberLauncherForActivityResult(
431− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
432− ) { uris -> stageUris(uris) }
433−
434− val filePicker = rememberLauncherForActivityResult(
435− ActivityResultContracts.GetMultipleContents(),
436− ) { uris -> stageUris(uris) }
437−
438− // Uri survives a config change mid-capture so the TakePicture result still resolves.
439− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
440− val cameraLauncher = rememberLauncherForActivityResult(
441− ActivityResultContracts.TakePicture(),
442− ) { success ->
443− val uri = pendingCaptureUri
444− pendingCaptureUri = null
445− if (success && uri != null) stageUris(listOf(uri))
446− }
447−
448− val voiceLauncher = rememberLauncherForActivityResult(
449− ActivityResultContracts.StartActivityForResult(),
450− ) { result ->
451− if (result.resultCode == Activity.RESULT_OK) {
452− val spoken = result.data
453− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
454− ?.firstOrNull()
455− ?.takeIf { it.isNotBlank() }
456− if (spoken != null) {
457− // Append to the existing draft rather than replacing, so dictation adds to
458− // whatever the user already typed.
459− val current = vm.draft.value
460− val combined = if (current.isBlank()) spoken else "$current $spoken"
461− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
462− }
463− }
464− }
465−
466− fun launchCamera() {
467− val uri = newCameraCaptureUri(appContext)
468− if (uri == null) {
469− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
470− return
471− }
472− pendingCaptureUri = uri
473− runCatching { cameraLauncher.launch(uri) }
474− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
475− }
476−
477− fun launchVoice() {
478− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
479− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
480− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
481− }
482− runCatching { voiceLauncher.launch(intent) }
483− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
484− }
485−
486− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
487− LaunchedEffect(Unit) {
488− vm.shareLinkEvents.collect { url ->
489− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
490− snackbar.showSnackbar(linkCopiedMsg)
491− }
492− }
493−
494− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
495− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
496− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
497− // a dropped branch-navigation event in the gap.
498− val branchedMsg = stringResource(R.string.branch_created)
499− LaunchedEffect(Unit) {
500− vm.branchEvents.collect { newId ->
501− showToast(shareContext, branchedMsg)
502− onOpenSession?.invoke(newId)
503− }
504− }
505−
506− // Stage images shared into the app (via the system share sheet) as attachments.
507− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
508− // while this ChatScreen is already composed — which happens in two-pane mode, where the
509− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
510− // only fire on first composition. consumePendingSharedMedia() atomically drains the
511− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
512− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
513− LaunchedEffect(pendingSharedMedia) {
514− val shared = container.consumePendingSharedMedia()
515− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
516− }
517−
518− fun doSend() {
519− if (vm.send(draft)) {
520− // TextHandleMove (a light tick) is semantically right for a send commit;
521− // LongPress is reserved for long-press/swipe gestures.
522− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
523− }
524− }
525−
526− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
527−
528− Scaffold(
529− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
530− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
531− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
532− // typing (and the composer's own Enter-to-send handling) is untouched.
533− modifier = Modifier.onPreviewKeyEvent { ev ->
534− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
535− when {
536− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
537− // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
538− // the field so the user can type immediately.
539− ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
540− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
541− ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
542− ev.key == Key.Escape && running && !showExitConfirm -> {
543− vm.abort(); true
544− }
545− else -> false
546− }
547− },
548− topBar = {
549− TopAppBar(
550− title = {
551− val changeLabel = stringResource(R.string.change_model_agent)
552− // The subtitle reads "model · agent", so tapping the title offers *both*
553− // — a small menu picks which picker to open. Previously the tap went
554− // straight to the model picker, leaving the agent changeable only via
555− // the overflow menu despite the title implying otherwise.
556− Box {
557− Row(
558− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
559− // node; the click label rides on `clickable` (onClickLabel) instead of
560− // an explicit contentDescription, which would have SUPPRESSED the child
561− // Texts and announced only "Change model and agent".
562− modifier = Modifier
563− .clickable(
564− role = Role.Button,
565− onClickLabel = changeLabel,
566− ) { showTitleMenu = true }
567− .semantics(mergeDescendants = true) {},
568− verticalAlignment = Alignment.CenterVertically,
569− ) {
570− Column(modifier = Modifier.weight(1f, fill = false)) {
571− // maxLines=1 + Ellipsis so a long session title can't wrap and
572− // push the top bar to multiple lines, shifting the whole layout.
573− Text(
574− sessionTitle ?: sessionLabel,
575− maxLines = 1,
576− overflow = TextOverflow.Ellipsis,
577− )
578− Text(
579− subtitle,
580− style = MaterialTheme.typography.labelSmall,
581− color = MaterialTheme.colorScheme.onSurfaceVariant,
582− maxLines = 1,
583− overflow = TextOverflow.Ellipsis,
584− )
585− }
586− // Always show the affordance so the title reads as tappable even when
587− // the model catalog failed to load (models empty). Without it the title
588− // is indistinguishable from plain text and the pickers are effectively
589− // undiscoverable — and the dropdown items already disable themselves
590− // while a catalog is loading or unavailable.
591− Icon(
592− Icons.Filled.KeyboardArrowDown,
593− contentDescription = null,
594− tint = MaterialTheme.colorScheme.onSurfaceVariant,
595− modifier = Modifier.size(20.dp),
596− )
597− }
598− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
599− DropdownMenuItem(
600− text = { Text(stringResource(R.string.palette_switch_model)) },
601− enabled = !modelsLoading || models.isNotEmpty(),
602− onClick = { showTitleMenu = false; showModelPicker = true },
603− )
604− DropdownMenuItem(
605− text = { Text(stringResource(R.string.palette_choose_agent)) },
606− enabled = !agentsLoading || agents.isNotEmpty(),
607− onClick = { showTitleMenu = false; showAgentPicker = true },
608− )
609− }
610− }
611− },
612− navigationIcon = {
613− IconButton(onClick = {
614− if (running) showExitConfirm = true else onBack()
615− }) {
616− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
617− }
618− },
619− actions = {
620− // At-a-glance run status in the top bar. When the user is scrolled
621− // up (jump-to-latest FAB visible), the input-bar Stop button and the
622− // trailing "working…" row are off-screen, so a top-bar spinner is the
623− // only signal the agent is still working.
624− if (running) {
625− val workingLabel = stringResource(R.string.working)
626− CircularProgressIndicator(
627− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
628− strokeWidth = 2.dp,
629− )
630− }
631− // Manual refresh: forces an SSE reconnect, which re-seeds messages
632− // from REST. A recovery path when the stream silently drops and the
633− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
634− // immediate tap feedback — the SSE reconnect may not visibly change
635− // the connection state when already Connected, so without it the tap
636− // appears to do nothing. Disabled while a run is active: a mid-run
637− // refresh forces a reconnect that can interrupt the streaming reply,
638− // and the working spinner already signals "wait" — the recovery path
639− // is only needed when nothing is actively streaming.
640− val refreshLabel = stringResource(R.string.refresh)
641− IconButton(
642− onClick = { vm.refreshMessages() },
643− enabled = activeConnection != null && !refreshing && !running,
644− ) {
645− if (refreshing) {
646− CircularProgressIndicator(
647− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
648− strokeWidth = 2.dp,
649− )
650− } else {
651− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
652− }
653− }
654− // Overflow menu consolidates the less-frequent actions (share,
655− // commands, agent, model, rename, delete) so the top bar stays
656− // scannable on narrow phones — previously 5 icons crowded the bar
657− // alongside the back button and tappable title. Catalog-loading
658− // spinners stay inline (next to the overflow) so a load state is
659− // visible without opening the menu.
660− val moreLabel = stringResource(R.string.more)
661− val loadingLabel = stringResource(R.string.loading)
662− val shareLabel = stringResource(R.string.share_conversation)
663− val copyAsMarkdownLabel = stringResource(R.string.copy_as_markdown)
664− val shareAsJsonLabel = stringResource(R.string.share_as_json)
665− val copyAsJsonLabel = stringResource(R.string.copy_as_json)
666− val commandsLabel = stringResource(R.string.commands)
667− val renameLabel = stringResource(R.string.rename_session_chat)
668− val deleteLabel = stringResource(R.string.delete_session_chat)
669− val createShareLabel = stringResource(R.string.create_share_link)
670− val copyShareLabel = stringResource(R.string.copy_share_link)
671− val stopShareLabel = stringResource(R.string.stop_sharing)
672− val summarizeLabel = stringResource(R.string.summarize_conversation)
673− val initLabel = stringResource(R.string.generate_agents_md)
674− val shellLabel = stringResource(R.string.run_shell_command)
675− Box {
676− IconButton(onClick = { showOverflowMenu = true }) {
677− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
678− }
679− DropdownMenu(
680− expanded = showOverflowMenu,
681− onDismissRequest = { showOverflowMenu = false },
682− ) {
683− DropdownMenuItem(
684− text = { Text(shareLabel) },
685− enabled = hasMessages,
686− onClick = {
687− showOverflowMenu = false
688− scope.launch {
689− val md = withContext(Dispatchers.Default) {
690− buildConversationMarkdown(vm.messages.value, sessionTitle)
691− }
692− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
693− type = "text/markdown"
694− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
695− putExtra(android.content.Intent.EXTRA_TEXT, md)
696− }
697− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
698− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
699− }
700− },
701− )
702− // Copy the whole conversation as Markdown to the clipboard, so a
703− // user can paste into another app without the share-sheet round-trip.
704− DropdownMenuItem(
705− text = { Text(copyAsMarkdownLabel) },
706− enabled = hasMessages,
707− onClick = {
708− showOverflowMenu = false
709− scope.launch {
710− val md = withContext(Dispatchers.Default) {
711− buildConversationMarkdown(vm.messages.value, sessionTitle)
712− }
713− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), md)
714− }
715− },
716− )
717− // Lossless JSON share: the full List<MessageWithParts> serialized with
718− // the shared OpencodeJson, so tool outputs, file sources, and reasoning
719− // survive verbatim (the Markdown export truncates/summarizes them).
720− DropdownMenuItem(
721− text = { Text(shareAsJsonLabel) },
722− enabled = hasMessages,
723− onClick = {
724− showOverflowMenu = false
725− scope.launch {
726− val json = withContext(Dispatchers.Default) {
727− buildConversationJson(vm.messages.value)
728− }
729− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
730− type = "application/json"
731− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
732− putExtra(android.content.Intent.EXTRA_TEXT, json)
733− }
734− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareAsJsonLabel)) }
735− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
736− }
737− },
738− )
739− DropdownMenuItem(
740− text = { Text(copyAsJsonLabel) },
741− enabled = hasMessages,
742− onClick = {
743− showOverflowMenu = false
744− scope.launch {
745− val json = withContext(Dispatchers.Default) {
746− buildConversationJson(vm.messages.value)
747− }
748− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), json)
749− }
750− },
751− )
752− DropdownMenuItem(
753− text = { Text(commandsLabel) },
754− enabled = !commandsLoading || commands.isNotEmpty(),
755− onClick = { showOverflowMenu = false; showCommandPicker = true },
756− )
757− DropdownMenuItem(
758− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
759− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
760− )
761− DropdownMenuItem(
762− text = { Text(stringResource(R.string.find_in_conversation)) },
763− onClick = {
764− showOverflowMenu = false
765− searchActive = true
766− // Focus is requested by the LaunchedEffect(searchActive)
767− // below, which waits for the search field to be composed
768− // before requesting focus (calling requestFocus here would
769− // target a field that isn't in the composition yet).
770− },
771− )
772− androidx.compose.material3.HorizontalDivider()
773− // Session sharing: create a public link, copy an existing one, or revoke it.
774− if (shareUrl == null) {
775− DropdownMenuItem(
776− text = { Text(createShareLabel) },
777− enabled = hasMessages,
778− onClick = { showOverflowMenu = false; vm.shareSession() },
779− )
780− } else {
781− DropdownMenuItem(
782− text = { Text(copyShareLabel) },
783− onClick = {
784− showOverflowMenu = false
785− shareUrl?.let {
786− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
787− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
788− }
789− },
790− )
791− DropdownMenuItem(
792− text = { Text(stopShareLabel) },
793− onClick = { showOverflowMenu = false; vm.unshareSession() },
794− )
795− }
796− DropdownMenuItem(
797− text = { Text(summarizeLabel) },
798− enabled = hasMessages && !running,
799− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
800− )
801− DropdownMenuItem(
802− text = { Text(initLabel) },
803− enabled = !running,
804− onClick = { showOverflowMenu = false; showInitConfirm = true },
805− )
806− DropdownMenuItem(
807− text = { Text(shellLabel) },
808− enabled = !running,
809− onClick = { showOverflowMenu = false; showShellDialog = true },
810− )
811− androidx.compose.material3.HorizontalDivider()
812− DropdownMenuItem(
813− text = { Text(renameLabel) },
814− onClick = { showOverflowMenu = false; showRenameDialog = true },
815− )
816− DropdownMenuItem(
817− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
818− onClick = { showOverflowMenu = false; showDeleteDialog = true },
819− )
820− }
821− // While a catalog is initially loading (empty list + loading flag),
822− // show a tiny inline spinner beside the overflow so the user can see
823− // a load is in progress without opening the menu. Once loaded the
824− // spinner disappears; the menu items are always enabled (tapping a
825− // picker with no items shows the "no models/agents/commands" state).
826− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
827− (agentsLoading && agents.isEmpty()) ||
828− (modelsLoading && models.isEmpty())
829− if (catalogLoading) {
830− CircularProgressIndicator(
831− Modifier
832− .align(Alignment.TopEnd)
833− .size(10.dp)
834− .semantics { contentDescription = loadingLabel },
835− strokeWidth = 1.dp,
836− )
837− }
838− }
839− },
840− )
841− },
842− snackbarHost = { SnackbarHost(snackbar) },
843− bottomBar = {
844− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
845− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
846− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
847− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
848− Column {
849− // Pinned above the composer so the agent's plan and progress stay visible
850− // while scrolled up mid-run; renders nothing when there's no plan.
851− TodoPlanBar(todoPlan)
852− val bannerMotion = rememberVisibilityTransitions()
853− AnimatedVisibility(
854− visible = reverted,
855− enter = bannerMotion.enter,
856− exit = bannerMotion.exit,
857− ) {
858− RevertBanner(
859− diff = revertDiff,
860− isEditing = editing,
861− onUndo = { vm.unrevert() },
862− )
863− }
864− AnimatedVisibility(
865− visible = queuedOffline.isNotEmpty(),
866− enter = bannerMotion.enter,
867− exit = bannerMotion.exit,
868− ) {
869− OutboxBanner(
870− count = queuedOffline.size,
871− sending = outboxSending,
872− onFlush = { vm.flushQueued() },
873− onDiscard = { vm.discardAllQueued() },
874− )
875− }
876− AnimatedVisibility(
877− visible = pendingQuote != null,
878− enter = bannerMotion.enter,
879− exit = bannerMotion.exit,
880− ) {
881− pendingQuote?.let { QuoteReplyBanner(it, onCancel = { vm.cancelQuoteReply() }) }
882− }
883− ChatInputBar(
884− value = draft,
885− onValueChange = vm::updateDraft,
886− running = running,
887− aborting = aborting,
888− enabled = activeConnection != null,
889− sendOnEnter = sendOnEnter,
890− onSend = ::doSend,
891− onAbort = { vm.abort() },
892− queuedFollowUp = queuedFollowUp,
893− onQueueFollowUp = vm::queueFollowUp,
894− onCancelQueue = { vm.queueFollowUp("") },
895− focusRequester = inputFocusRequester,
896− attachments = attachments,
897− staging = stagingCount > 0,
898− stagingFileCount = stagingFileTotal,
899− onRemoveAttachment = vm::removeAttachment,
900− onPickPhoto = {
901− photoPicker.launch(
902− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
903− )
904− },
905− onPickFile = { filePicker.launch("*/*") },
906− onCamera = { launchCamera() },
907− onVoice = { launchVoice() },
908− onPasteImage = { stageUris(it) },
909− commands = commands,
910− onRunCommand = { cmd ->
911− vm.runCommand(cmd)
912− // Clear the draft so the typed /prefix doesn't linger after the
913− // command fires (the command picker confirmation, if any, is
914− // handled inside runCommand).
915− vm.updateDraft("")
916− },
917− )
918− }
919− },
920− ) { padding ->
921− // Collect messages inside the content lambda so streaming token updates
922− // recompose only this subtree, not the top bar / input bar / 20+ other
923− // state reads in the ChatScreen body.
924− val messages by vm.messages.collectAsStateWithLifecycle()
925− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
926− val listState = rememberLazyListState()
927− val contentScope = rememberCoroutineScope()
928− val timeTick = rememberRelativeTimeTick()
929− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
930− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
931− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
932− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
933− androidx.compose.runtime.LaunchedEffect(listState) {
934− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
935− .distinctUntilChanged()
936− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
937− } // Group messages by day and interleave date separators so a long conversation
938− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
939− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
940− // outside the PullToRefreshBox so the auto-scroll effects below can reference
941− // the same list the LazyColumn renders (separators shift the indices vs. the
942− // raw messages list, so scroll targets must be in listItems space).
943− val todayLabel = stringResource(R.string.today)
944− val yesterdayLabel = stringResource(R.string.yesterday)
945− // In-conversation search: when active, narrow to messages whose text contains the query.
946− // Computed on the filtered set so day separators still align with the visible messages.
947− // Debounced + off-main-thread so a keystroke-by-keystroke filter walk over a long
948− // conversation (with many tool parts whose state stringification is non-trivial)
949− // doesn't jank the UI. produceState yields the empty list immediately and publishes
950− // the filtered result once the debounce settles.
951− val searchQuery = chatSearch.trim()
952− // When no search is active, skip the produceState indirection entirely and use the
953− // messages list directly. produceState keyed on (messages, searchQuery) re-launches
954− // its coroutine on every messages emission (every streamed token) even when the
955− // query is empty — the body just re-assigns `value = messages`, but the coroutine
956− // churn (launch + cancel + state write) ~20x/sec is pure overhead. Using `messages`
957− // directly when there's no search avoids that, and `buildMessageListItems` keys its
958− // own remember on the resulting list identity either way.
959− val searchMessages: List<MessageWithParts> = if (searchQuery.isEmpty()) {
960− messages
961− } else {
962− // Capture the messages list via rememberUpdatedState so the latest list is read
963− // when the debounce completes, WITHOUT re-launching the produceState coroutine on
964− // every messages emission. Keying produceState on `messages` restarts the debounce
965− // delay from zero on every streamed token (~20×/sec); if tokens arrive faster than
966− // the debounce interval the filter never runs and search shows "no matches" for the
967− // entire run. Keying only on `searchQuery` lets the debounce settle once per query
968− // while still filtering against the most recent list.
969− val currentMessages by rememberUpdatedState(messages)
970− val filtered by produceState(
971− initialValue = emptyList(),
972− searchQuery,
973− ) {
974− // Debounce: wait for the user to stop typing before running the filter,
975− // so each keystroke doesn't kick off a fresh scan.
976− kotlinx.coroutines.delay(NetworkConfig.chatSearchDebounceMs)
977− // Run the filter off the main thread — the walk stringifies tool state
978− // and scans every part of every message, which is non-trivial work for a
979− // long conversation.
980− value = withContext(Dispatchers.Default) {
981− currentMessages.filter { m ->
982− m.parts.any { p ->
983− when (p) {
984− is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
985− is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
986− is ToolPart -> {
987− // Match the tool name plus its running/completed/error text and the
988− // stringified input, so searching for an error string or a file the
989− // tool touched actually finds the message it appeared in.
990− p.tool.contains(searchQuery, ignoreCase = true) ||
991− (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
992− (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
993− p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
994− (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
995− p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
996− }
997− is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
998− p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
999− else -> false
1000− }
1001− }
1002− }
1003− }
1004− }
1005− filtered
1006− }
1007− // Keep the focused-match index in range as the query (and thus the match set) changes.
1008− // A new query resets to the first match (keyed on searchQuery alone so any change —
1009− // even one that still yields enough matches — jumps to index 0 rather than carrying
1010− // the old index over to a semantically unrelated message). A shrunk set clamps to
1011− // the last valid index (keyed on size so a content refresh that shrinks the matches
1012− // without a query change doesn't leave searchPos out of range).
1013− LaunchedEffect(searchQuery) {
1014− searchPos = 0
1015− }
1016− LaunchedEffect(searchMessages.size) {
1017− if (searchPos >= searchMessages.size) searchPos = 0
1018− }
1019− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
1020− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
1021− }
1022− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
1023− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
1024− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
1025− // would capture the first composition's list — which is empty, since `messages`
1026− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
1027− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
1028− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
1029− // whose value tracks the latest list.
1030− val currentListItems by rememberUpdatedState(listItems)
1031−
1032− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
1033− // while the user was scrolled away from the bottom, cleared once they return. A count
1034− // (vs. a bare dot) tells the user how much they missed at a glance.
1035− var newContentCount by remember { mutableIntStateOf(0) }
1036−
1037− val isPinnedToBottom by remember {
1038− derivedStateOf {
1039− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1040− // When a run is active, the LazyColumn has one trailing "__typing"
1041− // item after the last list item. Account for it so "pinned to bottom"
1042− // includes the working indicator — otherwise the pin check targets
1043− // listItems.lastIndex, the typing row sits just below the viewport,
1044− // and the user never sees the progress indicator even when pinned.
1045− val items = currentListItems
1046− val effectiveLast = if (running) items.size else items.lastIndex
1047− lastVisible >= effectiveLast || items.isEmpty()
1048− }
1049− }
1050−
1051− // Jump to the newest message once, when the conversation first loads. Guarded by a
1052− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1053− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1054− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1055− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1056− LaunchedEffect(listItems.isNotEmpty()) {
1057− if (listItems.isNotEmpty() && !didInitialScroll) {
1058− // When a run is active the LazyColumn has a trailing "__typing" row at
1059− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1060− // running session lands truly pinned to bottom and streaming auto-scroll engages.
1061− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1062− didInitialScroll = true
1063− }
1064− }
1065−
1066− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1067− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1068− // isPinnedToBottom check flips to false the instant you send — freezing
1069− // auto-scroll. If the user was pinned to the last item just before the run
1070− // began, bring the typing row into view so the pin (and streaming follow) is
1071− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1072− // recomputed to false by now) so we don't scroll when the user had scrolled up.
1073− LaunchedEffect(running) {
1074− if (running && listItems.isNotEmpty()) {
1075− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1076− if (lastVisible >= listItems.lastIndex) {
1077− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1078− }
1079− }
1080− }
1081−
1082− // Scroll the focused search match into view whenever the user steps through results with
1083− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1084− // includes date separators) and animates there.
1085− LaunchedEffect(searchPos, searchQuery, listItems) {
1086− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1087− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1088− val index = listItems.indexOfFirst {
1089− it is MessageListItem.Message && it.message.info.id == target.info.id
1090− }
1091− if (index >= 0) runCatchingCancellable { listState.animateScrollToItem(index) }
1092− }
1093−
1094− // Global-search deep link: scroll to and briefly highlight the matched message. The
1095− // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1096− // clears itself after a short delay so the user can re-read the surrounding context
1097− // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1098− var focusedMessageId by remember(focusMessageId) { mutableStateOf(focusMessageId) }
1099− LaunchedEffect(focusedMessageId, listItems) {
1100− val focus = focusedMessageId ?: return@LaunchedEffect
1101− if (listItems.isEmpty()) return@LaunchedEffect
1102− val index = listItems.indexOfFirst {
1103− it is MessageListItem.Message && it.message.info.id == focus
1104− }
1105− if (index < 0) return@LaunchedEffect
1106− runCatchingCancellable { listState.animateScrollToItem(index) }
1107− kotlinx.coroutines.delay(2500)
1108− focusedMessageId = null
1109− }
1110−
1111− // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1112− // latest reply stays visible as the composer rises. Without this the IME can obscure the
1113− // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1114− // @Composable property, so we read it inside a snapshotFlow registered in the composable
1115− // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1116− val density = androidx.compose.ui.platform.LocalDensity.current
1117− var wasImeOpen by remember { mutableStateOf(false) }
1118− val imeBottomPx = WindowInsets.ime.getBottom(density)
1119− androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1120− if (listItems.isEmpty()) return@LaunchedEffect
1121− val imeOpen = imeBottomPx > 0
1122− // Scroll to bottom only on the open transition (not close) and only when the user
1123− // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1124− val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1125− if (shouldScroll) {
1126− runCatchingCancellable {
1127− listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1128− }
1129− }
1130− wasImeOpen = imeOpen
1131− }
1132−
1133− LaunchedEffect(Unit) {
1134− var prevSize = 0
1135− var prevLen = 0
1136− snapshotFlow {
1137− // Track list size + the streaming length of the last part so we auto-scroll
1138− // as content arrives, plus the pinned flag. A small data class with primitive
1139− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1140− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1141− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1142− // and tool output — not just TextPart — keeps a pinned view following a long
1143− // reasoning/tool block while it streams (previously it stalled at 0).
1144− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1145− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1146− }.collect { signal ->
1147− if (signal.pinned) {
1148− // Back at the bottom: clear the new-content badge.
1149− newContentCount = 0
1150− if (signal.size > 0) {
1151− // Scroll to the effective last index, including the trailing
1152− // "__typing" row when a run is active so the working indicator
1153− // is brought into view (not just the last message).
1154− val items = currentListItems
1155− val target = if (running) items.size else items.lastIndex
1156− listState.scrollToItem(target)
1157− }
1158− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1159− // Content arrived while scrolled up — increment the jump-to-latest badge.
1160− // Only count whole new items (not per-token growth) so the number reflects
1161− // new messages, not a token count.
1162− if (signal.size > prevSize) newContentCount += signal.size - prevSize
1163− else if (newContentCount == 0) newContentCount = 1
1164− }
1165− prevSize = signal.size
1166− prevLen = signal.lastTextLength
1167− }
1168− }
1169−
1170− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1171− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1172− // content padding accounts for the bottomBar's raised height, so the message
1173− // list is already above the keyboard. Adding imePadding here would double-apply
1174− // the IME inset and push messages too far up.
1175− //
1176− // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1177− // message list on wide screens instead of floating at the screen edges — on a
1178− // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1179− // The horizontal margin below is applied to the FAB/search containers so they
1180− // track the list's left/right edges.
1181− androidx.compose.foundation.layout.BoxWithConstraints(
1182− modifier = Modifier.fillMaxSize().padding(padding),
1183− ) {
1184− val screenMaxWidth = maxWidth
1185− val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1186− // Horizontal margin between the capped list's edge and the screen edge (0 on
1187− // screens narrower than the cap). Applied as start/end padding so the FABs and
1188− // search bar sit at the list's edges, not the screen's.
1189− val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1190− if (activeConnection == null) {
1191− Column(
1192− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1193− horizontalAlignment = Alignment.CenterHorizontally,
1194− ) {
1195− Text(
1196− stringResource(R.string.not_connected),
1197− color = MaterialTheme.colorScheme.error,
1198− )
1199− Spacer(Modifier.size(12.dp))
1200− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1201− if (reconnecting) {
1202− CircularProgressIndicator(
1203− Modifier.size(20.dp),
1204− color = MaterialTheme.colorScheme.onPrimary,
1205− strokeWidth = 2.dp,
1206− )
1207− } else {
1208− Text(stringResource(R.string.reconnect))
1209− }
1210− }
1211− }
1212− } else {
1213− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1214− // Measure the banner's actual height instead of hardcoding 44dp. At large
1215− // accessibility font scales the banner's labelMedium text + spinner + Retry
1216− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1217− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1218− // fires while the banner is composed (visible), so gate the inset on
1219− // bannerVisible and fall back to 44dp until the first measurement arrives.
1220− var bannerHeightPx by remember { mutableIntStateOf(0) }
1221− // Track the search bar height so the list's top padding can grow when search
1222− // is active — otherwise a scrolled-to match lands at index 0, hidden behind
1223− // the floating search bar (the "scroll-under-the-search-bar" bug).
1224− var searchbarHeightPx by remember { mutableIntStateOf(0) }
1225− val density = LocalDensity.current
1226− val topPad = if (bannerVisible) {
1227− if (bannerHeightPx > 0) {
1228− with(density) { bannerHeightPx.toDp() } + 4.dp
1229− } else {
1230− 44.dp
1231− }
1232− } else {
1233− 16.dp
1234− } + if (searchActive && searchbarHeightPx > 0) {
1235− with(density) { searchbarHeightPx.toDp() } + 4.dp
1236− } else {
1237− 0.dp
1238− }
1239− ConnectionBanner(
1240− state = connectionState,
1241− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1242− isOnline = isOnline,
1243− // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1244− // re-seeds from REST). refreshMessages is the right recovery path
1245− // when the connection is present but the stream died; reconnect()
1246− // is the path when the whole connection is gone (handled by the
1247− // separate "Not connected" state below).
1248− onRetry = { vm.refreshMessages() },
1249− // On an auth failure (401/403), retrying with the same bad credentials
1250− // is futile — offer a one-tap path to edit the active profile's
1251− // credentials instead of making the user hunt for the server list.
1252− onEditCredentials = {
1253− val profileId = activeConnection?.profile?.id
1254− if (profileId != null) onEditProfile?.invoke(profileId)
1255− },
1256− reconnectAttempts = reconnectAttempts,
1257− )
1258− // Persistent inline error banner for a mid-conversation load failure.
1259− // Unlike the one-shot snackbar (which fires once per streak then goes
1260− // silent), this stays visible until the stream recovers, so a persistent
1261− // outage doesn't read as "everything is fine" after the snackbar dismisses.
1262− // Anchored at the top, below the connection banner, so it doesn't overlap
1263− // the message list.
1264− if (loadErrorInline && hasMessages) {
1265− Surface(
1266− color = MaterialTheme.colorScheme.errorContainer,
1267− shape = MaterialTheme.shapes.small,
1268− modifier = Modifier
1269− .align(Alignment.TopCenter)
1270− .padding(top = if (bannerVisible) topPad else 8.dp)
1271− .padding(horizontal = 16.dp)
1272− .semantics { liveRegion = LiveRegionMode.Polite },
1273− ) {
1274− Row(
1275− modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1276− verticalAlignment = Alignment.CenterVertically,
1277− horizontalArrangement = Arrangement.spacedBy(8.dp),
1278− ) {
1279− Icon(
1280− Icons.Filled.ErrorOutline,
1281− contentDescription = null,
1282− modifier = Modifier.size(16.dp),
1283− tint = MaterialTheme.colorScheme.onErrorContainer,
1284− )
1285− Text(
1286− stringResource(R.string.load_error_persistent),
1287− style = MaterialTheme.typography.labelMedium,
1288− color = MaterialTheme.colorScheme.onErrorContainer,
1289− modifier = Modifier.weight(1f),
1290− )
1291− TextButton(
1292− onClick = { vm.refreshMessages() },
1293− contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1294− ) {
1295− Text(stringResource(R.string.retry))
1296− }
1297− }
1298− }
1299− }
1300− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1301− // recovery is a swipe away everywhere — not just when the message list is
1302− // populated. Previously PTR was only around the populated list, leaving the
1303− // error/loading states reachable only via a button tap.
1304− PullToRefreshBox(
1305− isRefreshing = refreshing,
1306− // Suppress the refresh action while a run is active: a mid-stream
1307− // refresh forces an SSE reconnect that can interrupt the actively
1308− // streaming reply (matching the top-bar refresh button, which is
1309− // also disabled while running). The pull gesture still responds, but
1310− // the release no-ops instead of triggering a disruptive re-seed.
1311− onRefresh = { if (!running) vm.refreshMessages() },
1312− // Cap width and center on large screens for readability — full-width
1313− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1314− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1315− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1316− ) {
1317− // Reserve top space when the banner is visible so it doesn't overlap the
1318− // first message / state content. (topPad computed above.)
1319− if (loading && messages.isEmpty()) {
1320− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1321− // than a bare centered spinner and the first real messages pop into an
1322− // already-shaped list instead of a blank-then-pop.
1323− ChatSkeleton(topPad = topPad)
1324− } else if (loadError && messages.isEmpty()) {
1325− // A failed load with nothing to show. Distinct from the empty
1326− // conversation state below — the conversation isn't empty, it
1327− // failed to load, and offering "Start a conversation" here is
1328− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1329− Column(
1330− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1331− horizontalAlignment = Alignment.CenterHorizontally,
1332− ) {
1333− Text(
1334− stringResource(R.string.load_messages_failed),
1335− color = MaterialTheme.colorScheme.error,
1336− )
1337− Spacer(Modifier.size(12.dp))
1338− Button(onClick = { vm.refreshMessages() }) {
1339− Text(stringResource(R.string.retry))
1340− }
1341− // When the VM's retryWhen loop is actively retrying (loading is true
1342− // on top of the error state), surface a small "retrying…" indicator so
1343− // the user knows the system is working — without it, the static error
1344− // + Retry button reads as "broken, tap to fix", and the user may not
1345− // realize an automatic retry is already in progress.
1346− if (loading) {
1347− Spacer(Modifier.size(12.dp))
1348− val retryingLabel = stringResource(R.string.retrying_ellipsis)
1349− Row(verticalAlignment = Alignment.CenterVertically) {
1350− CircularProgressIndicator(
1351− Modifier.size(14.dp),
1352− strokeWidth = 2.dp,
1353− )
1354− Text(
1355− retryingLabel,
1356− style = MaterialTheme.typography.labelSmall,
1357− color = MaterialTheme.colorScheme.onSurfaceVariant,
1358− modifier = Modifier.padding(start = 6.dp),
1359− )
1360− }
1361− }
1362− }
1363− } else if (messages.isEmpty() && running) {
1364− // A run just started but no parts have arrived yet — the empty list with
1365− // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1366− // from the initial-load branch so the perceived start latency is lower and
1367− // the first real assistant part pops into an already-shaped list.
1368− ChatSkeleton(topPad = topPad)
1369− } else if (messages.isEmpty()) {
1370− EmptyConversation(
1371− onSuggestion = {
1372− vm.updateDraft(it)
1373− // Focus the input so the user can edit the suggestion before
1374− // sending, instead of having to manually tap the field.
1375− runCatching { inputFocusRequester.requestFocus() }
1376− },
1377− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1378− )
1379− } else {
1380− val lastMessageId = messages.lastOrNull()?.info?.id
1381− // Text-to-speech for reading assistant replies aloud; shuts down when the
1382− // message list leaves composition.
1383− val tts = rememberTtsController()
1384− val speakingMessageId by tts.speakingId
1385− val ttsState by tts.state
1386− // Provide the in-conversation search query to the markdown renderer so matching
1387− // text spans are highlighted in-place (in addition to the focused-row highlight
1388− // above). Scoped to the list so cleared search stops highlighting immediately.
1389− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1390− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1391− LazyColumn(
1392− state = listState,
1393− modifier = Modifier.fillMaxSize(),
1394− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1395− // never floats over the last message. Top padding grows when the
1396− // connection banner is visible so it doesn't overlap the first message.
1397− contentPadding = PaddingValues(
1398− start = 16.dp,
1399− top = topPad,
1400− end = 16.dp,
1401− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1402− ),
1403− // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1404− // more conversation on screen without scrolling as much.
1405− verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1406− ) {
1407− items(
1408− items = listItems,
1409− key = { it.key },
1410− contentType = { it.contentType },
1411− ) { item ->
1412− // When in-conversation search is stepping through matches, highlight the
1413− // focused one's row so the user can spot it at a glance among the filtered
1414− // results (full in-text term highlighting would require threading the query
1415− // through the markdown renderer; the row highlight + scroll-to-match covers
1416− // the navigation use case desktop chat apps solve with next/prev).
1417− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1418− searchMessages.getOrNull(searchPos)?.info?.id
1419− } else null
1420− val isFocusedMatch = focusedMatchId != null &&
1421− item is MessageListItem.Message &&
1422− item.message.info.id == focusedMatchId
1423− // Default placement animation so inserted/moved rows glide in. Skipped
1424− // entirely under reduced motion so a streaming message growing in place
1425− // doesn't animate on every token (and respects the a11y preference).
1426− Box(
1427− Modifier
1428− .then(reducedMotionAnimateItem())
1429− .then(
1430− if (isFocusedMatch) {
1431− Modifier.background(
1432− MaterialTheme.colorScheme.secondaryContainer,
1433− MaterialTheme.shapes.medium,
1434− )
1435− } else {
1436− Modifier
1437− },
1438− ),
1439− ) {
1440− when (item) {
1441− is MessageListItem.Separator -> DateSeparator(item.label)
1442− is MessageListItem.Message -> {
1443− val message = item.message
1444− val messageId = message.info.id
1445− // Only the last (streaming) message needs isRunning — it drives the
1446− // reasoning-block spinner. Passing the live flag to every bubble
1447− // makes all visible messages recompose whenever a run starts or stops.
1448− val modelLabel = remember(message.info, models) {
1449− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1450− ?.let { resolveModelLabel(it, models) }
1451− }
1452− // Key agentLabel/quoteText on the message id (not message.parts) so
1453− // the streaming message — whose `parts` list is replaced on every
1454− // token — doesn't re-run filterIsInstance per token for these two
1455− // derived labels. For a non-streaming message, `message.parts` is
1456− // reference-stable anyway, so this is equivalent. For the streaming
1457− // message the label updates as parts change via the message.info/
1458− // parts reference change below — keyed on messageId + a parts-hash
1459− // is overkill; agentLabel/quoteText only need to reflect the latest
1460− // parts, and `remember(messageId, message.parts)` would re-key per
1461− // token. Instead key on `messageId` alone and accept that the label
1462− // lags by one recomposition for the streaming bubble (it stabilizes
1463− // once the stream finishes). This is invisible in practice: agent
1464− // label is set on the first part, quote text grows with text parts
1465− // but is only consumed on a swipe (user-initiated, post-stream).
1466− val agentLabel = remember(messageId, message.parts) {
1467− message.parts
1468− .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1469− .firstOrNull { it.name.isNotBlank() }?.name
1470− }
1471− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1472− // image/code-only messages, which then opt out of the swipe gesture.
1473− val quoteText = remember(messageId, message.parts) {
1474− message.parts
1475− .filterIsInstance<TextPart>()
1476− .joinToString("\n\n") { it.text }
1477− .trim()
1478− .takeIf { it.isNotEmpty() }
1479− }
1480− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1481− // snapping back (the message isn't dismissed — the quote fills the composer).
1482− // Enabled for non-text messages too (image/tool-only), but the confirm
1483− // callback gives a haptic without triggering reply — so the user gets a
1484− // perceptible "can't quote this" signal instead of a silently dead gesture.
1485− val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1486− val undoLabel = stringResource(R.string.undo)
1487− val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1488− // Memoize the swipe confirmValueChange lambda on the message id + quoteText
1489− // so it's stable across recompositions (a fresh lambda would force the
1490− // SwipeToDismissBox to re-instantiate its state capture). quoteText is a
1491− // derived value that's stable for non-streaming messages.
1492− val swipeState = rememberSwipeToDismissBoxState(
1493− confirmValueChange = remember(messageId, quoteText) {
1494− { value ->
1495− val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1496− SwipeToDismissBoxValue.EndToStart
1497− } else {
1498− SwipeToDismissBoxValue.StartToEnd
1499− }
1500− if (value == replyValue) {
1501− if (quoteText != null) {
1502− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1503− vm.quoteReply(quoteText)
1504− runCatching { inputFocusRequester.requestFocus() }
1505− scope.launch {
1506− val res = snackbar.showSnackbar(
1507− message = quoteReplyLabel,
1508− actionLabel = undoLabel,
1509− )
1510− if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1511− vm.cancelQuoteReply()
1512− }
1513− }
1514− } else {
1515− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1516− scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1517− }
1518− }
1519− false
1520− }
1521− },
1522− )
1523− // In RTL locales, mirror the swipe direction so the reply
1524− // gesture reads naturally (swipe from the trailing edge
1525− // toward the leading edge), matching how LTR users swipe
1526− // left-to-right. Without this, RTL users had no reply swipe.
1527− val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1528− // Memoize every MessageBubble lambda on the message id so a recomposition
1529− // triggered by a sibling (e.g. the streaming message's parts changing,
1530− // which gives `listItems` a new identity) doesn't allocate fresh lambdas
1531− // for the unchanged bubbles. MessageBubble is non-skippable (it takes
1532− // many `(() -> Unit)?` params, which Compose treats as unstable), so
1533− // without memoization every visible bubble recomposes on every token,
1534− // defeating the @Immutable MessageWithParts reference-stability the
1535− // reducer's Holder cache provides. This mirrors the SessionListScreen
1536− // per-card lambda memoization pattern.
1537− val onRevert = remember(messageId) { { vm.revertTo(messageId) } }
1538− val onEdit = remember(messageId) {
1539− { text: String ->
1540− // editMessage reverts to before this message (hiding it and
1541− // everything after); the revert banner surfaces the rewind
1542− // with an Undo. Focus + scroll the composer into view like the
1543− // Quote action so the prefilled draft isn't off-screen.
1544− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1545− vm.editMessage(messageId, text)
1546− runCatching { inputFocusRequester.requestFocus() }
1547− contentScope.launch {
1548− runCatchingCancellable {
1549− listState.animateScrollToItem(currentListItems.lastIndex.coerceAtLeast(0))
1550− }
1551− }
1552− Unit
1553− }
1554− }
1555− val onSpeak = remember(messageId) {
1556− { text: String ->
1557− if (!tts.toggle(messageId, text)) {
1558− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1559− }
1560− Unit
1561− }
1562− }
1563− val onPause = remember { { tts.pause() } }
1564− val onResume = remember { { tts.resume() } }
1565− val onStop = remember { { tts.stop() } }
1566− val onQuote = remember(messageId) {
1567− { text: String ->
1568− vm.quoteReply(text)
1569− runCatching { inputFocusRequester.requestFocus() }
1570− Unit
1571− }
1572− }
1573− val onBranch = remember { { text: String -> vm.branchFrom(text); Unit } }
1574− // Regenerate is only meaningful for a finished assistant reply
1575− // (not the actively-streaming one), so gate it on !running.
1576− val onRegenerate = if (!running) {
1577− remember(messageId) { { vm.regenerate(messageId) } }
1578− } else {
1579− null
1580− }
1581− // Continue: resume a partial reply. Shown only for
1582− // incomplete assistant messages (a partial reply that
1583− // was aborted) and not while a run is active.
1584− val canContinue = !running && message.info is AssistantMessage && !message.info.isComplete
1585− val onContinue = if (canContinue) {
1586− remember(messageId) { { vm.continueRun(messageId) } }
1587− } else {
1588− null
1589− }
1590− val messageFailed = optimisticStatuses[messageId] == true
1591− val onRetry = if (messageFailed) {
1592− remember(messageId) { { vm.retryOptimisticMessage(messageId); Unit } }
1593− } else {
1594− null
1595− }
1596− val onDismiss = if (messageFailed) {
1597− remember(messageId) { { vm.dismissOptimistic(messageId) } }
1598− } else {
1599− null
1600− }
1601− val onShare = remember(messageId, sessionTitle, defaultShareSubject) {
1602− {
1603− // Per-message share: build a single-message Markdown
1604− // transcript off-thread and fire ACTION_SEND, mirroring the
1605− // whole-conversation share but scoped to just this message.
1606− scope.launch {
1607− val md = withContext(Dispatchers.Default) {
1608− buildMessageMarkdown(message)
1609− } ?: return@launch
1610− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1611− type = "text/markdown"
1612− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1613− putExtra(android.content.Intent.EXTRA_TEXT, md)
1614− }
1615− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1616− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1617− }
1618− Unit
1619− }
1620− }
1621− SwipeToDismissBox(
1622− state = swipeState,
1623− enableDismissFromEndToStart = !replyFromStartToEnd,
1624− enableDismissFromStartToEnd = replyFromStartToEnd,
1625− backgroundContent = {
1626− Box(
1627− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1628− contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1629− ) {
1630− Icon(
1631− Icons.AutoMirrored.Filled.Reply,
1632− contentDescription = null,
1633− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1634− )
1635− }
1636− },
1637− ) {
1638− MessageBubble(
1639− message,
1640− isRunning = running && messageId == lastMessageId,
1641− imageContext = imageContext,
1642− modelLabel = modelLabel,
1643− agentLabel = agentLabel,
1644− onOpenFile = onOpenFile,
1645− onRevert = onRevert,
1646− onEdit = onEdit,
1647− onSpeak = onSpeak,
1648− isSpeaking = messageId == speakingMessageId,
1649− ttsState = if (messageId == speakingMessageId) ttsState else TtsState.IDLE,
1650− onPause = onPause,
1651− onResume = onResume,
1652− onStop = onStop,
1653− onQuote = onQuote,
1654− onBranch = onBranch,
1655− onRegenerate = onRegenerate,
1656− onContinue = onContinue,
1657− sendStatus = optimisticStatuses[messageId]?.let { failed ->
1658− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1659− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1660− },
1661− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1662− onRetry = onRetry,
1663− onDismiss = onDismiss,
1664− onShare = onShare,
1665− isFirstOfSpeaker = item.isFirstOfSpeaker,
1666− highlighted = focusedMessageId != null && messageId == focusedMessageId,
1667− )
1668− }
1669− }
1670− }
1671− }
1672− }
1673− if (running) {
1674− item(key = "__typing") {
1675− val workingText = stringResource(R.string.working)
1676− // When the SSE stream dropped mid-run, show a "reconnecting" label
1677− // instead of the plain "working" text so the user understands the
1678− // run is still active but the stream is reconnecting (not finished).
1679− val reconnectingText = stringResource(R.string.reconnecting)
1680− val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1681− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1682− // survives LazyColumn recycling — a local remember reset to 0:00 when
1683− // the row was disposed and scrolled back into view. The VM stamps the
1684− // start on the real false→true transition (send/run/init), not on
1685− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1686− // once per second; the value is decorative (the a11y label is the row's).
1687− // The clock freezes when an abort is confirmed (aborting = true) so the
1688− // user can see how long the run lasted before they stopped it, rather
1689− // than the clock continuing to tick until SessionIdle clears _running.
1690− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1691− val elapsedMs by produceState(0L, startMs, aborting) {
1692− if (startMs == 0L) return@produceState
1693− if (aborting) {
1694− // Freeze at the last-computed value: one final snapshot then stop.
1695− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1696− return@produceState
1697− }
1698− while (true) {
1699− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1700− delay(1000)
1701− }
1702− }
1703− val elapsedText = remember(elapsedMs) {
1704− val total = elapsedMs / 1000
1705− // Locale.US for stable digit formatting: on locales with
1706− // non-ASCII digits (ar-/fa-) the default locale would render
1707− // localized digits inside the Monospace block, breaking the
1708− // fixed-width alignment the monospace family was chosen for.
1709− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1710− }
1711− Row(
1712− verticalAlignment = Alignment.CenterVertically,
1713− // Animate this slot in/out so the working row doesn't pop in and
1714− // jolt the message list when a run starts/stops — matching the
1715− // AnimatedVisibility used by every other transient banner/FAB here.
1716− modifier = Modifier
1717− .then(reducedMotionAnimateItem())
1718− .padding(vertical = 4.dp),
1719− ) {
1720− // Merge the indicator + label + clock into one TalkBack node so
1721− // it's announced once (the working label, then the elapsed time)
1722− // instead of "working… / working… / 0:14" with the label read
1723− // twice. The Stop IconButton below stays separately focusable.
1724− Row(
1725− verticalAlignment = Alignment.CenterVertically,
1726− modifier = Modifier.semantics(mergeDescendants = true) {
1727− contentDescription = "$interruptedLabel $elapsedText"
1728− },
1729− ) {
1730− // Dim the spinner when interrupted so the row reads as
1731− // "paused/reconnecting" rather than actively progressing.
1732− CircularProgressIndicator(
1733− Modifier.size(16.dp),
1734− strokeWidth = 2.dp,
1735− color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1736− else MaterialTheme.colorScheme.primary,
1737− )
1738− Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1739− Spacer(Modifier.size(8.dp))
1740− Icon(
1741− Icons.Filled.Schedule,
1742− contentDescription = null,
1743− modifier = Modifier.size(14.dp),
1744− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1745− )
1746− Text(
1747− elapsedText,
1748− style = MaterialTheme.typography.labelMedium,
1749− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1750− color = MaterialTheme.colorScheme.onSurfaceVariant,
1751− modifier = Modifier.padding(start = 4.dp),
1752− )
1753− }
1754− // A trailing Stop on the working row so the run can be aborted
1755− // without scrolling back to the composer (which may be off-screen
1756− // while the user reads the streaming output up-thread).
1757− Spacer(Modifier.weight(1f))
1758− val stopLabel = stringResource(R.string.stop)
1759− IconButton(
1760− onClick = { vm.abort() },
1761− modifier = Modifier.semantics { contentDescription = stopLabel },
1762− ) {
1763− Icon(Icons.Filled.Stop, contentDescription = null)
1764− }
1765− }
1766− }
1767− }
1768− }
1769− }
1770− }
1771− }
1772− // Jump-to-latest affordance when the user has scrolled away during a stream.
1773− val fabMotion = rememberVisibilityTransitions()
1774− AnimatedVisibility(
1775− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1776− enter = fabMotion.enter,
1777− exit = fabMotion.exit,
1778− // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1779− // edge instead of floating at the screen edge (visually detached on tablets).
1780− modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1781− ) {
1782− // Badge the FAB when new content arrived while the user was scrolled up, so
1783− // they know there's something new to jump to (cleared once back at bottom).
1784− BadgedBox(
1785− badge = {
1786− if (newContentCount > 0) {
1787− // Merge the count into the badge announcement so TalkBack reads
1788− // "5 new messages" instead of the bare label and a separate number.
1789− val newContentLabel = pluralStringResource(
1790− R.plurals.plurals_new_messages,
1791− newContentCount,
1792− newContentCount,
1793− )
1794− Badge(
1795− modifier = Modifier.semantics {
1796− contentDescription = newContentLabel
1797− // Announce new-content counts as they change so a
1798− // TalkBack user hears "5 new messages" without having
1799− // to focus the FAB. Polite so it doesn't interrupt an
1800− // in-progress utterance (e.g. streaming token reads).
1801− liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1802− },
1803− ) {
1804− Text(
1805− if (newContentCount > 99) "99+" else newContentCount.toString(),
1806− modifier = Modifier.semantics { invisibleToUser() },
1807− )
1808− }
1809− }
1810− },
1811− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1812− ) {
1813− ExtendedFloatingActionButton(
1814− onClick = {
1815− newContentCount = 0
1816− if (listItems.isNotEmpty()) {
1817− // Scroll to the effective last index, including the
1818− // trailing "__typing" row when a run is active.
1819− val target = if (running) listItems.size else listItems.lastIndex
1820− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1821− }
1822− },
1823− // contentDescription null: the visible "Latest" text already labels
1824− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1825− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1826− text = { Text(stringResource(R.string.latest)) },
1827− )
1828− }
1829− }
1830− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1831− // user has scrolled down past the first few messages. Symmetric to the
1832− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1833− val scrolledDown by remember {
1834− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1835− }
1836− AnimatedVisibility(
1837− visible = scrolledDown && listItems.size > 4,
1838− enter = fabMotion.enter,
1839− exit = fabMotion.exit,
1840− modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1841− ) {
1842− SmallFloatingActionButton(
1843− onClick = {
1844− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1845− },
1846− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1847− ) {
1848− Icon(
1849− Icons.Filled.KeyboardArrowUp,
1850− contentDescription = stringResource(R.string.scroll_to_top),
1851− )
1852− }
1853− }
1854− // In-conversation search bar. Overlays the list so typing filters messages in
1855− // place; the match count + a no-matches note give immediate feedback.
1856− val searchMotion = rememberVisibilityTransitions()
1857− AnimatedVisibility(
1858− visible = searchActive,
1859− enter = searchMotion.enter,
1860− exit = searchMotion.exit,
1861− // Inset by sideMargin on wide screens so the search bar spans the capped
1862− // list's width, not the full screen width.
1863− modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1864− ) {
1865− Surface(
1866− tonalElevation = 3.dp,
1867− modifier = Modifier
1868− .padding(horizontal = 12.dp, vertical = 4.dp)
1869− .fillMaxWidth()
1870− .onSizeChanged { searchbarHeightPx = it.height },
1871− ) {
1872− // Focus the search field when the bar appears (from the overflow menu's
1873− // "Find in conversation" or Ctrl+F), so the user can start typing
1874− // immediately. Runs after the search field enters the composition.
1875− LaunchedEffect(searchActive) {
1876− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1877− }
1878− Row(
1879− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1880− verticalAlignment = Alignment.CenterVertically,
1881− ) {
1882− OutlinedTextField(
1883− value = chatSearch,
1884− onValueChange = { chatSearch = it },
1885− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1886− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1887− singleLine = true,
1888− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1889− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1890− )
1891− // Match counter: "N of M" where N is the focused match (1-based) and
1892− // M is the total matching messages. Only shown when there's a query.
1893− val matchCount = searchMessages.size
1894− Text(
1895− if (searchQuery.isNotEmpty() && matchCount > 0) {
1896− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1897− } else if (searchQuery.isNotEmpty()) {
1898− stringResource(R.string.search_no_matches)
1899− } else "",
1900− style = MaterialTheme.typography.labelSmall,
1901− color = MaterialTheme.colorScheme.onSurfaceVariant,
1902− modifier = Modifier
1903− .padding(horizontal = 4.dp)
1904− // Live region so a TalkBack user hears "3 of 12" / "No
1905− // matches" announce as they step through results, not just
1906− // the sighted user seeing the counter update.
1907− .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
1908− )
1909− // Step through matches (Previous / Next), disabled when there are
1910− // fewer than two to navigate. Wrap around at the ends so repeated
1911− // taps cycle through every hit.
1912− val prevLabel = stringResource(R.string.find_previous)
1913− val nextLabel = stringResource(R.string.find_next)
1914− IconButton(
1915− onClick = {
1916− if (matchCount > 0) {
1917− searchPos = (searchPos - 1 + matchCount) % matchCount
1918− }
1919− },
1920− enabled = matchCount > 1,
1921− ) {
1922− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1923− }
1924− IconButton(
1925− onClick = {
1926− if (matchCount > 0) {
1927− searchPos = (searchPos + 1) % matchCount
1928− }
1929− },
1930− enabled = matchCount > 1,
1931− ) {
1932− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
1933− }
1934− IconButton(onClick = {
1935− searchActive = false
1936− chatSearch = ""
1937− }) {
1938− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1939− }
1940− }
1941− }
1942− }
1943− // When a search yields no matches (but the conversation isn't empty), say so
1944− // instead of showing a blank list.
1945− if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1946− Text(
1947− stringResource(R.string.search_no_matches),
1948− style = MaterialTheme.typography.bodyMedium,
1949− color = MaterialTheme.colorScheme.onSurfaceVariant,
1950− modifier = Modifier.align(Alignment.Center),
1951− )
1952− }
1953− }
1954− }
1955− }
1956− }
1957−
1958− if (showExitConfirm) {
1959− AlertDialog(
1960− onDismissRequest = { showExitConfirm = false },
1961− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1962− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1963− confirmButton = {
1964− TextButton(onClick = {
1965− showExitConfirm = false
1966− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1967− vm.abort()
1968− onBack()
1969− }) { Text(stringResource(R.string.stop_and_exit)) }
1970− },
1971− dismissButton = {
1972− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1973− },
1974− )
1975− }
1976−
1977− if (showSummarizeConfirm) {
1978− AlertDialog(
1979− onDismissRequest = { showSummarizeConfirm = false },
1980− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1981− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1982− confirmButton = {
1983− TextButton(onClick = {
1984− showSummarizeConfirm = false
1985− vm.summarize()
1986− }) { Text(stringResource(R.string.action_continue)) }
1987− },
1988− dismissButton = {
1989− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1990− },
1991− )
1992− }
1993−
1994− if (showInitConfirm) {
1995− AlertDialog(
1996− onDismissRequest = { showInitConfirm = false },
1997− title = { Text(stringResource(R.string.init_confirm_title)) },
1998− text = { Text(stringResource(R.string.init_confirm_text)) },
1999− confirmButton = {
2000− TextButton(onClick = {
2001− showInitConfirm = false
2002− vm.initProject()
2003− }) { Text(stringResource(R.string.action_continue)) }
2004− },
2005− dismissButton = {
2006− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
2007− },
2008− )
2009− }
2010−
2011− if (showRenameDialog) {
2012− RenameSessionChatDialog(
2013− initialTitle = sessionTitle ?: "",
2014− onDismiss = { showRenameDialog = false },
2015− onConfirm = { newName ->
2016− showRenameDialog = false
2017− vm.renameSession(newName)
2018− },
2019− )
2020− }
2021−
2022− if (showDeleteDialog) {
2023− AlertDialog(
2024− onDismissRequest = { showDeleteDialog = false },
2025− title = { Text(stringResource(R.string.delete_session_chat_title)) },
2026− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
2027− confirmButton = {
2028− TextButton(onClick = {
2029− showDeleteDialog = false
2030− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2031− vm.deleteSession()
2032− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
2033− },
2034− dismissButton = {
2035− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
2036− },
2037− )
2038− }
2039−
2040− if (showShellDialog) {
2041− ShellCommandDialog(
2042− onDismiss = { showShellDialog = false },
2043− onRun = { cmd ->
2044− showShellDialog = false
2045− vm.runShell(cmd)
2046− },
2047− )
2048− }
2049−
2050− if (showModelPicker) {
2051− // Resolve persisted recent composite keys to the live ModelOption entries they refer
2052− // to, dropping any whose model is no longer offered by the server. Ordered by
2053− // recency (head of the store first).
2054− val recentOptions = remember(models, recentModelEntries) {
2055− val byKey = models.associateBy { it.providerID to it.modelID }
2056− recentModelEntries.mapNotNull { entry ->
2057− container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2058− }
2059− }
2060− // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2061− // below isn't @Composable, so stringResource can't be called inside it.
2062− val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2063− val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2064− ModelPickerSheet(
2065− options = models,
2066− selected = selectedModel,
2067− loading = modelsLoading,
2068− error = modelsError,
2069− onSelect = {
2070− vm.selectModel(it)
2071− container.recentModelsStore.add(it.providerID, it.modelID)
2072− },
2073− onRetry = { vm.reloadModels() },
2074− onDismiss = { showModelPicker = false },
2075− preferredModelId = preferredModelId,
2076− onSetPreferredModel = { id ->
2077− scope.launch {
2078− runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2079− // Confirm the change with a snackbar so the user sees it took effect —
2080− // the toggle's label flip can be missed, especially when clearing.
2081− val msg = if (id.isEmpty()) {
2082− defaultModelClearedMsg
2083− } else {
2084− val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2085− defaultModelSetFmt.format(label)
2086− }
2087− snackbar.showSnackbar(msg)
2088− }
2089− },
2090− recent = recentOptions,
2091− )
2092− }
2093−
2094− if (showAgentPicker) {
2095− AgentPickerSheet(
2096− agents = agents,
2097− selected = selectedAgent,
2098− loading = agentsLoading,
2099− error = agentsError,
2100− onSelect = { vm.selectAgent(it?.name) },
2101− onRetry = { vm.reloadAgents() },
2102− onDismiss = { showAgentPicker = false },
2103− )
2104− }
2105−
2106− if (showCommandPicker) {
2107− CommandPickerSheet(
2108− commands = commands,
2109− loading = commandsLoading,
2110− error = commandsError,
2111− onSelect = { vm.runCommand(it) },
2112− onRetry = { vm.reloadCommands() },
2113− onDismiss = { showCommandPicker = false },
2114− )
2115− }
2116−
2117− pendingPermission?.let { permission ->
2118− PermissionDialog(
2119− permission = permission,
2120− position = permissionProgress.position,
2121− total = permissionProgress.total,
2122− onRespond = { response -> vm.respondPermission(permission, response) },
2123− // On auto-reject timeout, post a notification so a returning user finds a
2124− // persistent record of why the run stopped (the dialog itself is gone).
2125− // Gated by the user's notification setting (notifPermission).
2126− onAutoReject = {
2127− val conn = activeConnection
2128− val ctx = appContext
2129− val title = sessionTitle ?: sessionId
2130− if (notifPermission) {
2131− soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2132− ctx, sessionId, title, conn?.profile?.id,
2133− )
2134− }
2135− },
2136− )
2137− }
2138−
2139− if (showPalette) {
2140− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2141− }
2142−
2143− if (showShortcutsDialog) {
2144− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2145− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2146− // depends on the "Send on Enter" setting, noted inline.
2147− AlertDialog(
2148− onDismissRequest = { showShortcutsDialog = false },
2149− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2150− text = {
2151− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2152− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2153− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2154− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2155− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2156− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2157− }
2158− },
2159− confirmButton = {
2160− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2161− },
2162− )
2163− }
2164−}
2165−
2166−@Composable
2167−private fun ShortcutRow(keys: String, desc: String) {
2168− Row(verticalAlignment = Alignment.CenterVertically) {
2169− Text(
2170− keys,
2171− style = MaterialTheme.typography.labelLarge,
2172− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2173− modifier = Modifier.widthIn(min = 160.dp),
2174− )
2175− Text(
2176− desc,
2177− style = MaterialTheme.typography.bodyMedium,
2178− color = MaterialTheme.colorScheme.onSurfaceVariant,
2179− )
2180− }
2181−}
2182−
2183−/**
2184− * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2185− * of matching commands above the composer. Tapping a command fires it immediately.
2186− * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2187− * the detekt threshold. Suppressed while running or when the command catalog is empty.
2188− */
2189−@Composable
2190−private fun SlashCommandAutocomplete(
2191− value: String,
2192− commands: List<Command>,
2193− running: Boolean,
2194− onRunCommand: (Command) -> Unit,
2195−) {
2196− if (running || commands.isEmpty()) return
2197− val slashQuery = remember(value) {
2198− if (value.startsWith("/")) value.removePrefix("/") else null
2199− } ?: return
2200− val matchingCommands = remember(slashQuery, commands) {
2201− commands.filter { cmd ->
2202− slashQuery.isEmpty() ||
2203− cmd.name.contains(slashQuery, ignoreCase = true) ||
2204− (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2205− }.take(8)
2206− }
2207− if (matchingCommands.isNotEmpty()) {
2208− CommandAutocompleteDropdown(
2209− commands = matchingCommands,
2210− onPick = onRunCommand,
2211− )
2212− }
2213−}
2214−
2215−/**
2216− * Slash-command autocomplete dropdown shown above the composer when the draft starts
2217− * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2218− * user can discover and invoke commands by typing the conventional "/" prefix instead
2219− * of opening the overflow menu / command palette. Tapping a row fires the command.
2220− */
2221−@Composable
2222−private fun CommandAutocompleteDropdown(
2223− commands: List<Command>,
2224− onPick: (Command) -> Unit,
2225−) {
2226− val haptics = LocalHapticFeedback.current
2227− Surface(
2228− color = MaterialTheme.colorScheme.surface,
2229− tonalElevation = 3.dp,
2230− shape = MaterialTheme.shapes.medium,
2231− modifier = Modifier
2232− .fillMaxWidth()
2233− .padding(horizontal = 8.dp, vertical = 4.dp)
2234− .heightIn(max = 240.dp),
2235− ) {
2236− LazyColumn {
2237− items(
2238− count = commands.size,
2239− key = { commands[it].name },
2240− ) { i ->
2241− val cmd = commands[i]
2242− Row(
2243− modifier = Modifier
2244− .fillMaxWidth()
2245− .clickable(role = Role.Button) {
2246− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2247− onPick(cmd)
2248− }
2249− .padding(horizontal = 16.dp, vertical = 10.dp),
2250− verticalAlignment = Alignment.CenterVertically,
2251− horizontalArrangement = Arrangement.spacedBy(12.dp),
2252− ) {
2253− Text(
2254− "/${cmd.name}",
2255− style = MaterialTheme.typography.labelLarge,
2256− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2257− color = MaterialTheme.colorScheme.primary,
2258− )
2259− cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2260− Text(
2261− desc,
2262− style = MaterialTheme.typography.bodySmall,
2263− color = MaterialTheme.colorScheme.onSurfaceVariant,
2264− maxLines = 1,
2265− overflow = TextOverflow.Ellipsis,
2266− )
2267− }
2268− }
2269− }
2270− }
2271− }
2272−}
2273−
2274−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2275−@Suppress("CyclomaticComplexMethod")
2276−@Composable
2277−private fun ChatInputBar(
2278− value: String,
2279− onValueChange: (String) -> Unit,
2280− running: Boolean,
2281− aborting: Boolean,
2282− enabled: Boolean,
2283− sendOnEnter: Boolean,
2284− onSend: () -> Unit,
2285− onAbort: () -> Unit,
2286− queuedFollowUp: String?,
2287− onQueueFollowUp: (String) -> Unit,
2288− onCancelQueue: () -> Unit,
2289− focusRequester: androidx.compose.ui.focus.FocusRequester,
2290− attachments: List<PendingAttachment>,
2291− staging: Boolean,
2292− stagingFileCount: Int,
2293− onRemoveAttachment: (String) -> Unit,
2294− onPickPhoto: () -> Unit,
2295− onPickFile: () -> Unit,
2296− onCamera: () -> Unit,
2297− onVoice: () -> Unit,
2298− onPasteImage: (List<Uri>) -> Unit,
2299− commands: List<Command> = emptyList(),
2300− onRunCommand: (Command) -> Unit = {},
2301−) {
2302− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2303− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2304− val context = LocalContext.current
2305− // Full-screen editor state: opened when the user wants more space for a long prompt.
2306− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2307− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2308− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2309− // A queued follow-up replaces the Stop button with a "queued" chip so the
2310− // user sees their message will be sent when the run finishes, and can cancel.
2311− if (queuedFollowUp != null) {
2312− val editLabel = stringResource(R.string.edit)
2313− Row(
2314− modifier = Modifier
2315− .fillMaxWidth()
2316− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2317− verticalAlignment = Alignment.CenterVertically,
2318− ) {
2319− // Tapping the chip reloads the queued text into the draft (and clears the
2320− // queue) so a typo spotted while queuing can be fixed without retyping.
2321− Column(
2322− modifier = Modifier
2323− .weight(1f)
2324− .clip(MaterialTheme.shapes.small)
2325− .clickable(role = Role.Button, onClickLabel = editLabel) {
2326− onValueChange(queuedFollowUp)
2327− onCancelQueue()
2328− }
2329− .padding(vertical = 4.dp),
2330− ) {
2331− Text(
2332− stringResource(R.string.queued),
2333− style = MaterialTheme.typography.labelSmall,
2334− color = MaterialTheme.colorScheme.onSurfaceVariant,
2335− )
2336− Text(
2337− queuedFollowUp,
2338− style = MaterialTheme.typography.bodySmall,
2339− color = MaterialTheme.colorScheme.onSurfaceVariant,
2340− maxLines = 1,
2341− overflow = TextOverflow.Ellipsis,
2342− )
2343− }
2344− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2345− Text(stringResource(R.string.cancel))
2346− }
2347− }
2348− }
2349− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2350− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2351− // Slash-command autocomplete: extracted to a helper to keep this function's
2352− // complexity under the detekt threshold. Returns no-op when the draft doesn't
2353− // start with "/" or the command catalog is empty.
2354− SlashCommandAutocomplete(
2355− value = value,
2356− commands = commands,
2357− running = running,
2358− onRunCommand = onRunCommand,
2359− )
2360− Row(
2361− modifier = Modifier.fillMaxWidth().padding(8.dp),
2362− verticalAlignment = Alignment.Bottom,
2363− ) {
2364− // Attach menu: photo picker, camera, or any file.
2365− var showAttachMenu by remember { mutableStateOf(false) }
2366− Box {
2367− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2368− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2369− }
2370− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2371− DropdownMenuItem(
2372− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2373− text = { Text(stringResource(R.string.attach_photo)) },
2374− onClick = { showAttachMenu = false; onPickPhoto() },
2375− )
2376− DropdownMenuItem(
2377− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2378− text = { Text(stringResource(R.string.attach_camera)) },
2379− onClick = { showAttachMenu = false; onCamera() },
2380− )
2381− DropdownMenuItem(
2382− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2383− text = { Text(stringResource(R.string.attach_file)) },
2384− onClick = { showAttachMenu = false; onPickFile() },
2385− )
2386− }
2387− }
2388− // Voice dictation: appends recognized speech to the draft. Hidden (not just
2389− // disabled) when the device has no speech-recognition activity, so a user
2390− // without a voice app doesn't get a button that only fails noisily on tap.
2391− val voiceAvailable = remember {
2392− val pm = context.packageManager
2393− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2394− pm.queryIntentActivities(intent, 0).isNotEmpty()
2395− }
2396− if (voiceAvailable) {
2397− IconButton(onClick = onVoice, enabled = enabled) {
2398− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2399− }
2400− }
2401− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2402− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2403− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2404− }
2405− OutlinedTextField(
2406− value = value,
2407− onValueChange = { v ->
2408− // Cap input length so a huge paste can't stall the UI. Shares are
2409− // capped separately in MainActivity; this guards typed/pasted drafts.
2410− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2411− },
2412− modifier = Modifier
2413− .weight(1f)
2414− .focusRequester(focusRequester)
2415− .testTag("chat_input")
2416− // Intercept image content pasted/dropped into the field (keyboard paste
2417− // of a copied screenshot, drag from Files, etc.) and route it through the
2418− // same staging path as the attach menu. Non-image content (text) falls
2419− // through unchanged so normal typing/paste works.
2420− .contentReceiver(
2421− remember {
2422− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2423− val clipData = transferable.clipEntry?.clipData
2424− if (clipData != null) {
2425− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2426− val item = clipData.getItemAt(i)
2427− item.uri?.takeIf { uri ->
2428− item.text == null && uri.toString().let { s ->
2429− s.startsWith("content:") || s.startsWith("file:")
2430− }
2431− }
2432− }
2433− if (imageUris.isNotEmpty()) {
2434− onPasteImage(imageUris)
2435− }
2436− }
2437− transferable
2438− }
2439− },
2440− )
2441− .onPreviewKeyEvent { event ->
2442− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2443− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2444− // With it off, Enter inserts a newline and Ctrl+Enter sends.
2445− val send = enterShouldSend(
2446− enabled = enabled,
2447− hasContent = hasContent,
2448− sendOnEnter = sendOnEnter,
2449− shift = event.isShiftPressed,
2450− ctrl = event.isCtrlPressed,
2451− )
2452− if (send) {
2453− if (running) onQueueFollowUp(value) else onSend()
2454− true
2455− } else {
2456− false
2457− }
2458− },
2459− // While a run is active a typed message only queues (sends after the run), so
2460− // the placeholder says so instead of the plain "Message…".
2461− placeholder = {
2462− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2463− },
2464− enabled = enabled,
2465− maxLines = 6,
2466− // Show a "N / max" countdown once the draft crosses a high fraction of
2467− // the cap, so the user knows a paste is about to be truncated instead
2468− // of being silently cut off. Hidden for normal short prompts to avoid
2469− // clutter under a typical one-line message.
2470− supportingText = {
2471− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2472− if (value.length >= threshold) {
2473− Text(
2474− stringResource(
2475− R.string.draft_chars_remaining,
2476− NetworkConfig.maxDraftLengthChars - value.length,
2477− NetworkConfig.maxDraftLengthChars,
2478− ),
2479− style = MaterialTheme.typography.labelSmall,
2480− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2481− else MaterialTheme.colorScheme.onSurfaceVariant,
2482− )
2483− } else if (value.lines().size > 6) {
2484− // The inline field caps at 6 lines; once the draft crosses that,
2485− // hint that a bigger full-screen editor exists (the Expand icon
2486− // above is easy to miss among the icon row). A tappable label
2487− // would be ideal, but a plain hint is enough to draw attention.
2488− Text(
2489− stringResource(R.string.open_full_editor_hint),
2490− style = MaterialTheme.typography.labelSmall,
2491− color = MaterialTheme.colorScheme.onSurfaceVariant,
2492− )
2493− }
2494− },
2495− keyboardOptions = KeyboardOptions(
2496− // When "Send on Enter" is on, expose ImeAction.Send so the soft
2497− // keyboard shows a send key — matching the setting's intent and
2498− // giving touch-only users a keyboard send affordance. When off,
2499− // ImeAction.Default keeps the enter/newline key for multi-line input.
2500− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2501− capitalization = KeyboardCapitalization.Sentences,
2502− ),
2503− keyboardActions = KeyboardActions(
2504− onSend = {
2505− // Mirror the hardware-Enter handler: during a run the soft-keyboard
2506− // send key must queue the follow-up, not silently drop it. vm.send()
2507− // returns false while a run is active (beginRun() rejects), so calling
2508− // onSend() directly here would lose the typed message with no feedback
2509− // for touch-only users (no hardware Enter path available).
2510− if (enabled && hasContent) {
2511− if (running) onQueueFollowUp(value) else onSend()
2512− }
2513− },
2514− ),
2515− )
2516− ComposerTrailingButton(
2517− running = running,
2518− aborting = aborting,
2519− canSend = enabled && hasContent,
2520− canQueue = enabled && value.isNotBlank(),
2521− onSend = onSend,
2522− onAbort = onAbort,
2523− onQueue = { onQueueFollowUp(value) },
2524− )
2525− }
2526− }
2527− if (showFullScreenEditor) {
2528− FullScreenEditor(
2529− value = value,
2530− onValueChange = onValueChange,
2531− onDismiss = { showFullScreenEditor = false },
2532− onSend = {
2533− showFullScreenEditor = false
2534− // Mirror the inline composer's behavior: while a run is active a send
2535− // can't go immediately, so queue the follow-up instead of silently
2536− // dropping it (vm.send() returns false during a run, which previously
2537− // lost the typed message with no feedback).
2538− if (running) onQueueFollowUp(value) else onSend()
2539− },
2540− canSend = enabled && hasContent,
2541− running = running,
2542− sendOnEnter = sendOnEnter,
2543− attachments = attachments,
2544− onRemoveAttachment = onRemoveAttachment,
2545− staging = staging,
2546− stagingFileCount = stagingFileCount,
2547− )
2548− }
2549− }
2550−}
2551−
2552−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2553− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2554−@OptIn(ExperimentalMaterial3Api::class)
2555−@Composable
2556−private fun FullScreenEditor(
2557− value: String,
2558− onValueChange: (String) -> Unit,
2559− onDismiss: () -> Unit,
2560− onSend: () -> Unit,
2561− canSend: Boolean,
2562− running: Boolean = false,
2563− sendOnEnter: Boolean = false,
2564− attachments: List<PendingAttachment> = emptyList(),
2565− onRemoveAttachment: (String) -> Unit = {},
2566− staging: Boolean = false,
2567− stagingFileCount: Int = 0,
2568−) {
2569− androidx.compose.ui.window.Dialog(
2570− onDismissRequest = onDismiss,
2571− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2572− ) {
2573− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2574− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2575− // gives the available width so we can center a capped-width column.
2576− androidx.compose.foundation.layout.BoxWithConstraints(
2577− modifier = Modifier.fillMaxSize(),
2578− contentAlignment = Alignment.Center,
2579− ) {
2580− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2581− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2582− else 0.dp
2583− Scaffold(
2584− modifier = Modifier.padding(horizontal = hPad),
2585− topBar = {
2586− androidx.compose.material3.TopAppBar(
2587− title = { Text(stringResource(R.string.compose_editor_title)) },
2588− navigationIcon = {
2589− androidx.compose.material3.TextButton(onClick = onDismiss) {
2590− Text(stringResource(R.string.collapse_editor))
2591− }
2592− },
2593− )
2594− },
2595− bottomBar = {
2596− Surface(tonalElevation = 3.dp) {
2597− Row(
2598− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2599− horizontalArrangement = Arrangement.End,
2600− ) {
2601− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2602− Text(stringResource(if (running) R.string.queue else R.string.send))
2603− }
2604− }
2605− }
2606− },
2607− ) { padding ->
2608− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2609− // Show staged attachments in the full-screen editor too, so a user who staged
2610− // images then expanded for a long prompt can still see and remove them without
2611− // collapsing first (mirrors the inline composer's AttachmentStrip).
2612− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2613− OutlinedTextField(
2614− value = value,
2615− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2616− modifier = Modifier
2617− .fillMaxSize()
2618− .weight(1f)
2619− // Honor the "Send on Enter" setting here too, so the full-screen
2620− // editor matches the inline composer: Enter sends (Shift+Enter
2621− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2622− // when off. Previously this hard-coded ImeAction.Default and had no
2623− // key handler, so a hardware-keyboard user got a different behaviour
2624− // from the inline composer depending on which they happened to open.
2625− .onPreviewKeyEvent { event ->
2626− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2627− val send = enterShouldSend(
2628− enabled = canSend,
2629− hasContent = canSend,
2630− sendOnEnter = sendOnEnter,
2631− shift = event.isShiftPressed,
2632− ctrl = event.isCtrlPressed,
2633− )
2634− if (send) { onSend(); true } else false
2635− },
2636− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2637− maxLines = Int.MAX_VALUE,
2638− keyboardOptions = KeyboardOptions(
2639− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2640− capitalization = KeyboardCapitalization.Sentences,
2641− ),
2642− keyboardActions = KeyboardActions(
2643− onSend = { if (canSend) onSend() },
2644− ),
2645− )
2646− }
2647− }
2648− }
2649− }
2650−}
2651−
2652−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2653− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2654−private fun enterShouldSend(
2655− enabled: Boolean,
2656− hasContent: Boolean,
2657− sendOnEnter: Boolean,
2658− shift: Boolean,
2659− ctrl: Boolean,
2660−): Boolean = when {
2661− !enabled || !hasContent -> false
2662− sendOnEnter -> !shift
2663− else -> ctrl
2664−}
2665−
2666−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2667− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2668− * [ChatInputBar] stays under the complexity threshold. */
2669−@Composable
2670−private fun ComposerTrailingButton(
2671− running: Boolean,
2672− aborting: Boolean,
2673− canSend: Boolean,
2674− canQueue: Boolean,
2675− onSend: () -> Unit,
2676− onAbort: () -> Unit,
2677− onQueue: () -> Unit,
2678−) {
2679− if (running) {
2680− Row(verticalAlignment = Alignment.CenterVertically) {
2681− // While a run is active the trailing action is Stop, so the only send affordance is
2682− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2683− // That leaves a touch-only user with the setting off no way to queue a follow-up
2684− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2685− // there's typed TEXT so queuing is always reachable, without changing the user's
2686− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2687− // canSend, which is also true for an attachment-only composer — because queuing "" just
2688− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2689− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2690− if (canQueue) {
2691− IconButton(
2692− onClick = onQueue,
2693− modifier = Modifier.testTag("queue_button"),
2694− ) {
2695− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2696− // icon (which can be read as "snooze" or "later"), and isn't confused with
2697− // the Send action sitting right beside the Stop button.
2698− Icon(
2699− Icons.AutoMirrored.Filled.PlaylistAdd,
2700− contentDescription = stringResource(R.string.queue_followup),
2701− )
2702− }
2703− }
2704− // Show a spinner while the abort REST call is in flight so the user sees the stop
2705− // was sent, and disable to prevent a double-tap.
2706− IconButton(
2707− onClick = onAbort,
2708− enabled = !aborting,
2709− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2710− ) {
2711− if (aborting) {
2712− val stopLabel = stringResource(R.string.stop)
2713− CircularProgressIndicator(
2714− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2715− strokeWidth = 2.dp,
2716− )
2717− } else {
2718− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2719− }
2720− }
2721− }
2722− } else {
2723− IconButton(
2724− onClick = onSend,
2725− enabled = canSend,
2726− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2727− ) {
2728− // Tint the send icon with primary when there's content to send so the commit action
2729− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2730− Icon(
2731− Icons.AutoMirrored.Filled.Send,
2732− contentDescription = stringResource(R.string.send),
2733− tint = if (canSend) MaterialTheme.colorScheme.primary
2734− else MaterialTheme.colorScheme.onSurfaceVariant,
2735− )
2736− }
2737− }
2738−}
2739−
2740−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2741−@Composable
2742−private fun EmptyConversation(
2743− onSuggestion: (String) -> Unit,
2744− modifier: Modifier = Modifier,
2745−) {
2746− // A few example prompts so a first-time user has a one-tap path to their first
2747− // message instead of staring at a blank input. Tapping a chip fills the draft
2748− // (without sending) so the user can edit it before sending.
2749− val suggestions = remember {
2750− listOf(
2751− R.string.empty_chat_suggest_1,
2752− R.string.empty_chat_suggest_2,
2753− R.string.empty_chat_suggest_3,
2754− )
2755− }
2756− Column(
2757− modifier = modifier.padding(32.dp),
2758− horizontalAlignment = Alignment.CenterHorizontally,
2759− ) {
2760− Icon(
2761− Icons.Filled.AutoAwesome,
2762− contentDescription = null,
2763− modifier = Modifier.size(48.dp),
2764− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2765− )
2766− Spacer(Modifier.size(16.dp))
2767− Text(
2768− stringResource(R.string.empty_chat_title),
2769− style = MaterialTheme.typography.titleMedium,
2770− )
2771− Spacer(Modifier.size(8.dp))
2772− Text(
2773− stringResource(R.string.empty_chat_hint),
2774− style = MaterialTheme.typography.bodyMedium,
2775− color = MaterialTheme.colorScheme.onSurfaceVariant,
2776− )
2777− Spacer(Modifier.size(20.dp))
2778− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2779− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2780− FlowRow(
2781− modifier = Modifier.fillMaxWidth(),
2782− horizontalArrangement = Arrangement.spacedBy(8.dp),
2783− verticalArrangement = Arrangement.spacedBy(8.dp),
2784− ) {
2785− suggestions.forEach { resId ->
2786− val text = stringResource(resId)
2787− androidx.compose.material3.AssistChip(
2788− onClick = { onSuggestion(text) },
2789− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2790− )
2791− }
2792− }
2793− }
2794−}
2795−
2796−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2797− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2798− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2799−@Composable
2800−private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2801− val haptics = LocalHapticFeedback.current
2802− var showDiff by rememberSaveable { mutableStateOf(false) }
2803− val expandMotion = rememberVisibilityTransitions()
2804− Surface(
2805− color = MaterialTheme.colorScheme.tertiaryContainer,
2806− tonalElevation = 2.dp,
2807− modifier = Modifier.fillMaxWidth(),
2808− ) {
2809− Column {
2810− Row(
2811− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2812− verticalAlignment = Alignment.CenterVertically,
2813− horizontalArrangement = Arrangement.SpaceBetween,
2814− ) {
2815− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2816− Icon(
2817− if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2818− contentDescription = null,
2819− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2820− modifier = Modifier.size(18.dp),
2821− )
2822− Text(
2823− stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2824− style = MaterialTheme.typography.bodySmall,
2825− color = MaterialTheme.colorScheme.onTertiaryContainer,
2826− modifier = Modifier.padding(start = 8.dp),
2827− )
2828− // "Show what changed" toggle, shown only when the server provided a diff.
2829− // Collapsible so the banner stays compact by default; a user curious about
2830− // what the revert rolled back can expand it inline without leaving the chat.
2831− if (!diff.isNullOrBlank()) {
2832− TextButton(
2833− onClick = {
2834− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2835− showDiff = !showDiff
2836− },
2837− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2838− ) {
2839− Icon(
2840− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2841− contentDescription = null,
2842− modifier = Modifier.size(16.dp),
2843− )
2844− Text(
2845− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2846− style = MaterialTheme.typography.labelSmall,
2847− modifier = Modifier.padding(start = 4.dp),
2848− )
2849− }
2850− }
2851− }
2852− TextButton(onClick = {
2853− // Haptic on undo to match the other destructive/important confirmations: a
2854− // revert restores potentially hundreds of hidden messages.
2855− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2856− onUndo()
2857− }) { Text(stringResource(R.string.undo)) }
2858− }
2859− // The diff render lives inside the banner's Surface so it inherits the tertiary
2860− // tonal container and reads as part of the banner, not a floating panel.
2861− if (!diff.isNullOrBlank()) {
2862− AnimatedVisibility(
2863− visible = showDiff,
2864− enter = expandMotion.enter,
2865− exit = expandMotion.exit,
2866− ) {
2867− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2868− Text(
2869− stringResource(R.string.revert_diff_header),
2870− style = MaterialTheme.typography.labelSmall,
2871− color = MaterialTheme.colorScheme.onTertiaryContainer,
2872− modifier = Modifier.padding(bottom = 4.dp),
2873− )
2874− DiffView(diff, saveKey = "revertDiff")
2875− }
2876− }
2877− }
2878− }
2879− }
2880−}
2881−
2882−/** A dismissible preview card shown above the composer when the user quote-replied to a
2883− * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2884− * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2885− * the Discord/Slack quote-preview pattern. */
2886−@Composable
2887−private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2888− val haptics = LocalHapticFeedback.current
2889− Surface(
2890− color = MaterialTheme.colorScheme.secondaryContainer,
2891− tonalElevation = 2.dp,
2892− modifier = Modifier.fillMaxWidth(),
2893− ) {
2894− Row(
2895− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2896− verticalAlignment = Alignment.Top,
2897− ) {
2898− Icon(
2899− Icons.Filled.FormatQuote,
2900− contentDescription = null,
2901− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2902− modifier = Modifier.size(18.dp).padding(top = 2.dp),
2903− )
2904− Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
2905− Text(
2906− stringResource(R.string.quote_reply_banner),
2907− style = MaterialTheme.typography.labelSmall,
2908− color = MaterialTheme.colorScheme.onSecondaryContainer,
2909− )
2910− Text(
2911− quotedText,
2912− style = MaterialTheme.typography.bodySmall,
2913− color = MaterialTheme.colorScheme.onSecondaryContainer,
2914− maxLines = 2,
2915− overflow = TextOverflow.Ellipsis,
2916− )
2917− }
2918− IconButton(onClick = {
2919− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2920− onCancel()
2921− }) {
2922− Icon(
2923− Icons.Filled.Close,
2924− contentDescription = stringResource(R.string.cancel_quote_reply),
2925− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2926− modifier = Modifier.size(18.dp),
2927− )
2928− }
2929− }
2930− }
2931−}
2932−
2933−/** A banner shown while messages composed offline are queued in the outbox, with a
2934− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2935−@Composable
2936−private fun OutboxBanner(
2937− count: Int,
2938− sending: Boolean,
2939− onFlush: () -> Unit,
2940− onDiscard: () -> Unit,
2941−) {
2942− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
2943− Surface(
2944− color = MaterialTheme.colorScheme.secondaryContainer,
2945− tonalElevation = 2.dp,
2946− modifier = Modifier.fillMaxWidth(),
2947− ) {
2948− Row(
2949− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2950− verticalAlignment = Alignment.CenterVertically,
2951− horizontalArrangement = Arrangement.SpaceBetween,
2952− ) {
2953− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2954− if (sending) {
2955− CircularProgressIndicator(
2956− Modifier.size(16.dp),
2957− strokeWidth = 2.dp,
2958− color = MaterialTheme.colorScheme.onSecondaryContainer,
2959− )
2960− Spacer(Modifier.size(8.dp))
2961− }
2962− Text(
2963− if (sending) {
2964− stringResource(R.string.outbox_sending)
2965− } else {
2966− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2967− stringResource(res, count)
2968− },
2969− style = MaterialTheme.typography.bodySmall,
2970− color = MaterialTheme.colorScheme.onSecondaryContainer,
2971− )
2972− }
2973− if (!sending) {
2974− val haptics = LocalHapticFeedback.current
2975− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2976− TextButton(onClick = {
2977− // Confirm before discarding all queued messages (irreversible), matching
2978− // the confirmation pattern used by deleteSession and other destructive
2979− // actions. Previously a single tap dropped every queued message.
2980− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2981− showDiscardConfirm = true
2982− }) {
2983− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2984− }
2985− }
2986− }
2987− }
2988− if (showDiscardConfirm) {
2989− androidx.compose.material3.AlertDialog(
2990− onDismissRequest = { showDiscardConfirm = false },
2991− title = { Text(stringResource(R.string.discard_queued_title)) },
2992− text = { Text(stringResource(R.string.discard_queued_text, count)) },
2993− confirmButton = {
2994− androidx.compose.material3.TextButton(onClick = {
2995− showDiscardConfirm = false
2996− onDiscard()
2997− }) { Text(stringResource(R.string.discard)) }
2998− },
2999− dismissButton = {
3000− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3001− Text(stringResource(R.string.cancel))
3002− }
3003− },
3004− )
3005− }
3006−}
3007−
3008−/** Prompt for a one-off shell command to run in the session's worktree. */
3009−@Composable
3010−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3011− var command by rememberSaveable { mutableStateOf("") }
3012− AlertDialog(
3013− onDismissRequest = onDismiss,
3014− title = { Text(stringResource(R.string.run_shell_command)) },
3015− text = {
3016− OutlinedTextField(
3017− value = command,
3018− onValueChange = { command = it },
3019− modifier = Modifier.fillMaxWidth(),
3020− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3021− label = { Text(stringResource(R.string.shell_command_label)) },
3022− singleLine = true,
3023− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3024− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3025− )
3026− },
3027− confirmButton = {
3028− TextButton(
3029− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3030− enabled = command.isNotBlank(),
3031− ) { Text(stringResource(R.string.run)) }
3032− },
3033− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3034− )
3035−}
3036−
3037−/**
3038− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3039− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3040− * equality is structural so `snapshotFlow` emits only when something relevant changes.
3041− */
3042−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3043−
3044−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3045− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3046− * streaming, not just plain assistant text. O(1). */
3047−private fun streamingContentLength(part: Part?): Int = when (part) {
3048− is TextPart -> part.text.length
3049− is ReasoningPart -> part.text.length
3050− is ToolPart -> when (val st = part.state) {
3051− is ToolCompleted -> st.output?.length ?: 0
3052− is ToolError -> st.error?.length ?: 0
3053− is ToolRunning -> st.title?.length ?: 0
3054− else -> 0
3055− }
3056− else -> 0
3057−}
3058−
3059−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3060− * dialog but lives in the chat screen so the user can rename without backing out to
3061− * the list. Pre-filled with the current title; the cap matches the list dialog. */
3062−@Composable
3063−private fun RenameSessionChatDialog(
3064− initialTitle: String,
3065− onDismiss: () -> Unit,
3066− onConfirm: (String) -> Unit,
3067−) {
3068− // Seed the field once (no key input) so a later external title change — e.g. opencode
3069− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3070− // doesn't re-initialize the box and discard the user's in-progress edit.
3071− var title by rememberSaveable { mutableStateOf(initialTitle) }
3072− AlertDialog(
3073− onDismissRequest = onDismiss,
3074− title = { Text(stringResource(R.string.rename_session_chat)) },
3075− text = {
3076− OutlinedTextField(
3077− value = title,
3078− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3079− modifier = Modifier.fillMaxWidth(),
3080− placeholder = { Text(stringResource(R.string.session_title_hint)) },
3081− label = { Text(stringResource(R.string.rename_session_chat)) },
3082− singleLine = true,
3083− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3084− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3085− )
3086− },
3087− confirmButton = {
3088− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3089− Text(stringResource(R.string.save))
3090− }
3091− },
3092− dismissButton = {
3093− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3094− },
3095− )
3096−}
3097−
3098−/**
3099− * A single item in the chat message list — either a [Message] bubble or a day
3100− * [Separator] inserted before the first message of a new day. The separator shifts
3101− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3102− * the [List] of these items (not `messages.size`/`lastIndex`).
3103− */
3104−private sealed interface MessageListItem {
3105− val key: Any
3106− val contentType: Any
3107−
3108− data class Message(
3109− val message: MessageWithParts,
3110− override val key: Any,
3111− // Whether this is the first message in a consecutive run of the same speaker (role).
3112− // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3113− // reducing visual noise in tool-heavy conversations where many assistant messages
3114− // appear back-to-back. A separator or a role change resets the flag.
3115− val isFirstOfSpeaker: Boolean,
3116− ) : MessageListItem {
3117− override val contentType: Any get() = message.info::class
3118− }
3119−
3120− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3121− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3122− // can share a label (e.g. an untimestamped message — empty label — between two
3123− // same-day messages, or two untimestamped groups), and a label-only key would
3124− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3125− // stable for a given message ordering so slots aren't needlessly recreated.
3126− override val key: Any get() = "sep_${ordinal}_$label"
3127− // Separators share a contentType so the LazyColumn can recycle their slots.
3128− override val contentType: Any get() = "separator"
3129− }
3130−}
3131−
3132−/**
3133− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3134− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3135− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3136− * Messages with no timestamp are grouped under an empty-label separator only if they
3137− * start the list, so a server that omits timestamps doesn't suppress the first divider.
3138− *
3139− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3140− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3141− * labels; older days fall back to a locale-stable medium-date format.
3142− */
3143−private fun buildMessageListItems(
3144− messages: List<MessageWithParts>,
3145− todayLabel: String,
3146− yesterdayLabel: String,
3147−): List<MessageListItem> {
3148− if (messages.isEmpty()) return emptyList()
3149− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3150− val dateFmt = mediumDateFormat()
3151− val result = ArrayList<MessageListItem>(messages.size + 4)
3152− val seenKeys = HashSet<String>(messages.size * 2)
3153− var lastDayKey: String? = null
3154− var sepOrdinal = 0
3155− var emptyIdOrdinal = 0
3156− var first = true
3157− // Track the previous message's role to detect consecutive same-speaker runs, so the
3158− // avatar/header can be suppressed on follow-up messages in the same run. A null means
3159− // "no previous message or a separator just interrupted the run", both of which make the
3160− // next message the first of its group.
3161− var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3162− for (message in messages) {
3163− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3164− val dayKey = ts?.let { dayKey(it) } ?: ""
3165− // Emit a separator before the very first message (so a leading un-timestamped message
3166− // still gets the first divider, empty label and all), and thereafter only when crossing
3167− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3168− // neither emits its own separator nor resets the day — otherwise a following same-day
3169− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3170− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3171− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3172− // A date separator visually breaks a speaker run, so the next message is treated
3173− // as the first of its group (even if the same role continues across the day break).
3174− prevRoleClass = null
3175− }
3176− if (dayKey.isNotEmpty()) lastDayKey = dayKey
3177− first = false
3178− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3179− // empty id — and the reducer intentionally keeps several such messages as distinct
3180− // holders — so give each a stable synthetic key and defensively de-collide any remaining
3181− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3182− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3183− if (!seenKeys.add(key)) {
3184− var suffix = 1
3185− while (!seenKeys.add("$key#$suffix")) suffix++
3186− key = "$key#$suffix"
3187− }
3188− val roleClass = message.info::class
3189− val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3190− result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3191− prevRoleClass = roleClass
3192− }
3193− return result
3194−}
3195−
3196−/**
3197− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3198− *
3199− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3200− * whole `messages` list, which must stay so the live message's fresh parts render), so a
3201− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3202− * every message on every token. Message timestamps are immutable once assigned, so we
3203− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3204− * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3205− *
3206− * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3207− * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3208− * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3209− * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3210− * reads, so the common case (a hit) is a single volatile read + hash probe. The bound
3211− * is enforced via [removeEldestEntry] is not available on ConcurrentHashMap, so we cap
3212− * via `compute`-guarded size checks; in practice the cache size is bounded by the number
3213− * of distinct message timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]).
3214− */
3215−private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3216−
3217−private fun dayKey(epochMillis: Long): String = dayKeyCache.getOrPut(epochMillis) {
3218− java.time.Instant.ofEpochMilli(epochMillis)
3219− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3220−}
3221−
3222−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3223−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3224−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3225−private var cachedDateFmt: java.text.DateFormat? = null
3226−private var cachedDateFmtLocale: java.util.Locale? = null
3227−
3228−private fun mediumDateFormat(): java.text.DateFormat {
3229− val locale = java.util.Locale.getDefault()
3230− val existing = cachedDateFmt
3231− if (existing != null && cachedDateFmtLocale == locale) return existing
3232− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3233− cachedDateFmt = it
3234− cachedDateFmtLocale = locale
3235− }
3236−}
3237−
3238−/**
3239− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3240− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3241− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3242− * messages.
3243− */
3244−private fun dayLabel(
3245− dayKey: String,
3246− ts: Long,
3247− today: java.time.LocalDate,
3248− todayLabel: String,
3249− yesterdayLabel: String,
3250− dateFmt: java.text.DateFormat,
3251−): String {
3252− if (dayKey.isEmpty()) return ""
3253− val epochDay = dayKey.toLongOrNull() ?: return ""
3254− val date = java.time.LocalDate.ofEpochDay(epochDay)
3255− return when {
3256− date == today -> todayLabel
3257− date == today.minusDays(1) -> yesterdayLabel
3258− else -> dateFmt.format(java.util.Date(ts))
3259− }
3260−}
3261−
3262−/**
3263− * A centered day divider in the message list. Renders nothing for an empty label
3264− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3265− */
3266−@Composable
3267−private fun DateSeparator(label: String) {
3268− if (label.isBlank()) return
3269− Row(
3270− modifier = Modifier.fillMaxWidth(),
3271− horizontalArrangement = Arrangement.Center,
3272− ) {
3273− Surface(
3274− color = MaterialTheme.colorScheme.surfaceVariant,
3275− shape = MaterialTheme.shapes.small,
3276− // Marked as a heading so TalkBack users can navigate day-by-day with the
3277− // heading-skip gesture — the canonical affordance for date dividers in a list.
3278− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3279− ) {
3280− Text(
3281− label,
3282− style = MaterialTheme.typography.labelSmall,
3283− color = MaterialTheme.colorScheme.onSurfaceVariant,
3284− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3285− )
3286− }
3287− }
3288−}
3289−
3290−/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3291− * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3292− * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3293− * [BoxScope] extension so it can align itself to the top center of its host box. */
3294−@Composable
3295−private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3296− val loadingLabel = stringResource(R.string.loading)
3297− val reducedMotion = LocalReducedMotion.current
3298− val transition = rememberInfiniteTransition(label = "skeleton")
3299− val pulse by transition.animateFloat(
3300− initialValue = 0.35f,
3301− targetValue = 0.7f,
3302− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3303− label = "skeletonAlpha",
3304− )
3305− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3306− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3307− @Composable
3308− fun bar(widthFraction: Float) {
3309− Box(
3310− Modifier
3311− .fillMaxWidth(widthFraction)
3312− .height(14.dp)
3313− .clip(RoundedCornerShape(4.dp))
3314− .background(skeletonColor)
3315− .alpha(skeletonAlpha),
3316− )
3317− }
3318− Column(
3319− modifier = Modifier
3320− .align(Alignment.TopCenter)
3321− .padding(top = topPad)
3322− .padding(16.dp)
3323− .fillMaxWidth()
3324− .semantics { contentDescription = loadingLabel },
3325− verticalArrangement = Arrangement.spacedBy(14.dp),
3326− ) {
3327− repeat(4) { i ->
3328− val left = i % 2 == 0
3329− Row(
3330− modifier = Modifier.fillMaxWidth(),
3331− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3332− ) {
3333− Column(
3334− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3335− verticalArrangement = Arrangement.spacedBy(6.dp),
3336− ) {
3337− bar(1f)
3338− bar(0.8f)
3339− }
3340− }
3341− }
3342− }
3343−}
app/src/main/java/soy/iko/opencode/ui/chat/ChatViewModel.ktdeleted−1948
@@ -1,1948 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import androidx.lifecycle.ViewModel
4−import androidx.lifecycle.viewModelScope
5−import soy.iko.opencode.data.model.Agent
6−import soy.iko.opencode.data.model.Command
7−import soy.iko.opencode.data.model.FilePromptPart
8−import soy.iko.opencode.data.model.MessageWithParts
9−import soy.iko.opencode.data.model.ModelOption
10−import soy.iko.opencode.data.model.UserMessage
11−import soy.iko.opencode.data.model.Permission
12−import soy.iko.opencode.data.model.PermissionReplied
13−import soy.iko.opencode.data.model.PermissionResponse
14−import soy.iko.opencode.data.model.PermissionUpdated
15−import soy.iko.opencode.data.model.SessionDeleted
16−import soy.iko.opencode.data.model.SessionUpdated
17−import soy.iko.opencode.data.model.TextPart
18−import soy.iko.opencode.data.model.TodoItem
19−import soy.iko.opencode.data.model.TodoPlanCache
20−import soy.iko.opencode.data.model.currentTodoPlan
21−import soy.iko.opencode.data.model.defaultOption
22−import soy.iko.opencode.data.model.toOptions
23−import soy.iko.opencode.data.network.EventStreamClient
24−import soy.iko.opencode.data.network.NetworkConfig
25−import soy.iko.opencode.data.repo.OutboxMessage
26−import soy.iko.opencode.data.repo.SessionRepository
27−import soy.iko.opencode.di.AppContainer
28−import soy.iko.opencode.R
29−import soy.iko.opencode.util.runCatchingCancellable
30−import soy.iko.opencode.util.safeExceptionSummary
31−import android.util.Log
32−import kotlinx.coroutines.ExperimentalCoroutinesApi
33−import kotlinx.coroutines.channels.BufferOverflow
34−import kotlinx.coroutines.channels.Channel
35−import kotlinx.coroutines.flow.Flow
36−import kotlinx.coroutines.flow.MutableSharedFlow
37−import kotlinx.coroutines.flow.MutableStateFlow
38−import kotlinx.coroutines.flow.SharedFlow
39−import kotlinx.coroutines.flow.SharingStarted
40−import kotlinx.coroutines.flow.StateFlow
41−import kotlinx.coroutines.flow.asSharedFlow
42−import kotlinx.coroutines.flow.asStateFlow
43−import kotlinx.coroutines.flow.receiveAsFlow
44−import kotlinx.coroutines.CancellationException
45−import kotlinx.coroutines.flow.collectLatest
46−import kotlinx.coroutines.flow.combine
47−import kotlinx.coroutines.flow.debounce
48−import kotlinx.coroutines.flow.distinctUntilChanged
49−import kotlinx.coroutines.flow.drop
50−import kotlinx.coroutines.flow.first
51−import kotlinx.coroutines.flow.filterIsInstance
52−import kotlinx.coroutines.flow.flatMapLatest
53−import kotlinx.coroutines.flow.flowOf
54−import kotlinx.coroutines.flow.flowOn
55−import kotlinx.coroutines.flow.map
56−import kotlinx.coroutines.flow.merge
57−import kotlinx.coroutines.flow.onEach
58−import kotlinx.coroutines.flow.retryWhen
59−import kotlinx.coroutines.flow.stateIn
60−import kotlinx.coroutines.flow.update
61−import kotlinx.coroutines.Dispatchers
62−import kotlinx.coroutines.Job
63−import kotlinx.coroutines.NonCancellable
64−import kotlinx.coroutines.delay
65−import kotlinx.coroutines.isActive
66−import kotlinx.coroutines.currentCoroutineContext
67−import kotlinx.coroutines.launch
68−import kotlinx.coroutines.withContext
69−
70−/**
71− * A user-facing error to surface as a snackbar. [retryable] is true only for a failed
72− * message *send* (whose draft is held in [ChatViewModel.failedDraft]); the snackbar attaches
73− * a Retry action solely for those so an unrelated error (e.g. a message-load failure) can't
74− * inherit a Retry that silently re-submits the last prompt.
75− */
76−data class ChatError(val message: String, val retryable: Boolean = false)
77−
78−/**
79− * Progress of the current permission within a burst of requests. [total] is the max number
80− * simultaneously pending since the queue was last empty; [position] advances as the user clears
81− * the backlog. A [total] of 0/1 means there's no meaningful backlog to surface.
82− */
83−@androidx.compose.runtime.Immutable
84−data class PermissionProgress(val position: Int, val total: Int)
85−
86−/**
87− * An attachment staged to send with the next prompt. [previewModel] is a Coil-loadable model
88− * for the thumbnail (the source content Uri, as a string) for images, or null for non-image
89− * files (rendered with a generic icon). [part] is the wire form (a base64 data URL) sent to
90− * the server.
91− */
92−@androidx.compose.runtime.Immutable
93−data class PendingAttachment(
94− val id: String,
95− val name: String,
96− val mime: String,
97− val previewModel: Any?,
98− val part: FilePromptPart,
99−) {
100− val isImage: Boolean get() = mime.startsWith("image/")
101−}
102−
103−/** Reduce a staged attachment to its persistable form (the self-contained data URL). */
104−private fun PendingAttachment.toPersisted() =
105− soy.iko.opencode.data.repo.PersistedAttachment(id, name, mime, part.url, part.filename)
106−
107−/** Rebuild a staged attachment from persistence. The base64 data URL doubles as the Coil
108− * preview model for images (the original content Uri didn't survive the process restart). */
109−private fun soy.iko.opencode.data.repo.PersistedAttachment.toPending() = PendingAttachment(
110− id = id,
111− name = name,
112− mime = mime,
113− previewModel = if (mime.startsWith("image/")) url else null,
114− part = FilePromptPart(mime = mime, url = url, filename = filename),
115−)
116−
117−// Large by design: this VM owns the whole chat surface (streaming, drafts, attachments,
118−// catalogs, permissions, revert/edit, sharing, summarize/init/shell, TTS wiring). It's
119−// already grandfathered for TooManyFunctions in the detekt baseline; the class-size rule is
120−// suppressed for the same reason. A future split into sub-controllers is tracked separately.
121−@Suppress("LargeClass")
122−@OptIn(ExperimentalCoroutinesApi::class, kotlinx.coroutines.FlowPreview::class)
123−class ChatViewModel(
124− private val container: AppContainer,
125− private val sessionId: String,
126−) : ViewModel() {
127−
128− private val connection get() = container.activeConnection.value
129−
130− val connected: Boolean get() = connection != null
131−
132− private val _loading = MutableStateFlow(true)
133− val loading: StateFlow<Boolean> = _loading.asStateFlow()
134−
135− /** Set when the messages flow failed to load (and the list is empty), so the UI
136− * can render a distinct error state instead of masquerading as an empty
137− * conversation. Cleared on a successful non-empty emission. */
138− private val _loadError = MutableStateFlow(false)
139− val loadError: StateFlow<Boolean> = _loadError.asStateFlow()
140−
141− /** Set when a re-fetch fails mid-conversation (messages already visible). Distinct
142− * from [loadError] (which replaces the whole content with an error screen): this
143− * surfaces as a persistent inline banner above the message list so a persistent
144− * outage doesn't go silent after the one-shot snackbar. Cleared on the next
145− * successful emission. */
146− private val _loadErrorInline = MutableStateFlow(false)
147− val loadErrorInline: StateFlow<Boolean> = _loadErrorInline.asStateFlow()
148−
149− /** Tracks whether the messages flow has ever emitted a non-empty list, so
150− * [messages]' retryWhen can decide whether a re-fetch failure should set
151− * [loadError] (nothing shown yet → error screen) or just emit a snackbar
152− * (already showing messages → don't replace the conversation with an error). */
153− private var hasShownMessages = false
154−
155− /** True once we've surfaced a snackbar for the current message-load failure streak.
156− * Reset on any successful emission so a persistent failure doesn't spam a fresh
157− * snackbar every retry cycle (every few seconds). */
158− private var loadErrorSnackbarShown = false
159−
160− /** Separate from [loading]: tracks the manual reconnect() flow so its spinner
161− * doesn't conflict with the messages flow's loading state. */
162− private val _reconnecting = MutableStateFlow(false)
163− val reconnecting: StateFlow<Boolean> = _reconnecting.asStateFlow()
164−
165− /** When true, the debounced draft collector skips persisting an empty draft so
166− * [send]'s deliberate non-persistence of the cleared draft isn't undone by the
167− * debounce timer firing before the send completes. */
168− private val suppressDraftPersist = java.util.concurrent.atomic.AtomicBoolean(false)
169−
170− /** The draft value this VM last persisted, so the drafts observer can tell its own
171− * (debounced, possibly stale) echo apart from a genuine external write. Without this
172− * a debounced persist of an older value could echo back and overwrite newer text the
173− * user has since typed. */
174− @Volatile private var lastPersistedDraft: String? = null
175−
176− /** Per-catalog reload triggers: incrementing one causes [observeCatalog]'s
177− * collectLatest to cancel any in-flight fetch and start a fresh one, so a
178− * manual reload supersedes a stale observeCatalog fetch. */
179− private val _modelsReload = MutableStateFlow(0)
180− private val _agentsReload = MutableStateFlow(0)
181− private val _commandsReload = MutableStateFlow(0)
182−
183− /** An optimistically-injected user message shown immediately on send, before the server
184− * echoes the real message back via SSE. Removed once a matching UserMessage arrives. */
185− data class OptimisticEntry(val tempId: String, val text: String, val timestamp: Long, val failed: Boolean)
186−
187− private val _optimisticMessages = MutableStateFlow<List<OptimisticEntry>>(emptyList())
188−
189− /** SSE-driven message stream with retry/backoff and loading/error side effects. Combined
190− * with [_optimisticMessages] by [messages] so the user sees their outgoing prompt instantly. */
191− private val sseMessages: Flow<List<MessageWithParts>> =
192− container.activeConnection
193− .flatMapLatest { conn ->
194− conn?.repository?.observeMessages(sessionId) ?: flowOf(emptyList())
195− }
196− .onEach {
197− _loading.value = false
198− // A value flowed through: the stream recovered, so allow the next distinct
199− // failure to surface a fresh snackbar again.
200− loadErrorSnackbarShown = false
201− // Clear the error on ANY successful emission, including an empty list. An empty
202− // session that hit one transient error would otherwise stay latched on the
203− // "Failed to load / Retry" screen forever, because the later successful EMPTY
204− // emission couldn't clear the flag. hasShownMessages stays gated on non-empty
205− // (an empty session has genuinely shown nothing yet).
206− _loadError.value = false
207− _loadErrorInline.value = false
208− if (it.isNotEmpty()) {
209− hasShownMessages = true
210− }
211− // Reconcile optimistic messages: drop any whose text now matches a real SSE
212− // UserMessage (the server echoed the prompt back). Matching by trimmed text,
213− // removing the oldest match first so duplicate texts are handled in order.
214− reconcileOptimistic(it)
215− }
216− .retryWhen { cause, attempt ->
217− _loading.value = false
218− // Only surface the persistent error state when there's nothing to
219− // show — if we already have messages, a transient re-fetch failure
220− // is better surfaced as a snackbar (via errorEvents) than by
221− // replacing the visible conversation with an error screen.
222− if (!hasShownMessages) _loadError.value = true
223− // Mid-conversation failure: surface a persistent inline banner so
224− // the user knows the stream is broken (the one-shot snackbar alone
225− // reads as "recovered" once it dismisses). Cleared on recovery.
226− if (hasShownMessages) _loadErrorInline.value = true
227− // Surface the snackbar only once per failure streak — retryWhen loops on a
228− // backoff, so emitting here unconditionally would spam a new snackbar every
229− // retry on a persistent load failure.
230− if (!loadErrorSnackbarShown) {
231− _errorEvents.trySend(ChatError(container.friendlyError(cause)))
232− loadErrorSnackbarShown = true
233− }
234− // Exponential backoff capped at retryMaxDelayMs so a persistently failing
235− // server is retried with growing delays (retryInitialDelayMs, then doubling)
236− // instead of hammered at a fixed interval forever. Clamp the shift so a long
237− // failure streak can't overflow the Long delay.
238− val backoffMs = (NetworkConfig.retryInitialDelayMs shl attempt.coerceAtMost(16L).toInt())
239− .coerceAtMost(NetworkConfig.retryMaxDelayMs)
240− delay(backoffMs)
241− true
242− }
243−
244− val messages: StateFlow<List<MessageWithParts>> =
245− combine(sseMessages, _optimisticMessages) { sse, optimistic ->
246− mergeOptimistic(sse, optimistic)
247− }.stateIn(
248− scope = viewModelScope,
249− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
250− initialValue = emptyList(),
251− )
252−
253− /** Whether the conversation has any messages. Derived separately so the top bar
254− * (share button enabled state) can observe this cheap boolean instead of the
255− * full messages list, avoiding per-token recomposition of the app bar during
256− * streaming. */
257− val hasMessages: StateFlow<Boolean> = messages
258− .map { it.isNotEmpty() }
259− .stateIn(
260− scope = viewModelScope,
261− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
262− initialValue = false,
263− )
264−
265− /** Map of optimistic message tempId → failed flag, so the UI can render a "Sending…"
266− * or "Failed to send" indicator on the corresponding message bubble. */
267− val optimisticStatuses: StateFlow<Map<String, Boolean>> = _optimisticMessages
268− .map { entries -> entries.associate { it.tempId to it.failed } }
269− .stateIn(
270− scope = viewModelScope,
271− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
272− initialValue = emptyMap(),
273− )
274−
275− /** Merge SSE-driven messages with optimistic entries. An optimistic entry whose trimmed
276− * text matches a real [UserMessage] in [sse] is dropped (the server echoed it back).
277− * Remaining entries are appended as synthetic [UserMessage]s at the end. Failed entries
278− * are kept so the user sees the failed indicator until they retry or dismiss. */
279− private fun mergeOptimistic(
280− sse: List<MessageWithParts>,
281− optimistic: List<OptimisticEntry>,
282− ): List<MessageWithParts> {
283− if (optimistic.isEmpty()) return sse
284− // Collect the text of real user messages so optimistic entries can be matched.
285− val realUserTexts = mutableSetOf<String>()
286− for (msg in sse) {
287− if (msg.info !is UserMessage) continue
288− val text = msg.parts.filterIsInstance<TextPart>()
289− .joinToString("\n\n") { it.text }
290− .trim()
291− if (text.isNotEmpty()) realUserTexts.add(text)
292− }
293− val surviving = optimistic.filter { it.text.trim() !in realUserTexts }
294− if (surviving.isEmpty()) return sse
295− return sse + surviving.map { it.toMessageWithParts() }
296− }
297−
298− /** Remove optimistic entries whose text now matches a real user message delivered by SSE.
299− * Called from the SSE flow's onEach so stale optimistic entries are cleaned up promptly. */
300− private fun reconcileOptimistic(sse: List<MessageWithParts>) {
301− if (_optimisticMessages.value.isEmpty()) return
302− val realUserTexts = mutableSetOf<String>()
303− for (msg in sse) {
304− if (msg.info !is UserMessage) continue
305− val text = msg.parts.filterIsInstance<TextPart>()
306− .joinToString("\n\n") { it.text }
307− .trim()
308− if (text.isNotEmpty()) realUserTexts.add(text)
309− }
310− if (realUserTexts.isEmpty()) return
311− _optimisticMessages.update { entries ->
312− entries.filterNot { it.text.trim() in realUserTexts }
313− }
314− }
315−
316− /** Convert an optimistic entry to a [MessageWithParts] for display. */
317− private fun OptimisticEntry.toMessageWithParts(): MessageWithParts = MessageWithParts(
318− info = UserMessage(
319− id = tempId,
320− sessionID = sessionId,
321− time = soy.iko.opencode.data.model.TimeInfo(created = timestamp),
322− ),
323− parts = listOf(TextPart(id = "$tempId-text", text = text)),
324− )
325−
326− /** The agent's current task plan (the latest `todowrite`), surfaced so the chat can pin a
327− * live progress checklist above the composer. distinctUntilChanged so a per-token messages
328− * emission that doesn't change the plan doesn't recompose the bar.
329− *
330− * A [TodoPlanCache] memoizes the scan against the input list's identity, so a `combine`
331− * re-evaluation that re-emits the same list instance (e.g. when the optimistic-messages
332− * StateFlow updates without an SSE change) skips the O(messages×parts) re-scan. */
333− private val todoPlanCache = TodoPlanCache()
334− val todoPlan: StateFlow<List<TodoItem>> = messages
335− .map { todoPlanCache.plan(it) }
336− // Run the scan off the main thread: it's an O(messages×parts) scan (worst case
337− // when the conversation has no todowrite) and runs on every conflated messages emission.
338− // distinctUntilChanged is downstream so it dedupes the result but doesn't prevent the
339− // scan — without flowOn this scans on Main.immediate per streamed token → jank.
340− .flowOn(Dispatchers.Default)
341− .distinctUntilChanged()
342− .stateIn(
343− scope = viewModelScope,
344− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
345− initialValue = emptyList(),
346− )
347−
348− private val _running = MutableStateFlow(false)
349− val running: StateFlow<Boolean> = _running.asStateFlow()
350−
351− /**
352− * True when the SSE stream dropped mid-run (a transient [Disconnected] while a run is
353− * active). The UI uses this to switch the working indicator to a "stream interrupted /
354− * reconnecting" visual instead of clearing [_running] outright — the run is still active
355− * on the server, so showing it as finished would mislead the user into typing a follow-up
356− * or navigating away. Cleared when the stream reconnects ([Connected]) or when a hard
357− * failure ([Failed]/[AuthFailed]) genuinely clears [_running]. See the state watcher in
358− * [init]. */
359− private val _streamInterrupted = MutableStateFlow(false)
360− val streamInterrupted: StateFlow<Boolean> = _streamInterrupted.asStateFlow()
361−
362− /**
363− * Wall-clock millis at which the current run started (0L when no run is active). Drives
364− * the typing row's elapsed timer so it survives LazyColumn recycling — a local `remember`
365− * in the row resets to 0:00 when the row is disposed and scrolled back into view. Stamped
366− * only on a real false→[beginRun] transition (send/run/init), not on SSE-reconnect relight
367− * (which continues an existing run and should keep its original elapsed time).
368− */
369− private val _runStartMs = MutableStateFlow(0L)
370− val runStartMs: StateFlow<Long> = _runStartMs.asStateFlow()
371−
372− /**
373− * Atomically transition `_running` false→true and stamp the run-start timestamp. Returns
374− * false (with no state change) when a run is already in flight, so callers can surface a
375− * "busy" message instead of silently dropping the action. Centralizes the transition so
376− * every run-start path captures [runStartMs] consistently.
377− */
378− private fun beginRun(): Boolean {
379− if (!_running.compareAndSet(false, true)) return false
380− _runStartMs.value = System.currentTimeMillis()
381− return true
382− }
383−
384− /** True once the current run ended via SessionIdle/SessionError, until the next run starts
385− * (a send) or an SSE reconnect. Gates the run-indicator re-light below: isRunActivity
386− * returns true for ANY message.part.updated, so without this a trailing/replayed part
387− * arriving after a legitimate SessionIdle would re-light the "working" indicator with no
388− * further idle to clear it — a stuck spinner + foreground service. Cleared on reconnect so
389− * genuine reconnect-recovery re-lighting (its actual purpose) still works. */
390− @Volatile private var runEndedByIdle = false
391−
392− /** The in-flight REST title resolution for the current connection. Launched from — and
393− * cancelled by — the per-connection reset block so it can't observe or restore a previous
394− * server's stale title. */
395− private var sessionTitleJob: Job? = null
396−
397− /** True while an abort REST call is in flight, so the Stop button can show a
398− * spinner and prevent double-taps from firing a second abort. */
399− private val _aborting = MutableStateFlow(false)
400− val aborting: StateFlow<Boolean> = _aborting.asStateFlow()
401−
402− /** A follow-up the user typed while a run was active. send() queues it here and
403− * auto-sends once the run completes (SessionIdle), so the user isn't blocked with
404− * no way to send and no indication why the Send button is gone. */
405− private val _queuedFollowUp = MutableStateFlow<String?>(null)
406− val queuedFollowUp: StateFlow<String?> = _queuedFollowUp.asStateFlow()
407−
408− /** The text of the most recently-sent user prompt (captured in [send]), so an undo-able
409− * Stop can re-send it. Only text-bearing prompts are tracked — an image-only prompt has
410− * nothing to re-send text-wise. Cleared when a new run starts with different text. */
411− private var lastSentPrompt: String? = null
412−
413− /** One-shot event signals for an undoable Stop. The UI collects this and shows an
414− * "Stopped — Undo" snackbar; tapping Undo calls [resendLastPrompt]. A Channel so an
415− * emit before the UI subscribes is still delivered. */
416− private val _stopUndoEvents = Channel<String?>(Channel.CONFLATED)
417− val stopUndoEvents: Flow<String?> = _stopUndoEvents.receiveAsFlow()
418−
419− /** One-shot error events surfaced as snackbars. A Channel (not SharedFlow) so an event
420− * emitted before the UI subscribes is buffered and still delivered — a SharedFlow with
421− * replay=0 would drop it (e.g. a VM-init catalog fetch failing before first
422− * composition). Each event is delivered exactly once and not replayed to a
423− * re-subscribing collector, so rotation doesn't re-show a stale snackbar. */
424− private val _errorEvents = Channel<ChatError>(
425− capacity = NetworkConfig.snackbarEventBufferCapacity,
426− onBufferOverflow = BufferOverflow.DROP_OLDEST,
427− )
428− val errorEvents: Flow<ChatError> = _errorEvents.receiveAsFlow()
429−
430− /** One-shot events signaling a user-initiated delete was scheduled and is undoable in-place.
431− * The ChatScreen collects these to show an Undo snackbar over the conversation the user is
432− * already viewing, instead of navigating away first and surfacing Undo on the session list. */
433− private val _deleteUndoEvents = MutableSharedFlow<Unit>(
434− extraBufferCapacity = 1,
435− onBufferOverflow = BufferOverflow.DROP_OLDEST,
436− )
437− val deleteUndoEvents: SharedFlow<Unit> = _deleteUndoEvents.asSharedFlow()
438−
439− private val _models = MutableStateFlow<List<ModelOption>>(emptyList())
440− val models: StateFlow<List<ModelOption>> = _models.asStateFlow()
441−
442− private val _modelsLoading = MutableStateFlow(true)
443− val modelsLoading: StateFlow<Boolean> = _modelsLoading.asStateFlow()
444−
445− private val _modelsError = MutableStateFlow(false)
446− val modelsError: StateFlow<Boolean> = _modelsError.asStateFlow()
447−
448− private val _selectedModel = MutableStateFlow<ModelOption?>(null)
449− val selectedModel: StateFlow<ModelOption?> = _selectedModel.asStateFlow()
450−
451− val connectionState: StateFlow<EventStreamClient.ConnectionState> =
452− container.activeConnection
453− .flatMapLatest { it?.events?.state ?: flowOf(EventStreamClient.ConnectionState.Disconnected) }
454− .stateIn(
455− scope = viewModelScope,
456− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
457− initialValue = EventStreamClient.ConnectionState.Disconnected,
458− )
459−
460− /** SSE reconnect-attempt count for the active connection, surfaced so the chat's
461− * connection banner can show "Reconnecting (attempt N)…" during a sustained outage. */
462− val reconnectAttempts: StateFlow<Int> =
463− container.activeConnection
464− .flatMapLatest { it?.events?.reconnectAttempts ?: flowOf(0) }
465− .stateIn(
466− scope = viewModelScope,
467− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
468− initialValue = 0,
469− )
470−
471− private val _pendingPermission = MutableStateFlow<Permission?>(null)
472− val pendingPermission: StateFlow<Permission?> = _pendingPermission.asStateFlow()
473−
474− /** Backlog indicator for the permission dialog (see [PermissionProgress]). */
475− private val _permissionProgress = MutableStateFlow(PermissionProgress(0, 0))
476− val permissionProgress: StateFlow<PermissionProgress> = _permissionProgress.asStateFlow()
477−
478− /** Max number of permissions simultaneously pending since the queue was last empty. Reset
479− * to 0 when the queue drains, so a fresh burst starts its count over. */
480− private var maxPendingSeen = 0
481−
482− // Unanswered permission requests keyed by id, insertion-ordered. The dialog shows the most
483− // recent; when one is answered/replied — or a response fails — we fall back to the next so a
484− // request that arrived while another was in flight isn't silently dropped (its tool run would
485− // otherwise stay paused server-side with no UI affordance). Only touched on the VM's main
486− // dispatcher (event collector + viewModelScope launches), so no extra synchronization is needed.
487− private val pendingPermissions = LinkedHashMap<String, Permission>()
488−
489− // Session-scoped permission grants (Allow-for-this-session). Each entry is a (type, patternText)
490− // pair the user approved with PermissionResponse.SESSION. Subsequent matching requests are
491− // auto-responded ONCE without showing the dialog, so e.g. a user granting "read" for one path
492− // isn't re-prompted for every other file read in the same conversation. Cleared on connection
493− // change (see the activeConnection collector) so it never leaks across servers. The server only
494− // knows once/always/reject; SESSION is a client-side scope that maps to ONCE on the wire.
495− private val sessionAllowed = mutableSetOf<Pair<String, String>>()
496−
497− private fun enqueuePermission(permission: Permission) {
498− // Auto-respond to a permission whose (type, pattern) the user previously granted for this
499− // session, instead of showing the dialog again. Resolved immediately (not via the queue) so
500− // the tool run isn't paused waiting for a dialog the user will never see.
501− val type = permission.type.orEmpty()
502− val pattern = permission.patternText.orEmpty()
503− if (type.isNotEmpty() && sessionAllowed.contains(type to pattern)) {
504− respondPermission(permission, PermissionResponse.ONCE)
505− return
506− }
507− pendingPermissions[permission.id] = permission
508− _pendingPermission.value = pendingPermissions.values.lastOrNull()
509− updatePermissionProgress()
510− }
511−
512− private fun resolvePermission(id: String) {
513− pendingPermissions.remove(id)
514− _pendingPermission.value = pendingPermissions.values.lastOrNull()
515− updatePermissionProgress()
516− }
517−
518− private fun clearPermissions() {
519− pendingPermissions.clear()
520− _pendingPermission.value = null
521− updatePermissionProgress()
522− }
523−
524− /** Recompute the "N of M" backlog indicator. [maxPendingSeen] grows with the queue and
525− * resets only when it drains, so position = total - remaining + 1 advances as requests are
526− * answered. */
527− private fun updatePermissionProgress() {
528− val remaining = pendingPermissions.size
529− if (remaining == 0) {
530− maxPendingSeen = 0
531− _permissionProgress.value = PermissionProgress(0, 0)
532− return
533− }
534− if (remaining > maxPendingSeen) maxPendingSeen = remaining
535− _permissionProgress.value = PermissionProgress(
536− position = maxPendingSeen - remaining + 1,
537− total = maxPendingSeen,
538− )
539− }
540−
541− private val _agents = MutableStateFlow<List<Agent>>(emptyList())
542− val agents: StateFlow<List<Agent>> = _agents.asStateFlow()
543−
544− private val _agentsLoading = MutableStateFlow(true)
545− val agentsLoading: StateFlow<Boolean> = _agentsLoading.asStateFlow()
546−
547− private val _agentsError = MutableStateFlow(false)
548− val agentsError: StateFlow<Boolean> = _agentsError.asStateFlow()
549−
550− private val _selectedAgent = MutableStateFlow<String?>(null)
551− val selectedAgent: StateFlow<String?> = _selectedAgent.asStateFlow()
552−
553− private val _commands = MutableStateFlow<List<Command>>(emptyList())
554− val commands: StateFlow<List<Command>> = _commands.asStateFlow()
555−
556− private val _commandsLoading = MutableStateFlow(true)
557− val commandsLoading: StateFlow<Boolean> = _commandsLoading.asStateFlow()
558−
559− private val _commandsError = MutableStateFlow(false)
560− val commandsError: StateFlow<Boolean> = _commandsError.asStateFlow()
561−
562− private val _sessionTitle = MutableStateFlow<String?>(null)
563− val sessionTitle: StateFlow<String?> = _sessionTitle.asStateFlow()
564−
565− /** Set when the current session is deleted via SSE, so the UI can navigate away. */
566− private val _sessionDeleted = MutableStateFlow(false)
567− val sessionDeleted: StateFlow<Boolean> = _sessionDeleted.asStateFlow()
568−
569− /** The text of the last send that failed, surfaced so the UI can offer a retry. */
570− private val _failedDraft = MutableStateFlow<String?>(null)
571− val failedDraft: StateFlow<String?> = _failedDraft.asStateFlow()
572−
573− /** The idempotency key of the last failed online send, stashed alongside [_failedDraft] so
574− * [retryFailed] re-submits with the SAME key. A retry after a lost response is then
575− * deduplicated server-side instead of starting a duplicate agent run. */
576− @Volatile private var failedIdempotencyKey: String? = null
577−
578− /** Per-session draft, persisted so it survives navigation/process death. */
579− private val _draft = MutableStateFlow(container.draftStore.get(sessionId))
580− val draft: StateFlow<String> = _draft.asStateFlow()
581−
582− /** A pending quote-reply preview (the raw text the user quoted), shown as a dismissible
583− * card above the composer so the user can see and cancel the quote before sending. Cleared
584− * on send or via [cancelQuoteReply]. The actual `>` prefixed lines are still folded into
585− * the draft for the server; this state is purely for the visual preview chip. */
586− private val _pendingQuote = MutableStateFlow<String?>(null)
587− val pendingQuote: StateFlow<String?> = _pendingQuote.asStateFlow()
588−
589− /** Messages composed for this session while offline/disconnected, queued in the outbox and
590− * awaiting an automatic flush on reconnect. Surfaced so the composer can show a "queued"
591− * chip with a discard/send-now affordance. */
592− val outbox: StateFlow<List<OutboxMessage>> =
593− container.outboxStore.messages
594− .map { list -> list.filter { it.sessionId == sessionId } }
595− .stateIn(
596− scope = viewModelScope,
597− started = SharingStarted.WhileSubscribed(NetworkConfig.stateFlowSubscriptionTimeoutMs),
598− initialValue = emptyList(),
599− )
600−
601− /** Attachments staged for the next prompt (images/files). Persisted per-session (as their
602− * self-contained base64 data URLs) via [AttachmentDraftStore] so an interrupted compose
603− * survives process death — the source content Uris wouldn't survive, but the data URLs
604− * do. Cleared on a successful send. */
605− private val _attachments = MutableStateFlow<List<PendingAttachment>>(emptyList())
606− val attachments: StateFlow<List<PendingAttachment>> = _attachments.asStateFlow()
607−
608− // Count of picks currently being read + base64-encoded off the main thread, so the
609− // composer can show a staging placeholder immediately (chips only materialize once done).
610− // Exposed as StateFlows (not Compose state) so they survive a config change: the staging
611− // work runs on viewModelScope (which survives rotation), so the counters must live on the
612− // VM too — remember { mutableStateOf(0) } in the composable would reset to 0 on rotation
613− // and lose the staging chip mid-encode.
614− private val _stagingCount = MutableStateFlow(0)
615− val stagingCount: StateFlow<Int> = _stagingCount.asStateFlow()
616− // Total number of files still being staged across all in-flight batches, so the
617− // staging chip can show "Staging N files…" rather than a bare indeterminate spinner.
618− private val _stagingFileTotal = MutableStateFlow(0)
619− val stagingFileTotal: StateFlow<Int> = _stagingFileTotal.asStateFlow()
620−
621− /** True while a revert checkpoint is active for this session (messages after it are hidden
622− * server-side). Drives the "reverted" banner with its Undo. */
623− private val _reverted = MutableStateFlow(false)
624− val reverted: StateFlow<Boolean> = _reverted.asStateFlow()
625−
626− /** True when the revert was triggered by an Edit action (vs a bare Revert). Drives the
627− * banner's copy so it reads "Editing message" rather than "Reverted", making the composer's
628− * prefilled text unambiguous. Cleared on unrevert and on send. */
629− private val _editing = MutableStateFlow(false)
630− val editing: StateFlow<Boolean> = _editing.asStateFlow()
631−
632− /** The diff of the active revert checkpoint, when the server includes one. Shown in the
633− * revert banner so the user can see what changed before deciding to undo. Null when the
634− * session isn't reverted or the server didn't send a diff. */
635− private val _revertDiff = MutableStateFlow<String?>(null)
636− val revertDiff: StateFlow<String?> = _revertDiff.asStateFlow()
637−
638− /** The active public share URL for this session, or null when not shared. */
639− private val _shareUrl = MutableStateFlow<String?>(null)
640− val shareUrl: StateFlow<String?> = _shareUrl.asStateFlow()
641−
642− /** One-shot events carrying a freshly-created share URL so the UI can copy/share it. */
643− private val _shareLinkEvents = Channel<String>(
644− capacity = NetworkConfig.snackbarEventBufferCapacity,
645− onBufferOverflow = BufferOverflow.DROP_OLDEST,
646− )
647− val shareLinkEvents: Flow<String> = _shareLinkEvents.receiveAsFlow()
648−
649− /** One-shot events carrying the id of a session freshly branched from a message, so the
650− * UI can navigate to it. */
651− private val _branchEvents = Channel<String>(
652− capacity = NetworkConfig.snackbarEventBufferCapacity,
653− onBufferOverflow = BufferOverflow.DROP_OLDEST,
654− )
655− val branchEvents: Flow<String> = _branchEvents.receiveAsFlow()
656−
657− init {
658− // DraftStore loads SharedPreferences asynchronously; on a cold start the
659− // synchronous get() above returns "" until the background load completes.
660− // Observe the ready signal and re-seed the draft so it appears in the UI.
661− viewModelScope.launch {
662− container.draftStore.ready.collect { ready ->
663− if (!ready) return@collect
664− if (_draft.value.isEmpty()) {
665− _draft.value = container.draftStore.get(sessionId)
666− }
667− // Recover a follow-up queued before process death (its in-memory StateFlow
668− // is gone). If the input is now free, drop it back there for review/send and
669− // consume the stored copy; otherwise re-queue it so it auto-sends when the
670− // current run next idles. Guarded on == null so it never clobbers a
671− // follow-up the user queued after opening this session.
672− val savedFollowUp = container.draftStore.getFollowUp(sessionId)
673− if (savedFollowUp.isNotEmpty() && _queuedFollowUp.value == null) {
674− if (_draft.value.isEmpty()) {
675− _draft.value = savedFollowUp
676− container.draftStore.flushFollowUp(sessionId, "")
677− } else {
678− _queuedFollowUp.value = savedFollowUp
679− }
680− }
681− }
682− }
683− // Observe the drafts store for external mutations to this session's draft
684− // (e.g. a share injected via draftStore.set in two-pane mode, or setImmediate
685− // before navigation in single-pane mode). Without this, a share injected into
686− // an already-open session never appears in the input field — the init-time
687− // read and the ready-only re-seed miss it when the draft is non-empty.
688− // The VM's own debounced persist writes the same value _draft already holds,
689− // so those updates are no-ops here (storeValue == _draft.value). The
690− // suppressDraftPersist guard prevents a stale store value from clobbering
691− // the deliberate draft clear during a send (the store still holds the
692− // pre-send draft until the send resolves).
693− viewModelScope.launch {
694− container.draftStore.drafts.collect { drafts ->
695− // Ignore emissions until the initial disk load completes: the load itself
696− // emits the persisted snapshot, and applying it here would clobber text the
697− // user typed during the async load (the `ready` observer above seeds an
698− // empty draft). After ready, emissions are external writes.
699− if (!container.draftStore.ready.value) return@collect
700− val storeValue = drafts[sessionId].orEmpty()
701− // Ignore this VM's own (debounced, possibly stale) persistence echo — only a
702− // genuine external write (e.g. a two-pane share injection) should overwrite
703− // the live draft.
704− if (storeValue == lastPersistedDraft) return@collect
705− if (storeValue != _draft.value && !suppressDraftPersist.get()) {
706− _draft.value = storeValue
707− }
708− }
709− }
710− }
711−
712− init {
713− // Restore attachments staged before process death. They were persisted as
714− // self-contained data URLs, so they re-send and (for images) re-preview intact.
715− // Guarded on empty so it never clobbers attachments the user staged after opening.
716− viewModelScope.launch {
717− val restored = runCatchingCancellable { container.attachmentDraftStore.load(sessionId) }
718− .getOrDefault(emptyList())
719− if (restored.isNotEmpty() && _attachments.value.isEmpty()) {
720− _attachments.value = restored.map { it.toPending() }
721− }
722− }
723− }
724−
725− fun selectModel(option: ModelOption) { _selectedModel.value = option }
726−
727− fun selectAgent(name: String?) { _selectedAgent.value = name }
728−
729− fun reloadModels() {
730− val conn = connection ?: return
731− viewModelScope.launch {
732− conn.api.invalidateProvidersCache()
733− _modelsReload.value++
734− }
735− }
736−
737− fun reloadAgents() {
738− val conn = connection ?: return
739− viewModelScope.launch {
740− conn.api.invalidateAgentsCache()
741− _agentsReload.value++
742− }
743− }
744−
745− fun reloadCommands() {
746− val conn = connection ?: return
747− viewModelScope.launch {
748− conn.api.invalidateCommandsCache()
749− _commandsReload.value++
750− }
751− }
752−
753− /**
754− * Shared helper for init-block catalog observers: re-fetches whenever the active
755− * connection or the catalog's reload trigger changes, invoking [onNull] to clear
756− * state on null so stale data from the old server doesn't persist. The
757− * [reloadTrigger] is merged with [activeConnection] so a manual reload (via
758− * reloadModels/reloadAgents/reloadCommands) cancels any in-flight observe fetch
759− * via collectLatest, preventing a stale observe result from overwriting a fresh
760− * reload result. Failure is non-fatal — the error flag is surfaced to the UI.
761− */
762− private fun <T> observeCatalog(
763− tag: String,
764− loading: MutableStateFlow<Boolean>,
765− error: MutableStateFlow<Boolean>,
766− fetch: suspend (soy.iko.opencode.data.network.OpencodeApiClient) -> T,
767− onSuccess: suspend (T) -> Unit,
768− onNull: () -> Unit,
769− reloadTrigger: StateFlow<Int>,
770− ) {
771− viewModelScope.launch {
772− merge(container.activeConnection, reloadTrigger).collectLatest { _ ->
773− val conn = container.activeConnection.value
774− if (conn == null) { onNull(); loading.value = false; error.value = false; return@collectLatest }
775− loading.value = true
776− error.value = false
777− runCatchingCancellable { fetch(conn.api) }
778− // fetch() does HTTP via withRetry, so the failure can be a
779− // ClientRequestException whose message embeds the full request URL
780− // (may contain auth/paths). Log only a scrubbed summary.
781− .onFailure { Log.w("ChatViewModel", "Failed to load $tag: ${safeExceptionSummary(it)}"); error.value = true }
782− .getOrNull()?.let { onSuccess(it) }
783− loading.value = false
784− }
785− }
786− }
787−
788− fun updateDraft(text: String) {
789− _draft.value = text
790− }
791−
792− init {
793− // Debounce draft persistence so we don't write to disk on every keystroke.
794− // Skip persisting empty drafts that were set by send() (suppressed via
795− // suppressDraftPersist) — send() clears the in-memory draft immediately for
796− // UI feedback but deliberately doesn't persist the clear until the send
797− // succeeds, so a failed send can restore the draft.
798− viewModelScope.launch {
799− _draft.drop(1).debounce(NetworkConfig.draftDebounceMs).collect { text ->
800− if (text.isBlank() && suppressDraftPersist.get()) return@collect
801− lastPersistedDraft = text
802− runCatchingCancellable { container.draftStore.set(sessionId, text) }
803− .onFailure { Log.w("ChatViewModel", "Failed to persist draft", it) }
804− }
805− }
806− // Reset per-connection state when the active server changes so stale spinners,
807− // permission dialogs, errors, and agent selections from the old server don't
808− // persist into the new one.
809− viewModelScope.launch {
810− container.activeConnection.collectLatest { conn ->
811− if (conn == null) {
812− // The connection dropped (e.g. disconnect() mid-run). No SSE stream will
813− // arrive to deliver SessionIdle/SessionError, so reset the run state here —
814− // otherwise the working spinner sticks on, ChatScreen keeps keepScreenOn +
815− // the RunForegroundService alive, and the Stop button no-ops (abort() early-
816− // returns with no connection) until a later reconnect happens to clear it.
817− _running.value = false
818− _streamInterrupted.value = false
819− _aborting.value = false
820− clearPermissions()
821− sessionAllowed.clear()
822− sessionTitleJob?.cancel()
823− _revertDiff.value = null
824− return@collectLatest
825− }
826− _running.value = false
827− _streamInterrupted.value = false
828− // Allow the re-light below to recover a still-running run after this (re)connect;
829− // a run that actually finished during the outage emits no live parts, so this
830− // won't spuriously re-light.
831− runEndedByIdle = false
832− clearPermissions()
833− sessionAllowed.clear()
834− _failedDraft.value = null
835− _revertDiff.value = null
836− // NOTE: deliberately not clearing _queuedFollowUp here. It's session-scoped
837− // user intent that is now persisted; wiping it on every (re)connect — which
838− // this collector does, including transient SSE drops and the cold-start
839− // restore path — would drop a legitimately queued/recovered follow-up.
840− _selectedAgent.value = null
841− // Apply the user's persisted preferred-agent for this new session/load, so a
842− // user who always runs a specific agent doesn't have to pick it every session.
843− // No-op when the preference is empty (the server default applies). Read here
844− // (not in the agent-catalog onSuccess) because the catalog loads once per
845− // connection while this reset fires per-session-open; setting it once on
846− // connect is enough and avoids re-applying it on every catalog refresh.
847− runCatchingCancellable {
848− val pref = container.settingsStore.preferredAgentName.first()
849− if (pref.isNotEmpty()) _selectedAgent.value = pref
850− }
851− _sessionTitle.value = null
852− // Resolve the app-bar title via REST for THIS connection. Launched from the same
853− // block that just nulled _sessionTitle (and cancelled the previous fetch) so it can
854− // never observe or restore the previous server's stale title — the old separate
855− // collector could, racing that reset. The assignment is guarded on a still-null
856− // title so a fresher SSE SessionUpdated (from the event collector below) wins.
857− sessionTitleJob?.cancel()
858− sessionTitleJob = viewModelScope.launch {
859− runCatchingCancellable { conn.repository.listSessions() }
860− .getOrNull()
861− ?.firstOrNull { it.id == sessionId }
862− ?.let { session ->
863− if (_sessionTitle.value == null) {
864− _sessionTitle.value = session.displayTitle
865− _reverted.value = session.isReverted
866− _revertDiff.value = session.revert?.diff?.takeIf { it.isNotBlank() }
867− _shareUrl.value = session.share?.url?.takeIf { it.isNotBlank() }
868− }
869− }
870− }
871− try {
872− // Loop the inner collect so a transient non-cancellation exception (a
873− // malformed SSE event decoding error, an unexpected channel close)
874− // doesn't terminate the event collector for this connection. Without
875− // the loop, the catch returns the collectLatest lambda normally, so
876− // collectLatest considers this connection's block complete and never
877− // re-runs it — the chat would go permanently silent (no streaming,
878− // no permission prompts, no title updates) until a server switch.
879− while (currentCoroutineContext().isActive) {
880− try {
881− conn.events.events.collect { event ->
882− if (SessionRepository.isIdle(event, sessionId)) {
883− _running.value = false
884− runEndedByIdle = true
885− // Auto-send a queued follow-up once the previous run finishes,
886− // so the user's drafted-while-running message isn't lost.
887− // The follow-up is cleared *inside* send()'s launched
888− // coroutine (via queuedFollowUpToClear), so a scope
889− // cancellation between this point and the coroutine
890− // starting drops the launch without wiping the persisted
891− // follow-up — recovery on next session open instead of
892− // silent data loss.
893− val queued = _queuedFollowUp.value
894− if (queued != null) {
895− send(queued, includeAttachments = false, queuedFollowUpToClear = queued)
896− }
897− }
898− if (SessionRepository.isError(event, sessionId)) {
899− _running.value = false
900− runEndedByIdle = true
901− // The run errored, so the queued follow-up won't auto-send.
902− // Restore it to the input (if free) so the user's typed text
903− // isn't silently lost; otherwise just clear the queue.
904− val queued = _queuedFollowUp.value
905− if (!queued.isNullOrEmpty() && _draft.value.isEmpty()) {
906− _draft.value = queued
907− }
908− setQueuedFollowUp(null)
909− _errorEvents.trySend(ChatError(container.string(R.string.error_agent_reported)))
910− }
911− // Restore the run indicator if a live streaming event arrives while it's
912− // cleared — e.g. an SSE reconnect mid-run reset _running to false, but the
913− // agent is still working. Don't revive it once the user has hit Stop.
914− val relightRunIndicator = SessionRepository.isRunActivity(event, sessionId) &&
915− !_aborting.value && !_running.value && !runEndedByIdle
916− if (relightRunIndicator) {
917− _running.value = true
918− }
919− when (event) {
920− is PermissionUpdated ->
921− if (event.properties.sessionID == sessionId) enqueuePermission(event.properties)
922− is PermissionReplied ->
923− if (event.properties.sessionID == sessionId) event.properties.permissionID?.let { resolvePermission(it) }
924− is SessionUpdated ->
925− if (event.properties.info.id == sessionId) {
926− val info = event.properties.info
927− _sessionTitle.value = info.displayTitle
928− _reverted.value = info.isReverted
929− _revertDiff.value = info.revert?.diff?.takeIf { it.isNotBlank() }
930− _shareUrl.value = info.share?.url?.takeIf { it.isNotBlank() }
931− }
932− is SessionDeleted ->
933− if (event.properties.info?.id == sessionId || event.properties.sessionID == sessionId) {
934− _sessionDeleted.value = true
935− }
936− else -> {}
937− }
938− }
939− } catch (e: CancellationException) {
940− throw e
941− } catch (e: Exception) {
942− Log.w("ChatViewModel", "SSE event collector error, restarting", e)
943− }
944− }
945− } catch (e: CancellationException) {
946− throw e
947− } catch (e: Exception) {
948− Log.w("ChatViewModel", "SSE event collector loop error", e)
949− }
950− }
951− }
952− // Load the model catalog; preselect the server default. Failure is non-fatal —
953− // sending with no model just uses the server's default agent/model.
954− observeCatalog(
955− tag = "model catalog",
956− loading = _modelsLoading,
957− error = _modelsError,
958− fetch = { it.providers() },
959− onSuccess = { resp ->
960− val options = resp.toOptions()
961− _models.value = options
962− // Only (re)apply the default when there's no valid current selection. On
963− // re-fetch/reconnect/Retry the user's chosen model must survive — keep it as
964− // long as it's still present in the refreshed list. When there's no current
965− // selection, prefer the user's persisted default-model preference (if it's in
966− // the list) over the server default, so a user who always picks a specific
967− // model doesn't have to pick it every new session.
968− val current = _selectedModel.value
969− if (current == null || options.none { it.ref == current.ref }) {
970− val prefId = runCatchingCancellable {
971− container.settingsStore.preferredModelId.first()
972− }.getOrDefault("")
973− val preferredOption = if (prefId.isNotEmpty()) {
974− options.firstOrNull { it.modelID == prefId }
975− } else null
976− _selectedModel.value = preferredOption ?: resp.defaultOption(options)
977− }
978− },
979− onNull = { _models.value = emptyList(); _selectedModel.value = null },
980− reloadTrigger = _modelsReload,
981− )
982− // Load the agent catalog (non-fatal).
983− observeCatalog(
984− tag = "agent catalog",
985− loading = _agentsLoading,
986− error = _agentsError,
987− fetch = { it.agents() },
988− onSuccess = { _agents.value = it },
989− onNull = { _agents.value = emptyList() },
990− reloadTrigger = _agentsReload,
991− )
992− // Load the command catalog (non-fatal).
993− observeCatalog(
994− tag = "command catalog",
995− loading = _commandsLoading,
996− error = _commandsError,
997− fetch = { it.commands() },
998− onSuccess = { _commands.value = it },
999− onNull = { _commands.value = emptyList() },
1000− reloadTrigger = _commandsReload,
1001− )
1002− // If the SSE stream drops mid-run, the run indicator would spin forever;
1003− // reset it so the UI doesn't look stuck while the banner shows "Reconnecting…".
1004− // On a *transient* drop (Disconnected) we don't clear _running — the run is still
1005− // active on the server, and showing it as finished would mislead the user. Instead
1006− // we set _streamInterrupted so the working row switches to a "reconnecting" visual.
1007− // On a *hard* failure (Failed/AuthFailed) the run genuinely can't continue without
1008− // user action, so _running is cleared. _streamInterrupted is cleared on Connected.
1009− viewModelScope.launch {
1010− container.activeConnection.collectLatest { conn ->
1011− if (conn == null) return@collectLatest
1012− try {
1013− // Loop so a transient non-cancellation exception doesn't terminate the
1014− // state watcher for this connection. Without the loop, a single thrown
1015− // error returns the collectLatest lambda and the _running reset on
1016− // Disconnected/Failed never fires again for this connection — a dropped
1017− // stream leaves the working spinner (and the RunForegroundService) stuck.
1018− while (currentCoroutineContext().isActive) {
1019− try {
1020− conn.events.state.collect { state ->
1021− when (state) {
1022− EventStreamClient.ConnectionState.Connected -> {
1023− _streamInterrupted.value = false
1024− }
1025− EventStreamClient.ConnectionState.Disconnected -> {
1026− // Transient: the stream dropped but the system is
1027− // reconnecting. Flag interrupted so the working row
1028− // shows a "reconnecting" state instead of vanishing.
1029− if (_running.value) _streamInterrupted.value = true
1030− }
1031− EventStreamClient.ConnectionState.Failed,
1032− EventStreamClient.ConnectionState.AuthFailed -> {
1033− // Hard failure: the run can't continue without user
1034− // action (fix credentials / server). Clear running and
1035− // the interrupted flag so the UI doesn't look stuck.
1036− _streamInterrupted.value = false
1037− if (_running.value) _running.value = false
1038− }
1039− EventStreamClient.ConnectionState.Connecting -> {
1040− // Initial connect or reconnect attempt; leave running
1041− // as-is — interrupted (if set) stays until Connected.
1042− }
1043− }
1044− }
1045− } catch (e: CancellationException) {
1046− throw e
1047− } catch (e: Exception) {
1048− Log.w("ChatViewModel", "SSE state collector error, restarting", e)
1049− }
1050− }
1051− } catch (e: CancellationException) {
1052− throw e
1053− } catch (e: Exception) {
1054− Log.w("ChatViewModel", "SSE state collector loop error", e)
1055− }
1056− }
1057− }
1058− }
1059−
1060− /** Sends [text] together with any staged attachments; returns true on success so the
1061− * caller can clear the draft only then. */
1062− fun send(text: String): Boolean = send(text, includeAttachments = true)
1063−
1064− /**
1065− * Core send. [includeAttachments] is false for the internal auto-send paths (a queued
1066− * follow-up, a retry) so staged attachments aren't silently re-sent with unrelated text.
1067− *
1068− * [queuedFollowUpToClear] is the text of a queued follow-up being auto-sent (from
1069− * SessionIdle). When non-null, the follow-up is cleared from persistence *inside* the
1070− * launched coroutine — so if [viewModelScope] is cancelled before the coroutine runs
1071− * (e.g. the user navigates away at the exact moment SessionIdle arrives), the clear
1072− * never executes and the follow-up remains persisted, recovered on the next open of
1073− * this session. Clearing it before the launch (the prior approach) could lose the
1074− * follow-up entirely: the launch would be dropped by cancellation but the persisted
1075− * copy was already wiped.
1076− */
1077− @Suppress("CyclomaticComplexMethod")
1078− private fun send(
1079− text: String,
1080− includeAttachments: Boolean,
1081− idempotencyKey: String? = null,
1082− queuedFollowUpToClear: String? = null,
1083− ): Boolean {
1084− val trimmed = text.trim()
1085− val attachments = if (includeAttachments) _attachments.value else emptyList()
1086− // An image-only prompt (attachments, no text) is valid; a blank prompt with nothing
1087− // attached is not.
1088− if (trimmed.isEmpty() && attachments.isEmpty()) return false
1089− // Offline, or no active connection: queue the prompt to the outbox (flushed on
1090− // reconnect) instead of failing the send. Device-offline is caught even when a stale
1091− // connection object lingers, so a phone that lost signal mid-conversation still
1092− // captures the message rather than bouncing it off a dead socket.
1093− val conn = connection
1094− if (conn == null || !container.isOnline.value) {
1095− return enqueueOffline(trimmed, attachments)
1096− }
1097− if (!beginRun()) return false
1098− // A new run is starting: reopen the re-light gate so this run's streamed parts keep the
1099− // indicator lit (and a later SessionIdle re-closes it).
1100− runEndedByIdle = false
1101− // A plain manual Send of the auto-restored failed draft must reuse the stashed key too
1102− // (retryFailed passes it explicitly; the composer's Send does not), so a lost-response
1103− // re-send stays deduplicated server-side instead of starting a duplicate agent run.
1104− // Capture the match BEFORE clearing _failedDraft just below.
1105− val reuseKey = if (idempotencyKey == null && trimmed == _failedDraft.value?.trim()) {
1106− failedIdempotencyKey
1107− } else {
1108− null
1109− }
1110− _failedDraft.value = null
1111− // Stable idempotency key for THIS online attempt: a brand-new message gets a fresh key,
1112− // while retryFailed() (or a manual re-send of the restored failed draft) re-submits with the
1113− // key it stashed on the original failure — so a retry after a lost response is deduplicated
1114− // server-side (no duplicate agent run).
1115− val key = idempotencyKey ?: reuseKey ?: java.util.UUID.randomUUID().toString()
1116− // Clear the staged attachments optimistically so the composer empties immediately;
1117− // restore them if the send fails (mirrors the draft handling below).
1118− if (attachments.isNotEmpty()) _attachments.value = emptyList()
1119− // Clear the in-memory draft for the UI immediately, but don't persist the clear
1120− // yet — if the send fails and the process dies before we restore, the draft
1121− // would be lost forever. The persisted draft is cleared only on success.
1122− // suppressDraftPersist prevents the debounced collector from persisting the
1123− // empty draft before the send resolves.
1124− //
1125− // Only clear when the text being sent IS the current draft. send() is also
1126− // invoked for auto-sent queued follow-ups (SessionIdle) and retryFailed(), where
1127− // the user may have typed a NEW draft since — wiping it would lose that text.
1128− if (_draft.value.trim() == trimmed) {
1129− suppressDraftPersist.set(true)
1130− _draft.value = ""
1131− _pendingQuote.value = null
1132− _editing.value = false
1133− }
1134− // Inject an optimistic user message so the outgoing prompt is visible immediately,
1135− // before the server echoes it back via SSE. Removed by reconcileOptimistic once the
1136− // real UserMessage arrives. Only for text-bearing prompts (an image-only prompt has
1137− // no text to show).
1138− val optimisticId = if (trimmed.isNotEmpty()) "__optimistic_${System.nanoTime()}" else null
1139− if (optimisticId != null) {
1140− // Clear any prior failed optimistic entry with the same text (a retry re-sends).
1141− _optimisticMessages.update { entries -> entries.filterNot { it.failed && it.text.trim() == trimmed } }
1142− _optimisticMessages.update { it + OptimisticEntry(optimisticId, trimmed, System.currentTimeMillis(), failed = false) }
1143− }
1144− // Remember the sent text so an undoable Stop can re-send it. Overwrite unconditionally:
1145− // an image-only prompt has nothing to re-send, and leaving a prior text prompt tracked
1146− // would make Stop-Undo silently re-send that unrelated earlier message.
1147− lastSentPrompt = trimmed.takeIf { it.isNotEmpty() }
1148− viewModelScope.launch {
1149− // Clear a queued follow-up being auto-sent *inside* the launched coroutine, so a
1150− // scope cancellation between send() being called and the coroutine starting drops
1151− // the launch without wiping the persisted follow-up — the follow-up is then
1152− // recovered on the next session open instead of being silently lost.
1153− if (queuedFollowUpToClear != null) setQueuedFollowUp(null)
1154− runCatchingCancellable {
1155− conn.repository.sendPrompt(
1156− sessionId,
1157− trimmed,
1158− attachments = attachments.map { it.part },
1159− model = _selectedModel.value?.ref,
1160− agent = _selectedAgent.value,
1161− idempotencyKey = key,
1162− )
1163− }.onFailure {
1164− // Mark the optimistic message as failed so the user sees a failure indicator
1165− // instead of a perpetual "sending" state.
1166− if (optimisticId != null) {
1167− _optimisticMessages.update { entries ->
1168− entries.map { if (it.tempId == optimisticId) it.copy(failed = true) else it }
1169− }
1170− }
1171− suppressDraftPersist.set(false)
1172− _failedDraft.value = trimmed
1173− failedIdempotencyKey = key
1174− // Only restore the draft if the user hasn't typed anything new since.
1175− if (_draft.value.isBlank()) updateDraft(trimmed)
1176− // Restore the staged attachments too, so a failed send doesn't lose them —
1177− // but only if the user hasn't staged new ones in the meantime.
1178− if (attachments.isNotEmpty() && _attachments.value.isEmpty()) _attachments.value = attachments
1179− // Re-persist so the restored attachments survive process death after a failure.
1180− persistAttachments()
1181− // Retryable: this is the failed send whose prompt Retry re-submits.
1182− _errorEvents.trySend(ChatError(container.friendlyError(it), retryable = true))
1183− _running.value = false
1184− }.onSuccess {
1185− suppressDraftPersist.set(false)
1186− // This attempt reached the server, so the stashed retry key is spent — drop it so a
1187− // later unrelated send can't reuse it (retryFailed clears it on success too).
1188− failedIdempotencyKey = null
1189− // Send succeeded — the attachments rode along, so clear their persisted copy
1190− // (or keep any the user staged after the optimistic clear).
1191− persistAttachments()
1192− // Send succeeded — persist the cleared draft, but only if the user hasn't
1193− // typed a new one while the send was in flight. Otherwise clearing the
1194− // store echoes back through the draft observer and wipes the in-progress
1195− // text (data loss). Mirrors the guard on the failure path above.
1196− if (_draft.value.isBlank()) {
1197− lastPersistedDraft = ""
1198− container.draftStore.set(sessionId, "")
1199− }
1200− // Don't reset _running here: the agent continues streaming via SSE.
1201− // _running is cleared on SessionIdle/SessionError (see event collector)
1202− // or when the SSE stream drops (see connection state watcher below).
1203− }
1204− }
1205− return true
1206− }
1207−
1208− /**
1209− * Queue [trimmed] (+ [attachments]) to the offline outbox, clearing the composer
1210− * optimistically like a real send. AppContainer flushes the outbox automatically on
1211− * reconnect. The prompt is attributed to the active (or most-recent) server profile so a
1212− * reconnect to a different server doesn't misfire it. On any failure the draft/attachments
1213− * are restored so nothing is lost.
1214− */
1215− private fun enqueueOffline(trimmed: String, attachments: List<PendingAttachment>): Boolean {
1216− _failedDraft.value = null
1217− if (attachments.isNotEmpty()) _attachments.value = emptyList()
1218− val clearDraft = _draft.value.trim() == trimmed
1219− if (clearDraft) {
1220− suppressDraftPersist.set(true)
1221− _draft.value = ""
1222− }
1223− viewModelScope.launch {
1224− val profileId = connection?.profile?.id
1225− ?: runCatchingCancellable { container.profileStore.profiles.first().firstOrNull()?.id }.getOrNull()
1226− if (profileId == null) {
1227− // No server to attribute the message to — restore the composer and report it
1228− // rather than silently dropping the prompt.
1229− suppressDraftPersist.set(false)
1230− if (_draft.value.isBlank()) updateDraft(trimmed)
1231− if (attachments.isNotEmpty() && _attachments.value.isEmpty()) _attachments.value = attachments
1232− persistAttachments()
1233− _errorEvents.trySend(ChatError(container.string(R.string.no_servers_to_reconnect)))
1234− return@launch
1235− }
1236− runCatchingCancellable {
1237− container.outboxStore.enqueue(
1238− OutboxMessage(
1239− id = java.util.UUID.randomUUID().toString(),
1240− profileId = profileId,
1241− sessionId = sessionId,
1242− text = trimmed,
1243− attachments = attachments.map { it.toPersisted() },
1244− model = _selectedModel.value?.ref,
1245− agent = _selectedAgent.value,
1246− createdAt = System.currentTimeMillis(),
1247− ),
1248− )
1249− }.onSuccess {
1250− suppressDraftPersist.set(false)
1251− // The staged attachments now live in the outbox item; clear their draft copy.
1252− persistAttachments()
1253− if (_draft.value.isBlank()) {
1254− lastPersistedDraft = ""
1255− container.draftStore.set(sessionId, "")
1256− }
1257− // Nudge a flush in case we're actually online with a live connection.
1258− container.flushOutbox()
1259− _errorEvents.trySend(ChatError(container.string(R.string.outbox_queued)))
1260− }.onFailure {
1261− suppressDraftPersist.set(false)
1262− if (_draft.value.isBlank()) updateDraft(trimmed)
1263− if (attachments.isNotEmpty() && _attachments.value.isEmpty()) _attachments.value = attachments
1264− persistAttachments()
1265− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1266− }
1267− }
1268− return true
1269− }
1270−
1271− /** Discard a single queued (offline) message. */
1272− fun discardQueued(id: String) {
1273− viewModelScope.launch { runCatchingCancellable { container.outboxStore.remove(id) } }
1274− }
1275−
1276− /** Discard every queued (offline) message for this session. */
1277− fun discardAllQueued() {
1278− viewModelScope.launch { runCatchingCancellable { container.outboxStore.removeForSession(sessionId) } }
1279− }
1280−
1281− /** Attempt to flush the outbox now (e.g. the user tapped "Send now"). */
1282− fun flushQueued() { container.flushOutbox() }
1283−
1284− /** Re-send the last draft whose send failed, if any. */
1285− fun retryFailed() {
1286− val draft = _failedDraft.value ?: return
1287− // Reuse the failed send's idempotency key so a retry after a lost response is
1288− // deduplicated server-side rather than starting a duplicate run.
1289− val key = failedIdempotencyKey
1290− // Don't clear _failedDraft until send() accepts the text — if _running is
1291− // already true, send() returns false and the draft would be lost forever.
1292− // Attachments aren't re-sent on retry (they were optimistically restored to the
1293− // composer on the original failure, so they'll ride the next manual send).
1294− // send() accepts the text synchronously, but its onSuccess/onFailure callbacks run
1295− // asynchronously. Clearing failedIdempotencyKey here would open a window between this
1296− // synchronous clear and the async onFailure (which re-stashes the key) during which a
1297− // manual re-send of the same text gets a fresh UUID — defeating server-side deduplication.
1298− // Let send()'s own callbacks own the key's lifecycle, as they do for non-retry paths.
1299− if (send(draft, includeAttachments = false, idempotencyKey = key)) {
1300− _failedDraft.value = null
1301− }
1302− }
1303−
1304− /** Dismiss a single failed optimistic message by its tempId so it no longer lingers in the
1305− * list. Without this there's no recovery path for a failed message the user chose to abandon
1306− * (its text won't ever match a real server message, so reconcileOptimistic never clears it). */
1307− fun dismissOptimistic(tempId: String) {
1308− _optimisticMessages.update { entries -> entries.filterNot { it.tempId == tempId } }
1309− }
1310−
1311− /** Re-send a specific failed optimistic message by its tempId. Loads its text into the
1312− * composer and fires a send, mirroring the snackbar's Retry path. Returns false (and is a
1313− * no-op) if the entry can't be found or a run is already active. */
1314− fun retryOptimisticMessage(tempId: String): Boolean {
1315− val entry = _optimisticMessages.value.firstOrNull { it.tempId == tempId && it.failed } ?: return false
1316− return send(entry.text, includeAttachments = false)
1317− }
1318−
1319− /**
1320− * Queue [text] to be sent automatically when the current run finishes, or clear any
1321− * queued follow-up when [text] is blank. Used when the user taps Send while a run
1322− * is already active — the Send button is replaced by Stop during a run, but the
1323− * input field stays enabled, so a follow-up typed mid-run would otherwise have
1324− * nowhere to go.
1325− */
1326− fun queueFollowUp(text: String) {
1327− val trimmed = text.trim()
1328− setQueuedFollowUp(trimmed.takeIf { it.isNotEmpty() })
1329− // The text now lives in the queued chip, so clear the input field just as a
1330− // normal send would. No-op for the cancel case (blank text), which must leave
1331− // whatever the user has since typed untouched.
1332− if (trimmed.isNotEmpty()) {
1333− _draft.value = ""
1334− // Persist the cleared draft IMMEDIATELY, not just in memory: the follow-up was already
1335− // persisted synchronously above, so if the process is killed before the debounced
1336− // draft-persist fires, the same text would remain under BOTH the draft and follow-up
1337− // keys — and cold-start recovery would restore it to the composer AND re-queue it (a
1338− // duplicate). Mirror send()'s lastPersistedDraft update so the drafts observer treats
1339− // this store change as our own echo and doesn't write the cleared value back.
1340− lastPersistedDraft = ""
1341− container.draftStore.flushDraft(sessionId, "")
1342− }
1343− }
1344−
1345− /** Set or clear the queued follow-up and mirror it to persistence, so a follow-up
1346− * queued mid-run survives process death (recovered on the next open of this session).
1347− * Passing null / blank clears both the in-memory value and the persisted copy. */
1348− private fun setQueuedFollowUp(text: String?) {
1349− _queuedFollowUp.value = text
1350− container.draftStore.flushFollowUp(sessionId, text.orEmpty())
1351− }
1352−
1353− /** Transient flag set by [refreshMessages] so the top-bar refresh icon can show
1354− * a brief spinner as immediate tap feedback. The SSE reconnect triggered by
1355− * refreshMessages may not visibly change [connectionState] (it's already
1356− * Connected), so without this the tap appears to do nothing. Clears after a
1357− * short delay or when the connection state next becomes Connected. */
1358− private val _refreshing = MutableStateFlow(false)
1359− val refreshing: StateFlow<Boolean> = _refreshing.asStateFlow()
1360−
1361− /** Manually re-fetch messages by forcing the SSE stream to reconnect, which
1362− * triggers the repository's re-seed-from-REST logic. Gives the user a recovery
1363− * path when the SSE stream silently drops and the auto-reconnect re-seed is slow
1364− * or fails — a pull-to-refresh or top-bar refresh forces a fresh fetch under the
1365− * existing generation-guarded merge. Also clears [loadError] optimistically and
1366− * sets [refreshing] for immediate tap feedback. */
1367− fun refreshMessages() {
1368− val conn = connection ?: return
1369− _loadError.value = false
1370− _loadErrorInline.value = false
1371− _refreshing.value = true
1372− conn.events.triggerReconnect()
1373− viewModelScope.launch {
1374− delay(NetworkConfig.refreshFeedbackMs)
1375− _refreshing.value = false
1376− }
1377− }
1378−
1379− /** Invoke a slash-command by name via the server's /command endpoint. */
1380− fun runCommand(command: Command) {
1381− val conn = connection ?: return
1382− // A run is already in flight — surface feedback instead of silently dropping the
1383− // command (the picker stays openable during a run and dismisses on select).
1384− if (!beginRun()) {
1385− _errorEvents.trySend(ChatError(container.string(R.string.command_busy)))
1386− return
1387− }
1388− // A new run is starting: reopen the re-light gate (as send() does) so a mid-run SSE
1389− // reconnect keeps the working indicator lit instead of leaving it stuck off.
1390− runEndedByIdle = false
1391− viewModelScope.launch {
1392− runCatchingCancellable {
1393− conn.repository.runCommand(sessionId, command.name, agent = command.agent)
1394− }.onFailure {
1395− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1396− _running.value = false
1397− }
1398− }
1399− }
1400−
1401− fun abort() {
1402− val conn = connection ?: return
1403− // Drop any queued follow-up so the SessionIdle that follows the abort doesn't
1404− // auto-send it — the user tapped Stop to halt work, not to trigger the next turn.
1405− setQueuedFollowUp(null)
1406− if (!_aborting.compareAndSet(false, true)) return
1407− viewModelScope.launch {
1408− try {
1409− // Run the abort POST under NonCancellable so it survives this scope being
1410− // cancelled. The "Stop and exit" path calls abort() then navigates back
1411− // immediately, which pops this ViewModel's back-stack entry → onCleared() →
1412− // viewModelScope.cancel(); without this the in-flight abort is cancelled (often
1413− // before the request even reaches the server) and the run keeps burning tokens
1414− // server-side despite the user explicitly stopping it.
1415− runCatchingCancellable { withContext(NonCancellable) { conn.repository.abort(sessionId) } }
1416− .onSuccess {
1417− _running.value = false
1418− // Close the re-light gate so trailing SSE events in flight between the
1419− // abort POST's ack and the server's SessionIdle don't re-light the run
1420− // indicator (and re-arm the FGS / keepScreenOn) after the user hit Stop.
1421− // send()/runCommand()/continueRun() all open this gate on beginRun();
1422− // abort() is the one run-ending path that previously missed it.
1423− runEndedByIdle = true
1424− // Surface an undo opportunity so an accidental Stop is recoverable.
1425− // The UI shows a "Stopped — Undo" snackbar; tapping Undo re-sends the
1426− // last prompt. Only when there's a tracked prompt to undo back to.
1427− val prompt = lastSentPrompt
1428− if (prompt != null) _stopUndoEvents.trySend(prompt)
1429− }
1430− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1431− } finally {
1432− _aborting.value = false
1433− }
1434− }
1435− }
1436−
1437− /** Re-send the most recently-sent user prompt, used by the Stop-undo snackbar so an
1438− * accidental Stop can be recovered. No-op if no prompt is tracked (e.g. the run was
1439− * started by a command, not a text prompt). Clears the tracked prompt so a second Undo
1440− * tap doesn't double-send. */
1441− fun resendLastPrompt() {
1442− val prompt = lastSentPrompt ?: return
1443− lastSentPrompt = null
1444− send(prompt, includeAttachments = false)
1445− }
1446−
1447− fun addAttachment(attachment: PendingAttachment) {
1448− // Enforce the cumulative size cap across the whole staged set (the per-file size and the
1449− // count caps are checked upstream). The base64 data URLs are held in memory and
1450− // re-serialized on every add/remove and again when the request body is built, so an
1451− // unbounded set OOMs. Reject rather than add, mirroring the other attachment limits'
1452− // snackbar via errorEvents. Size is the raw (pre-base64) byte count, matching the
1453− // per-file check, and includes attachments already staged (incl. restored ones).
1454− val staged = _attachments.value.sumOf { base64DataUrlByteSize(it.part.url) }
1455− if (staged + base64DataUrlByteSize(attachment.part.url) > NetworkConfig.maxTotalAttachmentBytes) {
1456− _errorEvents.trySend(ChatError(container.string(R.string.attachment_limit)))
1457− return
1458− }
1459− _attachments.update { it + attachment }
1460− persistAttachments()
1461− }
1462−
1463− fun removeAttachment(id: String) {
1464− _attachments.update { list -> list.filterNot { it.id == id } }
1465− persistAttachments()
1466− }
1467−
1468− fun clearAttachments() {
1469− _attachments.value = emptyList()
1470− persistAttachments()
1471− }
1472−
1473− /** Convert each picked Uri to a base64 attachment off the main thread, honoring the
1474− * per-prompt count cap and surfacing per-file errors via [errorEvents] without aborting
1475− * the batch. Runs on [viewModelScope] (which survives configuration changes) so an
1476− * in-flight encode isn't cancelled and its progress counters ([stagingCount] /
1477− * [stagingFileTotal]) aren't reset to 0 on rotation — the prior UI-side
1478− * `rememberCoroutineScope` implementation lost both the work and the counters on
1479− * every config change. */
1480− fun stageUris(uris: List<android.net.Uri>, context: android.content.Context) {
1481− if (uris.isEmpty()) return
1482− val appContext = context.applicationContext
1483− viewModelScope.launch {
1484− _stagingCount.value++
1485− _stagingFileTotal.value += uris.size
1486− try {
1487− uris.forEachIndexed { index, uri ->
1488− if (_attachments.value.size >= NetworkConfig.maxAttachments) {
1489− _errorEvents.trySend(ChatError(container.string(R.string.attachment_limit)))
1490− // The cap dropped the rest of this batch; account for the files we
1491− // won't process so stagingFileTotal doesn't linger over-counted,
1492− // then abandon the batch. return@launch (not return@forEachIndexed)
1493− // so the remaining uris aren't re-checked against a never-relieved
1494− // cap (which would over-decrement the counter and re-fire the
1495− // snackbar once per leftover uri). The `finally` below still
1496− // decrements stagingCount.
1497− _stagingFileTotal.value -= uris.size - index
1498− return@launch
1499− }
1500− when (val result = uri.toAttachmentResult(appContext)) {
1501− is AttachmentResult.Ok -> addAttachment(result.attachment)
1502− AttachmentResult.TooLarge -> _errorEvents.trySend(ChatError(container.string(R.string.attachment_too_large)))
1503− AttachmentResult.Failed -> _errorEvents.trySend(ChatError(container.string(R.string.attachment_failed)))
1504− }
1505− _stagingFileTotal.value--
1506− }
1507− } finally {
1508− _stagingCount.value--
1509− }
1510− }
1511− }
1512−
1513− /** Persist the current staged attachments so an interrupted compose survives process
1514− * death (mirrors draft persistence). Fire-and-forget on [viewModelScope]. */
1515− private fun persistAttachments() {
1516− val snapshot = _attachments.value
1517− viewModelScope.launch {
1518− runCatchingCancellable { container.attachmentDraftStore.save(sessionId, snapshot.map { it.toPersisted() }) }
1519− .onFailure { Log.w("ChatViewModel", "Failed to persist attachments", it) }
1520− }
1521− }
1522−
1523− /** Revert the conversation to just before [messageId], hiding everything after it. The
1524− * authoritative state also arrives via SessionUpdated; we flag it here for immediate
1525− * feedback. */
1526− fun revertTo(messageId: String) {
1527− val conn = connection ?: return
1528− viewModelScope.launch {
1529− runCatchingCancellable { conn.api.revert(sessionId, messageId) }
1530− .onSuccess {
1531− _reverted.value = it.isReverted
1532− _revertDiff.value = it.revert?.diff?.takeIf { diff -> diff.isNotBlank() }
1533− _editing.value = false
1534− }
1535− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1536− }
1537− }
1538−
1539− /**
1540− * Regenerate an assistant reply: revert the conversation to that assistant message (removing
1541− * it and everything after), then re-send the user prompt that immediately preceded it. A
1542− * one-tap "try again" mirroring ChatGPT/Claude, instead of the two-step revert + re-Send.
1543− *
1544− * Captures the preceding user text *before* the revert (the messages list updates
1545− * asynchronously via SSE once the revert lands). No-op if there's no preceding user prompt
1546− * or the assistant message isn't found.
1547− */
1548− fun regenerate(assistantMessageId: String) {
1549− val conn = connection ?: return
1550− val msgs = messages.value
1551− val idx = msgs.indexOfFirst { it.info.id == assistantMessageId }
1552− if (idx < 0) return
1553− val precedingUserText = (idx - 1 downTo 0)
1554− .asSequence()
1555− .map { msgs[it] }
1556− .firstOrNull { it.info is UserMessage }
1557− ?.parts
1558− ?.filterIsInstance<TextPart>()
1559− ?.joinToString("\n\n") { it.text }
1560− ?.takeIf { it.isNotBlank() }
1561− ?: return
1562− viewModelScope.launch {
1563− runCatchingCancellable { conn.api.revert(sessionId, assistantMessageId) }
1564− .onSuccess { send(precedingUserText, includeAttachments = false) }
1565− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1566− }
1567− }
1568−
1569− /** Continue a partially-generated assistant reply by sending a "continue" prompt
1570− * without reverting (unlike [regenerate], which re-runs from the preceding user
1571− * prompt and loses the partial). The partial reply stays as context so the model
1572− * can pick up where it left off. This is the standard chat-app "continue" pattern
1573− * for a reply that was aborted mid-stream. */
1574− fun continueRun(@Suppress("UNUSED_PARAMETER") assistantMessageId: String) {
1575− val conn = connection ?: return
1576− if (running.value || aborting.value) return
1577− if (!beginRun()) return
1578− // Reopen the relight gate so this run's streamed parts keep the indicator lit (and a
1579− // later SessionIdle re-closes it). Without this, runEndedByIdle stays true from the
1580− // previous run's SessionIdle and the relight guard at the event collector would suppress
1581− // every streamed part of the continuation, leaving the working indicator / Stop button /
1582− // foreground service off for the whole run.
1583− runEndedByIdle = false
1584− viewModelScope.launch {
1585− runCatchingCancellable {
1586− conn.api.sendPrompt(sessionId, text = "continue")
1587− }.onFailure {
1588− _running.value = false
1589− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1590− }
1591− }
1592− }
1593−
1594− /** Load a previously-sent user prompt back into the composer to edit and re-send.
1595− * Reverts the conversation to just before [messageId] (hiding it and everything after)
1596− * and prefills the draft with [text]. The next Send continues from that checkpoint,
1597− * effectively replacing the edited message; the reverted banner's Undo restores it.
1598− * Overwrites the current draft — this is an explicit edit action on that message. */
1599− fun editMessage(messageId: String, text: String) {
1600− val conn = connection ?: return
1601− _draft.value = text.take(NetworkConfig.maxDraftLengthChars)
1602− _pendingQuote.value = null
1603− // Do NOT delegate to revertTo(): revertTo's onSuccess sets _editing = false, which races
1604− // this synchronous _editing = true (the async revert completes after editMessage returns
1605− // and clobbers the banner). Inline the revert so editMessage owns the _editing lifecycle:
1606− // set it true on success, matching the documented contract ("Cleared on unrevert and on
1607− // send"). revertTo() (the manual revert button) still clears _editing itself.
1608− viewModelScope.launch {
1609− runCatchingCancellable { conn.api.revert(sessionId, messageId) }
1610− .onSuccess {
1611− _reverted.value = it.isReverted
1612− _revertDiff.value = it.revert?.diff?.takeIf { diff -> diff.isNotBlank() }
1613− _editing.value = true
1614− }
1615− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1616− }
1617− }
1618−
1619− /** Prefill the composer with [text] as a Markdown blockquote so the user can respond to a
1620− * specific message inline. Appends to any existing draft (with a blank line) rather than
1621− * overwriting, so quoting doesn't discard text already being typed. Also stashes the raw
1622− * quoted text in [pendingQuote] so the composer can show a dismissible preview card. */
1623− fun quoteReply(text: String) {
1624− val quoted = text.trim().lineSequence().joinToString("\n") { "> $it" }
1625− if (quoted.isBlank()) return
1626− val current = _draft.value
1627− val combined = if (current.isBlank()) "$quoted\n\n" else "$current\n\n$quoted\n\n"
1628− // Cap like the composer's typed/pasted/dictated input so quoting onto a near-full draft
1629− // can't push it past the limit (negative remaining counter + an over-cap prompt sent).
1630− _draft.value = combined.take(NetworkConfig.maxDraftLengthChars)
1631− _pendingQuote.value = text.trim().takeIf { it.isNotBlank() }
1632− }
1633−
1634− /** Remove the pending quote-reply preview and strip the `>`-prefixed blockquote lines from
1635− * the draft so canceling the quote card actually removes the quoted text, not just the chip.
1636− * Strips by leading `> ` prefix (structural match) rather than by exact full-text replace,
1637− * so a user who edited any quoted line is still cleaned up — the exact-text replaces would
1638− * silently no-op on an edit, leaving orphan `>` lines in the draft after the chip vanished. */
1639− fun cancelQuoteReply() {
1640− val removed = _pendingQuote.value ?: return
1641− _pendingQuote.value = null
1642− val quoteLineCount = removed.trim().lineSequence().count()
1643− // Walk the draft and drop the first contiguous run of `> `-prefixed lines that matches
1644− // the stashed quote's line count (the block quoteReply inserted). Lines the user edited
1645− // still begin with `> ` (quoteReply prefixed every line), so a prefix match finds them
1646− // even when their trailing content diverges from the stashed original.
1647− val lines = _draft.value.split("\n").toMutableList()
1648− var runStart = -1
1649− var runLen = 0
1650− var i = 0
1651− while (i < lines.size) {
1652− if (lines[i].startsWith("> ") || lines[i] == ">") {
1653− if (runStart < 0) runStart = i
1654− runLen++
1655− if (runLen == quoteLineCount) {
1656− // Strip the run plus a single trailing blank line that separated the quote
1657− // from the reply (quoteReply appends "\n\n" after the block).
1658− val stripUntil = i + 1
1659− if (stripUntil < lines.size && lines[stripUntil].isEmpty()) {
1660− lines.subList(runStart, stripUntil + 1).clear()
1661− } else {
1662− lines.subList(runStart, stripUntil).clear()
1663− }
1664− break
1665− }
1666− i++
1667− } else {
1668− runStart = -1
1669− runLen = 0
1670− i++
1671− }
1672− }
1673− _draft.value = lines.joinToString("\n").trimStart()
1674− }
1675−
1676− /** Fork the conversation by creating a brand-new session seeded with [text] as its first
1677− * prompt (using the currently-selected model/agent). Emits the new session id via
1678− * [branchEvents] so the UI can navigate to it. There's no server-side "branch" endpoint,
1679− * so this starts a fresh session from the chosen prompt rather than copying history. */
1680− fun branchFrom(text: String) {
1681− val conn = connection ?: return
1682− val prompt = text.trim()
1683− if (prompt.isEmpty()) return
1684− viewModelScope.launch {
1685− var createdId: String? = null
1686− runCatchingCancellable {
1687− val session = conn.repository.createSession(title = null)
1688− createdId = session.id
1689− conn.repository.sendPrompt(
1690− session.id,
1691− prompt,
1692− model = _selectedModel.value?.ref,
1693− agent = _selectedAgent.value,
1694− )
1695− session.id
1696− }
1697− .onSuccess { newId -> _branchEvents.trySend(newId) }
1698− .onFailure {
1699− // If the session was created but the prompt failed, delete the orphaned
1700− // empty session so failed branches don't accumulate on the server.
1701− val id = createdId
1702− if (id != null) {
1703− runCatchingCancellable { conn.repository.deleteSession(id) }
1704− }
1705− _errorEvents.trySend(ChatError(container.string(R.string.branch_failed)))
1706− }
1707− }
1708− }
1709−
1710− /** Undo the active revert checkpoint, restoring the hidden messages. */
1711− fun unrevert() {
1712− val conn = connection ?: return
1713− viewModelScope.launch {
1714− runCatchingCancellable { conn.api.unrevert(sessionId) }
1715− .onSuccess {
1716− _reverted.value = it.isReverted
1717− _revertDiff.value = it.revert?.diff?.takeIf { diff -> diff.isNotBlank() }
1718− _editing.value = false
1719− }
1720− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1721− }
1722− }
1723−
1724− /** Create (or fetch the existing) public share link. The URL is exposed via [shareUrl]
1725− * and also emitted once via [shareLinkEvents] so the UI can copy it to the clipboard. */
1726− fun shareSession() {
1727− val conn = connection ?: return
1728− viewModelScope.launch {
1729− runCatchingCancellable { conn.api.shareSession(sessionId) }
1730− .onSuccess { session ->
1731− val url = session.share?.url?.takeIf { it.isNotBlank() }
1732− _shareUrl.value = url
1733− if (url != null) _shareLinkEvents.trySend(url)
1734− }
1735− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1736− }
1737− }
1738−
1739− /** Revoke the session's public share link. */
1740− fun unshareSession() {
1741− val conn = connection ?: return
1742− viewModelScope.launch {
1743− runCatchingCancellable { conn.api.unshareSession(sessionId) }
1744− .onSuccess { _shareUrl.value = it.share?.url?.takeIf { it.isNotBlank() } }
1745− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1746− }
1747− }
1748−
1749− /** Compact the conversation via the summarize endpoint; the summary streams back via SSE.
1750− * Uses the currently-selected model (required by the endpoint). */
1751− fun summarize() {
1752− val conn = connection ?: return
1753− val model = _selectedModel.value?.ref ?: run {
1754− _errorEvents.trySend(ChatError(container.string(R.string.needs_model)))
1755− return
1756− }
1757− if (!beginRun()) {
1758− _errorEvents.trySend(ChatError(container.string(R.string.command_busy)))
1759− return
1760− }
1761− // A new run is starting: reopen the re-light gate (as send() does) so a mid-run SSE
1762− // reconnect keeps the working indicator lit instead of leaving it stuck off.
1763− runEndedByIdle = false
1764− viewModelScope.launch {
1765− runCatchingCancellable { conn.api.summarize(sessionId, model) }
1766− .onFailure {
1767− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1768− _running.value = false
1769− }
1770− }
1771− }
1772−
1773− /** Analyze the project and (re)generate its AGENTS.md; the run streams back via SSE. */
1774− fun initProject() {
1775− val conn = connection ?: return
1776− if (!beginRun()) {
1777− _errorEvents.trySend(ChatError(container.string(R.string.command_busy)))
1778− return
1779− }
1780− // A new run is starting: reopen the re-light gate (as send() does) so a mid-run SSE
1781− // reconnect keeps the working indicator lit instead of leaving it stuck off.
1782− runEndedByIdle = false
1783− viewModelScope.launch {
1784− runCatchingCancellable { conn.api.initSession(sessionId) }
1785− .onFailure {
1786− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1787− _running.value = false
1788− }
1789− }
1790− }
1791−
1792− /** Run a one-off shell [command] in the session's worktree; output streams back via SSE.
1793− * The server requires an agent to scope the run — use the selected one, else the primary. */
1794− fun runShell(command: String) {
1795− val conn = connection ?: return
1796− val cmd = command.trim()
1797− if (cmd.isEmpty()) return
1798− val agent = _selectedAgent.value
1799− ?: _agents.value.firstOrNull { it.isPrimary }?.name
1800− ?: _agents.value.firstOrNull()?.name
1801− ?: DEFAULT_SHELL_AGENT
1802− if (!beginRun()) {
1803− _errorEvents.trySend(ChatError(container.string(R.string.command_busy)))
1804− return
1805− }
1806− // A new run is starting: reopen the re-light gate (as send() does) so a mid-run SSE
1807− // reconnect keeps the working indicator lit instead of leaving it stuck off.
1808− runEndedByIdle = false
1809− viewModelScope.launch {
1810− runCatchingCancellable { conn.api.shell(sessionId, cmd, agent, _selectedModel.value?.ref) }
1811− .onFailure {
1812− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1813− _running.value = false
1814− }
1815− }
1816− }
1817−
1818− /** Rename the current session via PATCH /session/:id. On success updates [sessionTitle]
1819− * so the top bar reflects the new name immediately. A failure surfaces as a snackbar;
1820− * the caller keeps the dialog open so the user can retry without retyping. */
1821− fun renameSession(newTitle: String) {
1822− val conn = connection ?: return
1823− val title = newTitle.trim()
1824− if (title.isEmpty() || title == _sessionTitle.value) return
1825− viewModelScope.launch {
1826− runCatchingCancellable { conn.api.updateSession(sessionId, title) }
1827− .onSuccess { _sessionTitle.value = it.displayTitle }
1828− .onFailure { _errorEvents.trySend(ChatError(container.friendlyError(it))) }
1829− }
1830− }
1831−
1832− /** Delete the current session via DELETE /session/:id. Schedules a deferred delete with an
1833− * undo window and signals [deleteUndoEvents] so the ChatScreen shows an Undo snackbar
1834− * *over the conversation the user is viewing* — they can cancel without first being
1835− * navigated back to the session list. The actual REST delete runs after
1836− * [NetworkConfig.undoDeleteDelayMs]; cancel via [cancelSessionDelete]. If the window
1837− * expires, the scheduled delete's onDeleted sets [sessionDeleted] so the UI navigates away.
1838− * A failure surfaces as a snackbar. */
1839− fun deleteSession() {
1840− val conn = connection ?: return
1841− container.scheduleSessionDelete(
1842− id = sessionId,
1843− delayMs = NetworkConfig.undoDeleteDelayMs,
1844− // Navigate away only once the deferred delete actually commits — so an in-place Undo
1845− // before the window expires keeps the user on this conversation.
1846− onDeleted = { _sessionDeleted.value = true },
1847− onError = { _errorEvents.trySend(ChatError(container.friendlyError(it))) },
1848− )
1849− _deleteUndoEvents.tryEmit(Unit)
1850− }
1851−
1852− /** Cancel a delete scheduled by [deleteSession] (the in-chat Undo action). Returns true if the
1853− * delete was still pending (Undo succeeded). */
1854− fun cancelSessionDelete(): Boolean = container.cancelSessionDelete(sessionId)
1855−
1856− /** Reconnect to the most recently used server profile (used when the connection is gone). */
1857− fun reconnect() {
1858− if (container.activeConnection.value != null) return
1859− // Guard against concurrent reconnect calls: the user can tap the button
1860− // multiple times while _reconnecting is true, which would launch parallel
1861− // connect() coroutines that race to set the active connection, leaking the
1862− // intermediate connections.
1863− if (!_reconnecting.compareAndSet(false, true)) return
1864− viewModelScope.launch {
1865− try {
1866− val recent = runCatchingCancellable { container.profileStore.profiles.first() }
1867− .getOrDefault(emptyList())
1868− .firstOrNull()
1869− if (recent == null) {
1870− _errorEvents.trySend(ChatError(container.string(R.string.no_servers_to_reconnect)))
1871− return@launch
1872− }
1873− runCatchingCancellable {
1874− val conn = container.connect(recent)
1875− conn.api.ping()
1876− }.onFailure {
1877− container.disconnect()
1878− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1879− }
1880− } finally {
1881− _reconnecting.value = false
1882− }
1883− }
1884− }
1885−
1886− fun respondPermission(permission: Permission, response: PermissionResponse) {
1887− val conn = connection ?: return
1888− // Record a session-scoped grant so subsequent matching requests are auto-answered.
1889− // SESSION maps to ONCE on the wire (the server has no session-scope concept); the
1890− // client-side set is what gives it the "for this session" semantics.
1891− if (response == PermissionResponse.SESSION) {
1892− val type = permission.type.orEmpty()
1893− val pattern = permission.patternText.orEmpty()
1894− if (type.isNotEmpty()) sessionAllowed.add(type to pattern)
1895− }
1896− // Dismiss optimistically (revealing any queued request); permission.replied will confirm.
1897− // If the call fails we re-surface this request so the user can retry instead of being stuck
1898− // with a dismissed dialog and a tool run that's still paused server-side.
1899− resolvePermission(permission.id)
1900− viewModelScope.launch {
1901− runCatchingCancellable { conn.api.respondPermission(sessionId, permission.id, response) }
1902− .onFailure {
1903− _errorEvents.trySend(ChatError(container.friendlyError(it)))
1904− // Revoke the session-scoped grant on failure: enqueuePermission() auto-responds
1905− // when (type, pattern) is in sessionAllowed, so leaving the entry in would loop
1906− // respondPermission -> fail -> enqueuePermission -> respondPermission ... forever,
1907− // spamming the dead server and the error snackbar without ever re-prompting the
1908− // user. Removing it makes enqueuePermission fall through to re-queueing the
1909− // request for the dialog so the user can retry.
1910− //
1911− // This must cover BOTH the SESSION and ONCE response paths: enqueuePermission's
1912− // auto-respond sends ONCE, not SESSION, so guarding only the SESSION branch (as
1913− // the original code did) leaves the entry in and still loops when the auto-reply
1914− // fails. Revoke unconditionally on any failure.
1915− val type = permission.type.orEmpty()
1916− val pattern = permission.patternText.orEmpty()
1917− if (type.isNotEmpty()) sessionAllowed.remove(type to pattern)
1918− enqueuePermission(permission)
1919− }
1920− }
1921− }
1922−
1923− private companion object {
1924− /** Fallback agent for the shell endpoint when none is selected and no agent catalog
1925− * loaded. opencode's default primary agent is "build". */
1926− const val DEFAULT_SHELL_AGENT = "build"
1927− }
1928−
1929− override fun onCleared() {
1930− super.onCleared()
1931− // Flush any pending debounced draft so it survives navigation. Uses an
1932− // asynchronous apply() (not a synchronous commit) so the main thread isn't
1933− // blocked on disk I/O — Android's SharedPreferences framework guarantees
1934− // pending apply() writes are flushed before the process exits.
1935− // Flush the pending draft — including an empty one. Persistence is otherwise debounced,
1936− // so if the user cleared the input and navigated back within the debounce window, the
1937− // debounce coroutine was cancelled with viewModelScope and the prefs still hold the
1938− // previous non-empty draft. flushDraft() removes the key when the text is blank, so
1939− // flushing commits the clear instead of resurrecting the deleted text.
1940− //
1941− // BUT respect the send-in-flight guard: send() optimistically clears _draft to "" WITHOUT
1942− // persisting the clear so a failed send can restore the text. If the user taps Send then
1943− // immediately navigates back (cancelling the in-flight send), flushing the blank _draft here
1944− // would remove the persisted key and erase the pre-send draft with no recovery. Skip the
1945− // flush while a send is in flight so the pre-send draft stays persisted (recoverable).
1946− if (!suppressDraftPersist.get()) container.draftStore.flushDraft(sessionId, _draft.value)
1947− }
1948−}
app/src/main/java/soy/iko/opencode/ui/chat/CommandPickerSheet.ktdeleted−248
@@ -1,248 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import androidx.compose.foundation.clickable
4−import androidx.compose.foundation.layout.Column
5−import androidx.compose.foundation.layout.Row
6−import androidx.compose.foundation.layout.fillMaxWidth
7−import androidx.compose.foundation.layout.heightIn
8−import androidx.compose.foundation.layout.imePadding
9−import androidx.compose.foundation.layout.navigationBarsPadding
10−import androidx.compose.foundation.layout.padding
11−import androidx.compose.foundation.lazy.LazyColumn
12−import androidx.compose.foundation.lazy.items
13−import androidx.compose.foundation.text.KeyboardActions
14−import androidx.compose.foundation.text.KeyboardOptions
15−import androidx.compose.material.icons.Icons
16−import androidx.compose.material.icons.automirrored.filled.PlaylistPlay
17−import androidx.compose.material.icons.filled.Close
18−import androidx.compose.material.icons.filled.Search
19−import androidx.compose.material3.CircularProgressIndicator
20−import androidx.compose.material3.ExperimentalMaterial3Api
21−import androidx.compose.material3.Icon
22−import androidx.compose.material3.IconButton
23−import androidx.compose.material3.MaterialTheme
24−import androidx.compose.material3.ModalBottomSheet
25−import androidx.compose.material3.OutlinedTextField
26−import androidx.compose.material3.Text
27−import androidx.compose.material3.AlertDialog
28−import androidx.compose.material3.TextButton
29−import androidx.compose.material3.rememberModalBottomSheetState
30−import androidx.compose.runtime.Composable
31−import androidx.compose.runtime.LaunchedEffect
32−import androidx.compose.runtime.getValue
33−import androidx.compose.runtime.mutableStateOf
34−import androidx.compose.runtime.remember
35−import androidx.compose.runtime.rememberCoroutineScope
36−import androidx.compose.runtime.saveable.rememberSaveable
37−import androidx.compose.runtime.setValue
38−import androidx.compose.ui.Alignment
39−import androidx.compose.ui.Modifier
40−import androidx.compose.ui.focus.FocusRequester
41−import androidx.compose.ui.focus.focusRequester
42−import androidx.compose.ui.hapticfeedback.HapticFeedbackType
43−import androidx.compose.ui.platform.LocalHapticFeedback
44−import androidx.compose.ui.platform.LocalSoftwareKeyboardController
45−import androidx.compose.ui.res.stringResource
46−import androidx.compose.ui.semantics.Role
47−import androidx.compose.ui.semantics.contentDescription
48−import androidx.compose.ui.semantics.semantics
49−import androidx.compose.ui.semantics.stateDescription
50−import androidx.compose.ui.text.input.ImeAction
51−import androidx.compose.ui.text.style.TextOverflow
52−import androidx.compose.ui.unit.dp
53−import androidx.compose.foundation.layout.Box
54−import kotlinx.coroutines.launch
55−import soy.iko.opencode.data.model.Command
56−import soy.iko.opencode.data.network.NetworkConfig
57−import soy.iko.opencode.R
58−
59−/** Bottom sheet that lists slash-commands; selecting one invokes it. */
60−@OptIn(ExperimentalMaterial3Api::class)
61−@Composable
62−fun CommandPickerSheet(
63− commands: List<Command>,
64− loading: Boolean,
65− error: Boolean,
66− onSelect: (Command) -> Unit,
67− onRetry: () -> Unit,
68− onDismiss: () -> Unit,
69−) {
70− // Persist only the command *name* (a savable String), not the Command itself: a
71− // kotlinx @Serializable Command is neither Parcelable nor java.io.Serializable, so
72− // routing it through rememberSaveable crashes on rotation while the confirm dialog
73− // is open. Re-resolve the full Command from the current list for rendering.
74− var pendingCommandName by rememberSaveable { mutableStateOf<String?>(null) }
75− val pendingCommand = pendingCommandName?.let { name -> commands.firstOrNull { it.name == name } }
76− // Hoist SheetState + skipPartiallyExpanded (see AgentPickerSheet for the full rationale).
77− val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
78− val scope = rememberCoroutineScope()
79− ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
80− Text(
81− stringResource(R.string.commands),
82− style = MaterialTheme.typography.titleMedium,
83− modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
84− )
85− if (loading) {
86− val loadingLabel = stringResource(R.string.loading_commands)
87− Column(
88− modifier = Modifier.fillMaxWidth().padding(vertical = 24.dp).imePadding(),
89− horizontalAlignment = Alignment.CenterHorizontally,
90− ) {
91− CircularProgressIndicator(Modifier.semantics { contentDescription = loadingLabel })
92− Text(
93− stringResource(R.string.loading_commands),
94− style = MaterialTheme.typography.bodyMedium,
95− color = MaterialTheme.colorScheme.onSurfaceVariant,
96− modifier = Modifier.padding(top = 8.dp),
97− )
98− }
99− } else if (error && commands.isEmpty()) {
100− Column(
101− modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 16.dp),
102− horizontalAlignment = Alignment.CenterHorizontally,
103− ) {
104− Text(
105− stringResource(R.string.load_failed),
106− style = MaterialTheme.typography.bodyMedium,
107− color = MaterialTheme.colorScheme.error,
108− )
109− TextButton(onClick = onRetry) { Text(stringResource(R.string.retry)) }
110− }
111− } else if (commands.isEmpty()) {
112− Text(
113− stringResource(R.string.no_commands),
114− style = MaterialTheme.typography.bodyMedium,
115− color = MaterialTheme.colorScheme.onSurfaceVariant,
116− modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp),
117− )
118− } else {
119− var query by rememberSaveable { mutableStateOf("") }
120− val keyboardController = LocalSoftwareKeyboardController.current
121− val haptics = LocalHapticFeedback.current
122− // Resolved once (not per-row): the semantics lambda below isn't a composable scope,
123− // so stringResource can't be called inside it.
124− val destructiveStateLabel = stringResource(R.string.command_confirmation_required)
125− // Auto-focus the search field (and raise the keyboard) when the sheet opens, but skip
126− // it for a short list that's faster to scan by eye than to filter.
127− val searchFocus = remember { FocusRequester() }
128− LaunchedEffect(Unit) {
129− if (commands.size > NetworkConfig.pickerSearchAutofocusThreshold) {
130− runCatching { searchFocus.requestFocus() }
131− }
132− }
133− OutlinedTextField(
134− value = query,
135− onValueChange = { query = it },
136− modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp).focusRequester(searchFocus),
137− placeholder = { Text(stringResource(R.string.search_commands)) },
138− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
139− trailingIcon = if (query.isNotEmpty()) {
140− {
141− IconButton(onClick = { query = "" }) {
142− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
143− }
144− }
145− } else null,
146− singleLine = true,
147− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
148− keyboardActions = KeyboardActions(onSearch = { keyboardController?.hide() }),
149− )
150− // Dedupe the source list once, then filter the distinct list.
151− val distinct = remember(commands) { commands.distinctBy { it.name } }
152− val filtered = remember(distinct, query) {
153− val q = query.trim()
154− if (q.isEmpty()) distinct
155− else distinct.filter {
156− it.name.contains(q, ignoreCase = true) ||
157− it.displayDescription.contains(q, ignoreCase = true)
158− }
159− }
160− if (filtered.isEmpty()) {
161− Text(
162− stringResource(R.string.no_commands_match, query.trim()),
163− style = MaterialTheme.typography.bodyMedium,
164− color = MaterialTheme.colorScheme.onSurfaceVariant,
165− modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp),
166− )
167− } else {
168− LazyColumn(
169− modifier = Modifier
170− .heightIn(max = NetworkConfig.pickerSheetMaxHeightDp.dp)
171− .imePadding()
172− .navigationBarsPadding(),
173− ) {
174− items(filtered, key = { it.name }) { cmd ->
175− val destructive = isDestructiveCommand(cmd.name)
176− Column(
177− modifier = Modifier
178− .fillMaxWidth()
179− .clickable(role = Role.Button) {
180− haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)
181− if (destructive) {
182− pendingCommandName = cmd.name
183− } else {
184− scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() }
185− onSelect(cmd)
186− }
187− }
188− .semantics {
189− if (destructive) stateDescription = destructiveStateLabel
190− }
191− .padding(horizontal = 24.dp, vertical = 12.dp),
192− ) {
193− Row(
194− verticalAlignment = Alignment.CenterVertically,
195− ) {
196− Icon(Icons.AutoMirrored.Filled.PlaylistPlay, contentDescription = null)
197− Text(
198− "/${cmd.name}",
199− style = MaterialTheme.typography.bodyLarge,
200− modifier = Modifier.padding(start = 8.dp),
201− )
202− }
203− Text(
204− cmd.displayDescription,
205− style = MaterialTheme.typography.bodySmall,
206− color = MaterialTheme.colorScheme.onSurfaceVariant,
207− maxLines = 2,
208− overflow = TextOverflow.Ellipsis,
209− modifier = Modifier.padding(start = 28.dp, top = 2.dp),
210− )
211− }
212− }
213− }
214− }
215− }
216− }
217−
218− // Confirmation for commands whose name suggests they may discard work or reset state,
219− // so a tap doesn't irrevocably run e.g. /clear or /compact without consent.
220− pendingCommand?.let { cmd ->
221− AlertDialog(
222− onDismissRequest = { pendingCommandName = null },
223− title = { Text(stringResource(R.string.run_command_title, cmd.name)) },
224− text = { Text(stringResource(R.string.run_command_text, "/${cmd.name}")) },
225− confirmButton = {
226− TextButton(onClick = {
227− pendingCommandName = null
228− scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() }
229− onSelect(cmd)
230− }) { Text(stringResource(R.string.run)) }
231− },
232− dismissButton = {
233− TextButton(onClick = { pendingCommandName = null }) { Text(stringResource(R.string.cancel)) }
234− },
235− )
236− }
237−}
238−
239−/**
240− * Heuristic for commands that may be destructive (discard work / reset state) and so
241− * warrant a confirmation step before invocation. Matches common opencode slash-command
242− * names; non-matching commands invoke immediately.
243− */
244−private fun isDestructiveCommand(name: String): Boolean {
245− val n = name.lowercase()
246− return n in setOf("clear", "compact", "delete", "reset", "remove", "wipe", "drop", "purge") ||
247− n.startsWith("clear-") || n.startsWith("compact-") || n.startsWith("reset-")
248−}
app/src/main/java/soy/iko/opencode/ui/chat/ConversationExport.ktdeleted−236
@@ -1,236 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import soy.iko.opencode.data.model.AssistantMessage
4−import soy.iko.opencode.data.model.FilePart
5−import soy.iko.opencode.data.model.MessageWithParts
6−import soy.iko.opencode.data.model.ReasoningPart
7−import soy.iko.opencode.data.model.TextPart
8−import soy.iko.opencode.data.model.ToolCompleted
9−import soy.iko.opencode.data.model.ToolError
10−import soy.iko.opencode.data.model.ToolPart
11−import soy.iko.opencode.data.model.ToolRunning
12−import soy.iko.opencode.data.model.UserMessage
13−import soy.iko.opencode.data.model.sourcePath
14−import soy.iko.opencode.data.network.NetworkConfig
15−import soy.iko.opencode.data.network.OpencodeJson
16−import kotlinx.serialization.builtins.ListSerializer
17−import java.text.SimpleDateFormat
18−import java.util.Date
19−import java.util.Locale
20−
21−/**
22− * Render a conversation as a lossless JSON document for sharing/exporting. Unlike
23− * [buildConversationMarkdown], this preserves the full fidelity of the server's
24− * message stream: tool outputs are not truncated, file parts keep their source
25− * objects and data URLs, reasoning keeps its raw text, and the polymorphic
26− * `type`/`role` discriminators are retained. That makes the JSON export suitable
27− * for re-importing into another client, for auditing exactly what the agent did,
28− * and for bug reports where the Markdown summary would have dropped detail.
29− *
30− * Uses the shared [OpencodeJson] so the on-the-wire shape round-trips — the same
31− * serializer that decoded the messages re-encodes them, including the `Unknown*`
32− * fallback variants for parts/roles the client doesn't otherwise model.
33− */
34−fun buildConversationJson(messages: List<MessageWithParts>): String =
35− try {
36− // Explicit serializer (mirrors MessageCacheStore) rather than the reified
37− // encodeToString overload, so the polymorphic Part/MessageInfo discriminators
38− // registered in OpencodeJson are exercised on the way back out.
39− OpencodeJson.encodeToString(ListSerializer(MessageWithParts.serializer()), messages)
40− } catch (e: Throwable) {
41− // Fall back to an explicit error document rather than crashing the share
42− // flow; a serialization failure here is most likely a model invariant bug
43− // and a silent empty string would be harder to diagnose than this stub.
44− "{\"error\":\"conversation_json_export_failed\",\"message\":\"${e.message ?: e.javaClass.simpleName}\"}"
45− }
46−
47−/**
48− * Render a conversation as Markdown for sharing/exporting. Each message becomes a
49− * role-prefixed section containing its text parts; reasoning is exported as a blockquote
50− * and tool calls are summarized so the transcript shows what the agent *did*, not just
51− * what it said. Pure (no Android deps) so it can be unit-tested directly.
52− */
53−fun buildConversationMarkdown(messages: List<MessageWithParts>, title: String?): String {
54− val sb = StringBuilder(messages.size * 128)
55− if (!title.isNullOrBlank()) {
56− sb.append("# ").append(escapeMarkdown(title.trim())).append("\n\n")
57− }
58− appendMetadataHeader(sb, messages)
59− for (message in messages) {
60− val heading = when (message.info) {
61− is UserMessage -> "## You"
62− is AssistantMessage -> "## opencode"
63− else -> null
64− } ?: continue
65− // The assistant's reply text is already Markdown (code fences, bold, headings);
66− // escaping it would render the export as backslash noise. Only escape user-authored
67− // text, which isn't expected to be Markdown.
68− val escapeText = message.info is UserMessage
69− val body = message.parts
70− .mapNotNull { part ->
71− when (part) {
72− is TextPart -> part.text.takeIf { it.isNotBlank() }
73− ?.let { if (escapeText) escapeMarkdown(it) else it }
74− is ReasoningPart -> part.text.takeIf { it.isNotBlank() }
75− ?.let { text -> text.trim().lines().joinToString("\n") { "> _${escapeMarkdown(it)}_" } }
76− is ToolPart -> formatToolCall(part)
77− is FilePart -> {
78− // Image/file attachments aren't portable in a text export; emit a
79− // labeled placeholder so the transcript records that one was present
80− // (useful for debugging) instead of silently dropping it.
81− val name = part.sourcePath ?: part.url ?: part.filename ?: "attachment"
82− if (part.mime?.startsWith("image/") == true) "_[image: ${escapeMarkdown(name)}]_"
83− else "_[file: ${escapeMarkdown(name)}]_"
84− }
85− else -> null
86− }
87− }
88− .joinToString("\n\n")
89− .trim()
90− if (body.isEmpty()) continue
91− sb.append(heading).append("\n\n")
92− // Per-message timestamp (ISO, local zone) so an exported transcript is useful for
93− // support/debugging — without it only the metadata header's global range has timing.
94− message.info.time?.created?.let { ts -> sb.append("_").append(formatExportTimestamp(ts)).append("_\n\n") }
95− sb.append(body).append("\n\n")
96− }
97− return sb.toString().trimEnd()
98−}
99−
100−/**
101− * Render a single message as Markdown for per-message sharing. A trimmed-down version of
102− * [buildConversationMarkdown] that emits just this message's role heading + body (no metadata
103− * header), so a shared single reply/exchange is self-contained without dragging the whole
104− * transcript. Returns null when the message has no exportable body (e.g. an image-only prompt).
105− */
106−fun buildMessageMarkdown(message: MessageWithParts): String? {
107− val heading = when (message.info) {
108− is UserMessage -> "## You"
109− is AssistantMessage -> "## opencode"
110− else -> return null
111− }
112− val escapeText = message.info is UserMessage
113− val body = message.parts
114− .mapNotNull { part ->
115− when (part) {
116− is TextPart -> part.text.takeIf { it.isNotBlank() }
117− ?.let { if (escapeText) escapeMarkdown(it) else it }
118− is ReasoningPart -> part.text.takeIf { it.isNotBlank() }
119− ?.let { text -> text.trim().lines().joinToString("\n") { "> _${escapeMarkdown(it)}_" } }
120− is ToolPart -> formatToolCall(part)
121− is FilePart -> {
122− val name = part.sourcePath ?: part.url ?: part.filename ?: "attachment"
123− if (part.mime?.startsWith("image/") == true) "_[image: ${escapeMarkdown(name)}]_"
124− else "_[file: ${escapeMarkdown(name)}]_"
125− }
126− else -> null
127− }
128− }
129− .joinToString("\n\n")
130− .trim()
131− if (body.isEmpty()) return null
132− return buildString {
133− append(heading).append("\n\n")
134− message.info.time?.created?.let { ts -> append("_").append(formatExportTimestamp(ts)).append("_\n\n") }
135− append(body)
136− }
137−}
138−
139−/** Format an epoch-millis as a locale-stable ISO-ish timestamp for the export. Thread-confined
140− * to the exporting coroutine, so a shared SimpleDateFormat (not thread-safe) is fine. */
141−private fun formatExportTimestamp(epochMillis: Long): String =
142− SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date(epochMillis))
143−
144−/** Append a metadata header (message counts + timestamp range) so a shared transcript has
145− * context for support/debugging. Skipped when there are no messages. */
146−private fun appendMetadataHeader(sb: StringBuilder, messages: List<MessageWithParts>) {
147− if (messages.isEmpty()) return
148− val userCount = messages.count { it.info is UserMessage }
149− val assistantCount = messages.count { it.info is AssistantMessage }
150− val firstTime = messages.firstOrNull()?.info?.time?.created
151− val lastTime = messages.lastOrNull()?.info?.time?.created
152− sb.append("> ")
153− // Pluralize each noun independently (a prior bug keyed both on userCount, so "user" was
154− // never pluralized and "message" was pluralized based on the wrong count).
155− sb.append("$userCount user")
156− if (userCount != 1) sb.append("s")
157− sb.append(" · $assistantCount assistant message")
158− if (assistantCount != 1) sb.append("s")
159− if (firstTime != null && lastTime != null) {
160− sb.append(" · ${formatExportTimestamp(firstTime)} → ${formatExportTimestamp(lastTime)}")
161− }
162− sb.append("\n\n---\n\n")
163−}
164−
165−/** Render a tool call as a compact, readable blockquote summary: the tool name, its
166− * human-readable title (if any), and a truncated output/error. Keeps the exported
167− * transcript useful when the agent's work (edits, command runs) is the substance. */
168−private fun formatToolCall(part: ToolPart): String? {
169− val title = when (val s = part.state) {
170− is ToolRunning -> s.title
171− is ToolCompleted -> s.title
172− else -> null
173− }
174− val detail = when (val s = part.state) {
175− is ToolCompleted -> s.output?.takeIf { it.isNotBlank() }?.let { truncateOutput(it) }
176− is ToolError -> s.error?.takeIf { it.isNotBlank() }?.let { "Error: ${truncateOutput(it)}" }
177− else -> null
178− }
179− val status = when (part.state) {
180− is ToolCompleted -> null
181− is ToolError -> " — error"
182− is ToolRunning -> " — running"
183− else -> null
184− }
185− val head = "**${part.tool}**${status ?: ""}"
186− val titleLine = title?.takeIf { it.isNotBlank() }?.let { escapeMarkdown(it) }
187− return buildList {
188− add("> $head")
189− if (titleLine != null) add("> $titleLine")
190− // Prefix every detail line with "> " so the fenced code block stays inside the
191− // blockquote — otherwise lines after the first fall out of the quote.
192− if (detail != null) {
193− val quoted = detail.lines().joinToString("\n") { "> $it" }
194− // Use a fence longer than the longest backtick run in the content, so tool output
195− // that itself contains a ``` sequence (shell output echoing markdown, etc.) can't
196− // prematurely close the block and make the rest of the transcript render broken.
197− val fence = "`".repeat(maxOf(3, longestBacktickRun(detail) + 1))
198− add(">\n> $fence\n$quoted\n> $fence")
199− }
200− }.joinToString("\n").takeIf { it.isNotBlank() }
201−}
202−
203−/** Length of the longest consecutive run of backticks in [text] (0 if none). */
204−private fun longestBacktickRun(text: String): Int {
205− var max = 0
206− var current = 0
207− for (c in text) {
208− if (c == '`') {
209− current++
210− if (current > max) max = current
211− } else {
212− current = 0
213− }
214− }
215− return max
216−}
217−
218−private fun truncateOutput(output: String): String {
219− if (output.length <= NetworkConfig.exportToolOutputLimitChars) return output
220− return output.take(NetworkConfig.exportToolOutputLimitChars) + "\n… (truncated)"
221−}
222−
223−/** Escape markdown special characters so user/model text doesn't produce malformed markdown.
224− * Extends the basic set with [ ] ( ) - + ! so user text containing links, list markers, or
225− * image syntax doesn't render as live Markdown in the exported transcript. */
226−private fun escapeMarkdown(text: String): String {
227− if (text.isEmpty()) return text
228− val sb = StringBuilder(text.length + 16)
229− for (c in text) {
230− when (c) {
231− '\\', '*', '_', '#', '`', '>', '[', ']', '(', ')', '!', '+', '-' -> sb.append('\\')
232− }
233− sb.append(c)
234− }
235− return sb.toString()
236−}
app/src/main/java/soy/iko/opencode/ui/chat/CostFormat.ktdeleted−60
@@ -1,60 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import soy.iko.opencode.data.model.Tokens
4−
5−// NumberFormat.getNumberInstance performs an expensive ICU locale lookup + object
6−// construction on every call. Reuse a thread-local instance so repeated calls (e.g.
7−// when the message list re-seeds after a reconnect and every visible assistant bubble
8−// recomposes at once) don't each pay that cost. Thread-local because NumberFormat is
9−// not thread-safe.
10−internal val tokenNumberFormat: ThreadLocal<java.text.NumberFormat> = ThreadLocal.withInitial {
11− java.text.NumberFormat.getNumberInstance(java.util.Locale.US)
12−}
13−
14−internal fun formatTokens(tokens: Tokens, format: String): String {
15− val nf = tokenNumberFormat.get()!!
16− return format.format(nf.format(tokens.input), nf.format(tokens.output))
17−}
18−
19−internal fun formatCost(cost: Double, shortFormat: String, longFormat: String): String =
20− // Locale.US so the formatting is stable regardless of device locale (avoids
21− // non-ASCII digits or comma decimal separators in a dollar amount). The format
22− // string itself is localized via strings.xml so the currency symbol can be
23− // adapted by translators.
24− if (cost < 0.01) String.format(java.util.Locale.US, longFormat, cost)
25− else String.format(java.util.Locale.US, shortFormat, cost)
26−
27−/** Assemble the single-line cost/tokens summary for an assistant bubble. Returns null when the
28− * message isn't complete, when neither cost nor tokens were reported, or when every figure is
29− * zero (so the bubble doesn't show a meaningless "0 in · 0 out • $0.0000"). Extracted from
30− * [AssistantBlock] to keep that function's cyclomatic complexity under the detekt threshold.
31− * Reasoning and cache segments are added only when non-zero. */
32−internal fun buildCostSummary(
33− isComplete: Boolean,
34− tokens: Tokens?,
35− cost: Double?,
36− tokenFormat: String,
37− reasoningFormat: String,
38− cacheReadFormat: String,
39− cacheWriteFormat: String,
40− costShort: String,
41− costLong: String,
42−): String? {
43− if (!isComplete || (cost == null && tokens == null)) return null
44− val nf = tokenNumberFormat.get()!!
45− return buildList {
46− // Skip an all-zero token count (e.g. a completed message that reported no usage) so
47− // the bubble doesn't show a meaningless "0 in · 0 out".
48− tokens?.takeIf { it.input > 0 || it.output > 0 }?.let { add(formatTokens(it, tokenFormat)) }
49− tokens?.takeIf { it.reasoning > 0 }?.let {
50− add(reasoningFormat.format(nf.format(it.reasoning)))
51− }
52− tokens?.cache?.takeIf { it.read > 0 }?.let {
53− add(cacheReadFormat.format(nf.format(it.read)))
54− }
55− tokens?.cache?.takeIf { it.write > 0 }?.let {
56− add(cacheWriteFormat.format(nf.format(it.write)))
57− }
58− cost?.takeIf { it > 0 }?.let { add(formatCost(it, costShort, costLong)) }
59− }.takeIf { it.isNotEmpty() }?.joinToString(" • ")
60−}
app/src/main/java/soy/iko/opencode/ui/chat/MessageBubble.ktdeleted−1418

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/ModelPickerSheet.ktdeleted−330

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/PartRenderer.ktdeleted−802

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/PermissionDialog.ktdeleted−321

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/TodoPlan.ktdeleted−205

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/TtsController.ktdeleted−257

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/ViewSourceDialog.ktdeleted−76

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/AppTopBar.ktdeleted−82

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/Autofill.ktdeleted−49

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/ChatTextPrefs.ktdeleted−54

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/CodeHighlighter.ktdeleted−632

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/CommandPalette.ktdeleted−171

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/CommonStates.ktdeleted−170

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/CompactNavBar.ktdeleted−106

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/ConnectionBanner.ktdeleted−266

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/DiffView.ktdeleted−662

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/EmptyState.ktdeleted−77

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/GatedHapticFeedback.ktdeleted−33

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/LargeScreenNavRail.ktdeleted−109

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/LoadingSize.ktdeleted−12

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/LoadingSpinner.ktdeleted−40

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/MarkdownText.ktdeleted−855

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.ktnew file+479

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/PaletteAction.ktdeleted−11

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/ReducedMotion.ktdeleted−131

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/RelativeTimeUnit.ktdeleted−56

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/RemoteImage.ktdeleted−577

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/SectionHeader.ktdeleted−25

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/SkeletonRow.ktdeleted−97

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/TimeFormat.ktdeleted−194

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/file/FileBrowserScreen.ktdeleted−1016

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/file/FileBrowserViewModel.ktdeleted−279

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/file/FileViewModel.ktdeleted−91

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/file/FileViewScreen.ktdeleted−1272

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/file/TwoPaneFileBrowser.ktdeleted−117

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/mcp/McpScreen.ktdeleted−505

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/mcp/McpServerInfo.ktdeleted−76

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/mcp/McpViewModel.ktdeleted−169

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.ktnew file+590

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.ktnew file+222

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.ktnew file+402

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/search/GlobalSearchScreen.ktdeleted−427

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/search/GlobalSearchViewModel.ktdeleted−346

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/server/ServerEditScreen.ktdeleted−569

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/server/ServerEditViewModel.ktdeleted−508

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/server/ServerListScreen.ktdeleted−719

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/server/ServerListViewModel.ktdeleted−256

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/session/NewSessionDialog.ktdeleted−315

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/session/SessionListScreen.ktdeleted−2036

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/session/SessionListViewModel.ktdeleted−1115

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/session/TwoPaneSessionChat.ktdeleted−292

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/settings/DiagnosticsScreen.ktdeleted−681

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/settings/SettingsScreen.ktdeleted−1660

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/theme/Color.ktnew file+19

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/theme/Shapes.ktdeleted−19

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+38−179

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/theme/Type.ktnew file+15

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/theme/Typography.ktdeleted−136

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/usage/UsageAggregation.ktdeleted−151

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/usage/UsageScreen.ktdeleted−419

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/usage/UsageViewModel.ktdeleted−147

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/util/Contexts.ktdeleted−15

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/util/Coroutines.ktdeleted−56

This diff is too big to show here.

app/src/main/res/drawable/ic_action_block.xmldeleted−10

This diff is too big to show here.

app/src/main/res/drawable/ic_action_check.xmldeleted−9

This diff is too big to show here.

app/src/main/res/drawable/ic_action_refresh.xmldeleted−9

This diff is too big to show here.

app/src/main/res/drawable/ic_action_reply.xmldeleted−9

This diff is too big to show here.

app/src/main/res/drawable/ic_action_stop.xmldeleted−9

This diff is too big to show here.

app/src/main/res/drawable/ic_launcher_foreground.xmldeleted−13

This diff is too big to show here.

app/src/main/res/drawable/ic_stat_notify.xmldeleted−9

This diff is too big to show here.

app/src/main/res/drawable/widget_background.xmldeleted−8

This diff is too big to show here.

app/src/main/res/layout/widget_session_item.xmldeleted−21

This diff is too big to show here.

app/src/main/res/layout/widget_sessions.xmldeleted−64

This diff is too big to show here.

app/src/main/res/mipmap-anydpi/ic_launcher.xmldeleted−6

This diff is too big to show here.

app/src/main/res/values-es/strings.xmldeleted−905

This diff is too big to show here.

app/src/main/res/values-es/strings_cross_ux.xmldeleted−7

This diff is too big to show here.

app/src/main/res/values-es/strings_diag_ux.xmldeleted−4

This diff is too big to show here.

app/src/main/res/values-es/strings_notif_ux.xmldeleted−5

This diff is too big to show here.

app/src/main/res/values-es/strings_settings_ux.xmldeleted−12

This diff is too big to show here.

app/src/main/res/values-night/colors.xml+1−15

This diff is too big to show here.

app/src/main/res/values-night/themes.xml+2−2

This diff is too big to show here.

app/src/main/res/values/colors.xml+1−19

This diff is too big to show here.

app/src/main/res/values/strings.xml−928

This diff is too big to show here.

app/src/main/res/values/strings_cross_ux.xmldeleted−7

This diff is too big to show here.

app/src/main/res/values/strings_diag_ux.xmldeleted−4

This diff is too big to show here.

app/src/main/res/values/strings_notif_ux.xmldeleted−8

This diff is too big to show here.

app/src/main/res/values/strings_settings_ux.xmldeleted−12

This diff is too big to show here.

app/src/main/res/values/themes.xml+7−16

This diff is too big to show here.

app/src/main/res/xml/data_extraction_rules.xmldeleted−15

This diff is too big to show here.

app/src/main/res/xml/file_paths.xmldeleted−9

This diff is too big to show here.

app/src/main/res/xml/network_security_config.xmldeleted−15

This diff is too big to show here.

app/src/main/res/xml/sessions_widget_info.xmldeleted−10

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/M5DecodingTest.ktdeleted−144

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/M6Test.ktdeleted−102

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/OpencodeJsonTest.ktdeleted−122

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/UxTest.ktdeleted−104

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/core/ConnectUrlTest.ktnew file+69

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/model/TodoPlanTest.ktdeleted−90

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/network/EventStreamClientTest.ktdeleted−37

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/network/NormalizeBaseUrlTest.ktdeleted−42

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/network/OpencodeApiClientTest.ktdeleted−115

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/network/WithRetryTest.ktdeleted−254

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/repo/CrashLoggerScrubTest.ktdeleted−46

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/repo/ErrorKindTest.ktdeleted−60

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/repo/MessageStoreTest.ktdeleted−385

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/repo/OutboxStoreTest.ktdeleted−44

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/data/repo/SessionRepositoryTest.ktdeleted−73

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/di/UnreadTrackingTest.ktdeleted−56

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/chat/ChatViewModelTest.ktdeleted−650

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/chat/ConversationExportTest.ktdeleted−120

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/chat/ToolDurationFormatTest.ktdeleted−45

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/components/CodeHighlighterLanguageTest.ktdeleted−66

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/components/DiffParseTest.ktdeleted−55

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/components/ExtractCodeTextTest.ktdeleted−56

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/components/ExtractFenceLanguageTest.ktdeleted−28

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/file/FileBrowserViewModelTest.ktdeleted−231

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/file/FileViewModelTest.ktdeleted−70

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/mcp/McpParserTest.ktdeleted−52

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/search/GlobalSearchViewModelTest.ktdeleted−120

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/server/CertPinValidationTest.ktdeleted−39

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/server/ServerEditViewModelTest.ktdeleted−460

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/session/SessionListViewModelTest.ktdeleted−649

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/testing/TestFakes.ktdeleted−486

This diff is too big to show here.

app/src/test/java/soy/iko/opencode/ui/usage/UsageAggregationTest.ktdeleted−67

This diff is too big to show here.

build.gradle.kts+2−1

This diff is too big to show here.

config/detekt/detekt.ymldeleted−68

This diff is too big to show here.

flake.lock+3−3

This diff is too big to show here.

flake.nix+29−19

This diff is too big to show here.

generated/com/novi/bincode/BincodeDeserializer.javanew file+38

This diff is too big to show here.

generated/com/novi/bincode/BincodeSerializer.javanew file+33

This diff is too big to show here.

generated/com/novi/serde/ArrayLen.javanew file+12

This diff is too big to show here.

generated/com/novi/serde/BinaryDeserializer.javanew file+195

This diff is too big to show here.

generated/com/novi/serde/BinarySerializer.javanew file+146

This diff is too big to show here.

generated/com/novi/serde/Bytes.javanew file+54

This diff is too big to show here.

generated/com/novi/serde/DeserializationError.javanew file+11

This diff is too big to show here.

generated/com/novi/serde/Deserializer.javanew file+56

This diff is too big to show here.

generated/com/novi/serde/Int128.javanew file+11

This diff is too big to show here.

generated/com/novi/serde/SerializationError.javanew file+11

This diff is too big to show here.

generated/com/novi/serde/Serializer.javanew file+58

This diff is too big to show here.

generated/com/novi/serde/Slice.javanew file+40

This diff is too big to show here.

generated/com/novi/serde/Tuple2.javanew file+40

This diff is too big to show here.

generated/com/novi/serde/Tuple3.javanew file+46

This diff is too big to show here.

generated/com/novi/serde/Tuple4.javanew file+54

This diff is too big to show here.

generated/com/novi/serde/Tuple5.javanew file+61

This diff is too big to show here.

generated/com/novi/serde/Tuple6.javanew file+67

This diff is too big to show here.

generated/com/novi/serde/Unit.javanew file+20

This diff is too big to show here.

generated/com/novi/serde/Unsigned.javanew file+11

This diff is too big to show here.

generated/soy/iko/opencode/shared/MessageStatus.javanew file+150

This diff is too big to show here.

generated/soy/iko/opencode/shared/MessageView.javanew file+131

This diff is too big to show here.

generated/soy/iko/opencode/shared/Requests.javanew file+27

This diff is too big to show here.

generated/soy/iko/opencode/shared/Screen.javanew file+150

This diff is too big to show here.

generated/soy/iko/opencode/shared/SessionView.javanew file+77

This diff is too big to show here.

generated/soy/iko/opencode/shared/ToolView.javanew file+86

This diff is too big to show here.

generated/soy/iko/opencode/shared/TraitHelpers.javanew file+71

This diff is too big to show here.

generated/soy/iko/opencode/shared/ViewModel.javanew file+185

This diff is too big to show here.

gradle.properties+5−2

This diff is too big to show here.

gradle/libs.versions.toml+29−58

This diff is too big to show here.

gradle/wrapper/gradle-wrapper.properties+1−1

This diff is too big to show here.

renovate.jsondeleted−32

This diff is too big to show here.

scripts/run-device.shdeleted−106

This diff is too big to show here.

scripts/run.shdeleted−95

This diff is too big to show here.

settings.gradle.kts+3

This diff is too big to show here.

shared/Cargo.locknew file+1358

This diff is too big to show here.

shared/Cargo.tomlnew file+31

This diff is too big to show here.

shared/src/app.rsnew file+1051

This diff is too big to show here.

shared/src/bin/codegen.rsnew file+35

This diff is too big to show here.

shared/src/lib.rsnew file+17

This diff is too big to show here.

shared/src/protocol.rsnew file+248

This diff is too big to show here.