git.iko.soy/opencode-android
on master help sign in
.github/workflows/build.yml+12
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:
.github/workflows/release.yml+48−36
@@ -1,17 +1,28 @@
1name: Release
1name: Release
2
2
3−# Build a signed production 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.08.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.
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,14 +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
37 CODE="$(git rev-list --count HEAD)"
59 CODE="$(git rev-list --count HEAD)"
60+ {
38− echo "version=$VERSION" >> "$GITHUB_OUTPUT"
61+ echo "version=$VERSION"
62+ echo "tag=$TAG"
63+ echo "code=$CODE"
39− echo "code=$CODE" >> "$GITHUB_OUTPUT"
64+ } >> "$GITHUB_OUTPUT"
40− echo "Version: $VERSION (code $CODE)"
65+ echo "Releasing $TAG (version $VERSION, code $CODE)"
41
66
42 - uses: actions/setup-java@v4
67 - uses: actions/setup-java@v4
43 with:
68 with:
@@ -49,43 +74,30 @@ jobs:
49 - uses: gradle/actions/setup-gradle@v4
74 - uses: gradle/actions/setup-gradle@v4
50
75
51 # 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.
52− # 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`.
53− # unsigned APK (the same behavior as a local build), so this workflow is
54− # green even before signing is wired up.
55 - name: Decode signing keystore
78 - name: Decode signing keystore
56 if: env.OPENCODE_STORE_BASE64 != ''
79 if: env.OPENCODE_STORE_BASE64 != ''
57− env:
58− OPENCODE_STORE_BASE64: ${{ secrets.OPENCODE_STORE_BASE64 }}
59 run: |
80 run: |
60 STORE_FILE="$RUNNER_TEMP/release.keystore"
81 STORE_FILE="$RUNNER_TEMP/release.keystore"
61 printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > "$STORE_FILE"
82 printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > "$STORE_FILE"
62 echo "OPENCODE_STORE_FILE=$STORE_FILE" >> "$GITHUB_ENV"
83 echo "OPENCODE_STORE_FILE=$STORE_FILE" >> "$GITHUB_ENV"
63
84
64 - name: Build release APK
85 - name: Build release APK
65− env:
66− OPENCODE_STORE_FILE: ${{ env.OPENCODE_STORE_FILE }}
67− OPENCODE_STORE_PASSWORD: ${{ secrets.OPENCODE_STORE_PASSWORD }}
68− OPENCODE_KEY_ALIAS: ${{ secrets.OPENCODE_KEY_ALIAS }}
69− OPENCODE_KEY_PASSWORD: ${{ secrets.OPENCODE_KEY_PASSWORD }}
70 run: |
86 run: |
71 ./gradlew assembleRelease \
87 ./gradlew assembleRelease \
72 -PversionName="${{ steps.version.outputs.version }}" \
88 -PversionName="${{ steps.version.outputs.version }}" \
89+ -PversionCode="${{ steps.version.outputs.code }}" \
73 --no-daemon
90 --no-daemon
74
91
75− # Rename to a stable, version-tagged filename so the release attachment is
92+ # Rename to a stable, version-tagged filename for the release attachment.
76− # recognizable regardless of the release/ vs release-signed/ output dir.
77 - name: Stage APK
93 - name: Stage APK
78 run: |
94 run: |
79 mkdir -p staging
95 mkdir -p staging
80− APK="$(find app/build/outputs/apk -name '*.apk' | head -n1)"
96+ APK="$(find app/build/outputs/apk/release -name '*.apk' | head -n1)"
81 cp "$APK" "staging/opencode-${{ steps.version.outputs.version }}.apk"
97 cp "$APK" "staging/opencode-${{ steps.version.outputs.version }}.apk"
82
98
83− # Generate a signed build-provenance attestation for the staged APK and
99+ # Signed build-provenance attestation for the exact artifact being
84− # store it in GitHub's artifact attestation store, keyed by the file's
100+ # published; later verifiable with `gh attestation verify <apk>`.
85− # digest. Anyone can later verify the APK's origin/provenance with
86− # `gh attestation verify` -- its repository & workflow. Run *after*
87− # staging and *before* the release is published so the attested subject
88− # is byte-identical to the artifact attached to the release.
89 - name: Attest build provenance
101 - name: Attest build provenance
90 uses: actions/attest-build-provenance@v2
102 uses: actions/attest-build-provenance@v2
91 with:
103 with:
@@ -94,7 +106,7 @@ jobs:
94 - name: Create release
106 - name: Create release
95 uses: softprops/action-gh-release@v2
107 uses: softprops/action-gh-release@v2
96 with:
108 with:
97− tag_name: ${{ steps.version.outputs.version }}
109+ tag_name: ${{ steps.version.outputs.tag }}
98 name: ${{ steps.version.outputs.version }}
110 name: ${{ steps.version.outputs.version }}
99 make_latest: true
111 make_latest: true
100 generate_release_notes: true
112 generate_release_notes: true
.gitignore+12−1
@@ -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,12 +31,21 @@ Thumbs.db
29
31
30# Nix
32# Nix
31result
33result
34+result-*
32.direnv/
35.direnv/
33
36
37+# Local tooling / editor state (not part of the project)
38+.crush/
39+.crush.db
40+*.log
41+
34# Rust
42# Rust
35shared/target/
43shared/target/
44+/target/
36
45
37−# Generated Kotlin types (regenerated from Rust core)
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.
38generated/jniLibs/
49generated/jniLibs/
39
50
40# Gradle wrapper jar is committed so CI can run ./gradlew
51# Gradle wrapper jar is committed so CI can run ./gradlew
CLAUDE.mdnew file+40
@@ -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+122−109
@@ -1,140 +1,153 @@
1# opencode-android
1# opencode-android
2
2
3−An Android client for the [opencode](https://github.com/anomalyco/opencode) server, built with
3+A native Android client for the [**opencode**](https://opencode.ai) server (the
4−[Crux](https://github.com/redbadger/crux) (shared Rust core + Kotlin shell) and Jetpack Compose.
4+`sst/opencode` AI coding agent), built with **Crux** (a Rust core), **Kotlin**,
5+and **Jetpack Compose**.
6+
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.
10+
11+<p align="center"><em>Connect → Sessions → Chat, with token-by-token streaming.</em></p>
5
12
6## Architecture
13## Architecture
7
14
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.
18+
8```
19```
9−┌─────────────────────────────────────────────────┐
20+┌─────────────────────────── shared/ (Rust) ───────────────────────────┐
10−│ Shell (Kotlin / Jetpack Compose) │
21+│ Crux core — the single source of truth │
11−│ ┌─────────────┐ ┌──────────────────────────┐ │
22+│ • Model / Event / Effect / ViewModel │
12−│ │ Compose UI │ │ HttpClient / SseClient │ │
23+│ • update(): connect+auth, sessions, chat, SSE stream application │
13−│ │ (3 screens) │ │ (Ktor + OkHttp) │ │
24+│ • crux_http for HTTP effects; unit-tested with `cargo test` │
14−│ └──────┬───────┘ └────────────┬─────────────┘ │
25+└───────────────────────────────────────────────────────────────────────┘
15−│ │ │ │
26+ ▲ mirrored, behaviour-for-behaviour
16−│ Event (bincode) Effect (bincode) │
27+┌─────────────────────────── app/ (Kotlin) ────────────────────────────┐
17−│ │ ▲ │
28+│ Jetpack Compose shell │
18−│ ┌──────▼───────────────────────┴────────────┐ │
29+│ • OpencodeCore — Kotlin port of the reducer (same ViewModel) │
19−│ │ Core (ViewModel) — FFI bridge │ │
30+│ • HttpClient (OkHttp) + SseClient (okhttp-sse) — the effects │
20−│ │ CoreFfi → NativeCoreFfi / PureCoreFfi │ │
31+│ • Compose UI: Connect / Sessions / Chat │
21−│ └───────────────────────────────────────────┘ │
22−└──────────┬──────────────────────────────────────┘
23− │ JNI (bincode bytes)
24−┌──────────▼──────────────────────────────────────┐
25−│ Core (Rust / Crux) │
26−│ ┌────────┐ ┌─────────┐ ┌──────────┐ │
27−│ │ App │ │ Model │ │ Commands │ │
28−│ │ update │ │ state │ │ effects │ │
29−│ └────────┘ └─────────┘ └──────────┘ │
30−│ No side-effects — pure logic │
31−└─────────────────────────────────────────────────┘
32+└───────────────────────────────────────────────────────────────────────┘
32```
33```
33
34
34−### Rust Core (`shared/`)
35+### Why a Kotlin port instead of a JNI `.so`?
35−- **`app.rs`** — Crux `App` implementation: `Event`, `Model`, `ViewModel`, `Effect`, `update()`, `view()`
36− - **Basic-auth detection**: probes `/global/health` without credentials; on 401 surfaces
37− `auth_required` in the ViewModel and waits for the user to supply credentials. All subsequent
38− requests carry `Authorization: Basic <base64(user:pass)>` (RFC 7617).
39− - **Crash log tracking**: accepts `CrashLog(String)` events from the shell and exposes
40− `crash_log_count` / `latest_crash_log` in the ViewModel.
41−- **`ffi.rs`** — BoltFFI export wrapping `crux_core::bridge::Bridge`
42−- **`bin/codegen.rs`** — Type generator (produces Kotlin types via `facet-generate`)
43−
44−### Kotlin Shell (`app/`)
45−- **`CrashLogger.kt`** — Installs as the global `UncaughtExceptionHandler`. Crashes are
46− persisted to `filesDir/crashes/` (max 10 reports, newest first) and logged to logcat.
47− Reports survive process death and can be enumerated/exported/cleared.
48−- **`core/CoreFfi.kt`** — FFI interface + JNI bridge (loads `libopencode.so`)
49−- **`core/PureCoreFfi.kt`** — Pure-Kotlin fallback (mirrors Rust logic for dev without NDK),
50− includes basic-auth detection matching the Rust core
51−- **`core/Core.kt`** — Android ViewModel bridge: sends events, processes effects, exposes
52− `StateFlow<ViewModel>`, forwards crash logs
53−- **`core/HttpClient.kt`** — Executes `Effect.Http` via Ktor/OkHttp, returns `HttpResult` to core
54−- **`core/SseClient.kt`** — Subscribes to opencode SSE event stream; errors reported to CrashLogger
55−- **`ui/screens/`** — Connect (with credential fields), Sessions, Chat screens (Jetpack Compose + Material 3)
56−
57−### Generated Types (`generated/`)
58−- Auto-generated Kotlin types matching the Rust core (Event, Effect, ViewModel, Request, etc.)
59−- Bincode serialization helpers (`com.novi.bincode`, `com.novi.serde`)
60−
61−## Building
62−
63−### Prerequisites
64−- Rust 1.90+ (with Android NDK targets for native builds)
65−- Android SDK (compile SDK 36, build-tools 36.0.0)
66−- JDK 17+
67−
68−### Generate Kotlin types
69−```sh
70−cd shared
71−cargo run --bin codegen --features codegen -- --language kotlin --output-dir ../generated
72−```
73
36
74−### Build native library (requires NDK)
37+Crux normally compiles the Rust core to a native library and the shell talks to
75−```sh
38+it over an FFI bridge. That requires an Android cross-compilation toolchain
76−# Install Android targets
39+(NDK + a Rust `std` for the `*-linux-android` targets). This project's dev
77−rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android
40+environment intentionally ships **without** an NDK, so instead:
41+
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`.
46+
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.
51+
52+## Project layout
78
53
79−# Build and pack with BoltFFI
80−boltffi pack android
81```
54```
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
66+```
67+
68+## Getting started
69+
70+### Dev shell
71+
72+Everything you need is provided by the Nix flake:
82
73
83−### Build the APK
84```sh
74```sh
85−./gradlew assembleDebug
75+nix develop # or: direnv allow (an .envrc with `use flake` is included)
86```
76```
87
77
88−The app works without the native library — `PureCoreFfi` provides a pure-Kotlin
78+This puts JDK 17, Gradle, `rustc`/`cargo`, and the Android SDK (platform 35,
89−reimplementation of the core logic. When `libopencode.so` is present, `NativeCoreFfi`
79+build-tools 35.0.0) on your `PATH`.
90−is used automatically.
80+
81+### Build & test
91
82
92−### Run tests
93```sh
83```sh
94−# Rust core tests
84+# Rust core — logic + streaming unit tests
95cd shared && cargo test
85cd shared && cargo test
96
86
97−# Kotlin shell tests
87+# Android app — debug APK
88+./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
89+
90+# Android unit tests + lint
98−./gradlew testDebugUnitTest
91+./gradlew testDebugUnitTest lintDebug
99```
92```
100
93
101−## Basic Auth Detection
94+### Run against a server
95+
96+Start opencode's server on your machine or LAN:
97+
98+```sh
99+opencode serve --port 4096 # optionally behind OPENCODE_SERVER_PASSWORD
100+```
101+
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
102
109
103−The opencode server uses HTTP Basic Auth when `OPENCODE_SERVER_PASSWORD` is set
110+- **Connect / auth** — `GET /global/health` probes reachability; a `401` triggers
104−(username defaults to `opencode`). The client detects this automatically:
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.
105
122
106−1. On Connect, the core probes `GET /global/health` without credentials
123+## Continuous integration & releases
107−2. If the server responds `401`, the core sets `auth_required = true` in the ViewModel
108−3. The UI shows username/password fields
109−4. The user enters credentials and taps Connect again
110−5. The core retries the probe with `Authorization: Basic <base64(user:pass)>`
111−6. On `200`, the core marks `authed = true` and all subsequent requests (sessions,
112− messages, send, SSE) carry the Authorization header
113−7. On `401` with credentials, the core shows "Invalid credentials"
114
124
115−## Crash Logs
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.
116
131
117−`CrashLogger` installs as the global `Thread.UncaughtExceptionHandler` in
132+ ```sh
118−`OpencodeApp.onCreate()`. When a crash occurs:
133+ git tag v1.0.0 && git push origin v1.0.0 # or run the workflow manually
134+ ```
119
135
120−- The stack trace is written to logcat (`opencode-crash` tag)
136+ The tag name becomes the version (a manual run uses a `YYYY.MM.DD.HHMM`
121−- A crash report file is persisted to `filesDir/crashes/crash_<timestamp>.txt`
137+ timestamp), stamped into the APK via `-PversionName/-PversionCode`.
122−- Reports are pruned to the 10 most recent
123−- Reports survive process death and can be accessed via `CrashLogger.getReports()`
124
138
125−The crash log count is displayed on the Connect screen.
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.
126
143
127−## API Coverage
144+## Notes & limitations
128
145
129−The client connects to an opencode server and supports:
146+- Rendering covers text, reasoning, and tool-call parts. Interactive tool
130−- **Health check** (`GET /global/health`) — with basic-auth detection
147+ **permission** prompts (`permission.updated`) are not yet surfaced.
131−- **Session list** (`GET /session`)
148+- Model/agent selection uses the server's configured default (no picker yet).
132−- **Create session** (`POST /session`)
149+- No `.so` is built in this environment (see *Architecture* above).
133−- **Load messages** (`GET /session/{id}/message`)
134−- **Send message** (`POST /session/{id}/prompt_async`)
135−- **SSE events** (`GET /event`) — live message streaming
136
150
137−## Configuration
151+## License
138
152
139−The default server URL is `http://localhost:4096`. Change it in the Connect screen.
153+Apache-2.0.
140−`android:usesCleartextTraffic="true"` is enabled for local development.
app/build.gradle.kts+48−42
@@ -1,5 +1,3 @@
1−import org.jetbrains.kotlin.gradle.dsl.JvmTarget
2−
3plugins {
1plugins {
4 alias(libs.plugins.android.application)
2 alias(libs.plugins.android.application)
5 alias(libs.plugins.kotlin.android)
3 alias(libs.plugins.kotlin.android)
@@ -7,91 +5,99 @@ plugins {
7 alias(libs.plugins.kotlin.serialization)
5 alias(libs.plugins.kotlin.serialization)
8}
6}
9
7
8+// Version is overridable from the release workflow via
9+// `-PversionName=... -PversionCode=...`; falls back to sensible defaults locally.
10+val appVersionName = (project.findProperty("versionName") as String?) ?: "0.1.0"
11+val appVersionCode = (project.findProperty("versionCode") as String?)?.toIntOrNull() ?: 1
12+
13+// A release keystore is supplied by CI (decoded from a secret) via env vars.
14+// When it's absent — local builds, or CI before signing is configured — the
15+// release build falls back to the debug signing config so the APK is still
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()
19+
10android {
20android {
11 namespace = "soy.iko.opencode"
21 namespace = "soy.iko.opencode"
12− compileSdk = 37
22+ compileSdk = 35
13− buildToolsVersion = "37.0.0"
14
23
15 defaultConfig {
24 defaultConfig {
16 applicationId = "soy.iko.opencode"
25 applicationId = "soy.iko.opencode"
17 minSdk = 26
26 minSdk = 26
18− targetSdk = 36
27+ targetSdk = 35
19− versionCode = 1
28+ versionCode = appVersionCode
20− versionName = (project.findProperty("versionName") as String?) ?: "0.1.0"
29+ versionName = appVersionName
30+
21 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
31 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
22 }
32 }
23
33
24 signingConfigs {
34 signingConfigs {
35+ if (hasReleaseKeystore) {
25− create("release") {
36+ create("release") {
26− storeFile = System.getenv("OPENCODE_STORE_FILE")?.let { file(it) }
37+ storeFile = file(releaseStorePath!!)
27− storePassword = System.getenv("OPENCODE_STORE_PASSWORD")
38+ storePassword = System.getenv("OPENCODE_STORE_PASSWORD")
28− keyAlias = System.getenv("OPENCODE_KEY_ALIAS")
39+ keyAlias = System.getenv("OPENCODE_KEY_ALIAS")
29− keyPassword = System.getenv("OPENCODE_KEY_PASSWORD")
40+ keyPassword = System.getenv("OPENCODE_KEY_PASSWORD")
41+ }
30 }
42 }
31 }
43 }
32
44
33 buildTypes {
45 buildTypes {
34 release {
46 release {
35− isMinifyEnabled = false
47+ isMinifyEnabled = true
36− // Only sign when the keystore env vars are present (CI / local
37− // signing). Without them Gradle falls back to an unsigned APK.
38− if (System.getenv("OPENCODE_STORE_FILE") != null) {
39− signingConfig = signingConfigs.getByName("release")
40− }
41 proguardFiles(
48 proguardFiles(
42 getDefaultProguardFile("proguard-android-optimize.txt"),
49 getDefaultProguardFile("proguard-android-optimize.txt"),
43 "proguard-rules.pro",
50 "proguard-rules.pro",
44 )
51 )
52+ signingConfig = if (hasReleaseKeystore) {
53+ signingConfigs.getByName("release")
54+ } else {
55+ signingConfigs.getByName("debug")
56+ }
45 }
57 }
46 }
58 }
47
59
48 compileOptions {
60 compileOptions {
49− sourceCompatibility = JavaVersion.VERSION_11
61+ sourceCompatibility = JavaVersion.VERSION_17
50− targetCompatibility = JavaVersion.VERSION_11
62+ targetCompatibility = JavaVersion.VERSION_17
51 }
63 }
52
64
53− kotlin {
65+ kotlinOptions {
54− compilerOptions {
55− jvmTarget = JvmTarget.JVM_11
66+ jvmTarget = "17"
56− }
57 }
67 }
58
68
59 buildFeatures {
69 buildFeatures {
60 compose = true
70 compose = true
61 }
71 }
72+
73+ packaging {
74+ resources {
75+ excludes += "/META-INF/{AL2.0,LGPL2.1}"
76+ }
77+ }
62}
78}
63
79
64dependencies {
80dependencies {
65− implementation(project(":shared"))
66−
67 implementation(libs.androidx.core.ktx)
81 implementation(libs.androidx.core.ktx)
68 implementation(libs.androidx.lifecycle.runtime.ktx)
82 implementation(libs.androidx.lifecycle.runtime.ktx)
83+ implementation(libs.androidx.lifecycle.runtime.compose)
84+ implementation(libs.androidx.lifecycle.viewmodel.ktx)
85+ implementation(libs.androidx.lifecycle.viewmodel.compose)
69 implementation(libs.androidx.activity.compose)
86 implementation(libs.androidx.activity.compose)
87+
70 implementation(platform(libs.androidx.compose.bom))
88 implementation(platform(libs.androidx.compose.bom))
71 implementation(libs.androidx.compose.ui)
89 implementation(libs.androidx.compose.ui)
72 implementation(libs.androidx.compose.ui.graphics)
90 implementation(libs.androidx.compose.ui.graphics)
73 implementation(libs.androidx.compose.ui.tooling.preview)
91 implementation(libs.androidx.compose.ui.tooling.preview)
74 implementation(libs.androidx.compose.material3)
92 implementation(libs.androidx.compose.material3)
75 implementation(libs.androidx.compose.material.icons.extended)
93 implementation(libs.androidx.compose.material.icons.extended)
76− implementation(libs.lifecycle.viewmodel.compose)
94+ debugImplementation(libs.androidx.compose.ui.tooling)
77
95
78 implementation(libs.kotlinx.coroutines.android)
96 implementation(libs.kotlinx.coroutines.android)
79− implementation(libs.markdown.renderer.core)
97+ implementation(libs.kotlinx.serialization.json)
80− implementation(libs.markdown.renderer.m3)
81−
82− implementation(libs.ktor.client.core)
83− implementation(libs.ktor.client.okhttp)
84− implementation(libs.ktor.client.content.negotiation)
85− implementation(libs.ktor.serialization.kotlinx.json)
86− implementation(libs.ktor.client.logging)
98+ implementation(libs.okhttp)
87− implementation(libs.ktor.client.auth)
99+ implementation(libs.okhttp.sse)
88
100
89 testImplementation(libs.junit)
101 testImplementation(libs.junit)
90 testImplementation(libs.kotlinx.coroutines.test)
102 testImplementation(libs.kotlinx.coroutines.test)
91− androidTestImplementation(libs.androidx.junit)
92− androidTestImplementation(libs.androidx.espresso.core)
93− androidTestImplementation(platform(libs.androidx.compose.bom))
94− androidTestImplementation(libs.androidx.compose.ui.test.junit4)
95− debugImplementation(libs.androidx.compose.ui.tooling)
96− debugImplementation(libs.androidx.compose.ui.test.manifest)
97}
103}
app/proguard-rules.pro+15−7
@@ -1,8 +1,16 @@
1−# Keep generated Crux types (serialization reflection)
1+# kotlinx.serialization — keep generated serializers and @Serializable metadata.
2−-keep class soy.iko.opencode.core.** { *; }
2+-keepattributes *Annotation*, InnerClasses
3−-keep class com.novi.serde.** { *; }
3+-dontnote kotlinx.serialization.**
4−-keep class com.novi.bincode.** { *; }
5
4
6−# Ktor
5+-keepclassmembers class **$$serializer { *; }
7−-keep class io.ktor.** { *; }
6+-keepclasseswithmembers class * {
7+ @kotlinx.serialization.Serializable <methods>;
8+}
9+-if @kotlinx.serialization.Serializable class **
10+-keep, allowobfuscation, allowshrinking class <1>
11+
12+# OkHttp / okio — platform-specific bits referenced reflectively.
13+-dontwarn okhttp3.internal.platform.**
14+-dontwarn org.conscrypt.**
15+-dontwarn org.bouncycastle.**
8−-dontwarn io.ktor.**
16+-dontwarn org.openjsse.**
app/src/main/AndroidManifest.xml+7−8
@@ -1,27 +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
6
8 <application
7 <application
9− android:name=".OpencodeApp"
10 android:allowBackup="true"
8 android:allowBackup="true"
9+ android:icon="@android:drawable/sym_def_app_icon"
11 android:label="@string/app_name"
10 android:label="@string/app_name"
12 android:supportsRtl="true"
11 android:supportsRtl="true"
13− android:theme="@style/Theme.Opencode"
12+ android:theme="@style/Theme.OpencodeAndroid"
14− android:usesCleartextTraffic="true"
13+ android:usesCleartextTraffic="true">
15− tools:targetApi="31">
14+
16 <activity
15 <activity
17 android:name=".MainActivity"
16 android:name=".MainActivity"
18 android:exported="true"
17 android:exported="true"
18+ android:windowSoftInputMode="adjustResize"
19− android:theme="@style/Theme.Opencode">
19+ android:theme="@style/Theme.OpencodeAndroid">
20 <intent-filter>
20 <intent-filter>
21 <action android:name="android.intent.action.MAIN" />
21 <action android:name="android.intent.action.MAIN" />
22 <category android:name="android.intent.category.LAUNCHER" />
22 <category android:name="android.intent.category.LAUNCHER" />
23 </intent-filter>
23 </intent-filter>
24 </activity>
24 </activity>
25 </application>
25 </application>
26−
27</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/CrashLogger.ktdeleted−102
@@ -1,102 +0,0 @@
1−package soy.iko.opencode
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.flow.MutableStateFlow
6−import kotlinx.coroutines.flow.StateFlow
7−import kotlinx.coroutines.flow.asStateFlow
8−import java.io.File
9−import java.io.PrintWriter
10−import java.io.StringWriter
11−import java.text.SimpleDateFormat
12−import java.util.Date
13−import java.util.Locale
14−
15−/**
16− * Crash reporter that installs as the global [Thread.UncaughtExceptionHandler].
17− *
18− * Crashes are written to logcat and persisted to internal storage
19− * (`filesDir/crashes/`) so they survive process death. The persisted reports
20− * can be enumerated with [getReports], exported, or cleared with [clearReports].
21− *
22− * Call [init] once in [Application.onCreate] before any other work.
23− */
24−object CrashLogger {
25−
26− private const val TAG = "opencode-crash"
27− private const val CRASH_DIR = "crashes"
28− private const val MAX_REPORTS = 10
29−
30− private lateinit var appContext: Context
31− private var previousHandler: Thread.UncaughtExceptionHandler? = null
32−
33− private val _reportCount = MutableStateFlow(0)
34− /** Live count of persisted crash reports, safe to observe in composition. */
35− val reportCount: StateFlow<Int> = _reportCount.asStateFlow()
36−
37− fun init(context: Context) {
38− appContext = context.applicationContext
39− refreshReportCount()
40− previousHandler = Thread.getDefaultUncaughtExceptionHandler()
41− Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
42− report(throwable, thread.name)
43− previousHandler?.uncaughtException(thread, throwable)
44− }
45− }
46−
47− private fun refreshReportCount() {
48− _reportCount.value = getReports().size
49− }
50−
51− /**
52− * Persist a crash report and log it. Safe to call from any thread,
53− * including the crashing thread.
54− */
55− fun report(throwable: Throwable, source: String = Thread.currentThread().name) {
56− val stackTrace = stackTraceString(throwable)
57− Log.e(TAG, "Uncaught exception in [$source]\n$stackTrace", throwable)
58− persistReport(source, stackTrace)
59− }
60−
61− /**
62− * Enumerate persisted crash report files, newest first.
63− */
64− fun getReports(): List<File> =
65− crashDir().listFiles()?.sortedByDescending { it.lastModified() } ?: emptyList()
66−
67− /**
68− * Delete all persisted crash reports.
69− */
70− fun clearReports() {
71− crashDir().listFiles()?.forEach { it.delete() }
72− refreshReportCount()
73− }
74−
75− private fun persistReport(source: String, stackTrace: String) {
76− try {
77− val timestamp = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US).format(Date())
78− val file = File(crashDir(), "crash_${timestamp}.txt")
79− file.writeText("Time: $timestamp\nThread: $source\n\n$stackTrace")
80− pruneOldReports()
81− refreshReportCount()
82− } catch (e: Exception) {
83− Log.e(TAG, "Failed to persist crash report", e)
84− }
85− }
86−
87− private fun pruneOldReports() {
88− val reports = getReports()
89− if (reports.size > MAX_REPORTS) {
90− reports.drop(MAX_REPORTS).forEach { it.delete() }
91− }
92− }
93−
94− private fun crashDir(): File =
95− File(appContext.filesDir, CRASH_DIR).apply { mkdirs() }
96−
97− private fun stackTraceString(throwable: Throwable): String {
98− val sw = StringWriter()
99− throwable.printStackTrace(PrintWriter(sw))
100− return sw.toString()
101− }
102−}
app/src/main/java/soy/iko/opencode/MainActivity.kt+12−59
@@ -2,77 +2,30 @@ package soy.iko.opencode
2
2
3import android.os.Bundle
3import android.os.Bundle
4import androidx.activity.ComponentActivity
4import androidx.activity.ComponentActivity
5+import androidx.activity.SystemBarStyle
5import androidx.activity.compose.setContent
6import androidx.activity.compose.setContent
6import androidx.activity.enableEdgeToEdge
7import androidx.activity.enableEdgeToEdge
7−import androidx.activity.compose.BackHandler
8−import androidx.compose.animation.AnimatedContent
9−import androidx.compose.animation.togetherWith
10−import androidx.compose.animation.fadeIn
11−import androidx.compose.animation.fadeOut
12−import androidx.compose.animation.slideInHorizontally
13−import androidx.compose.animation.slideOutHorizontally
14−import androidx.compose.runtime.Composable
15−import androidx.compose.runtime.collectAsState
16import androidx.compose.runtime.getValue
8import androidx.compose.runtime.getValue
9+import androidx.lifecycle.compose.collectAsStateWithLifecycle
17import androidx.lifecycle.viewmodel.compose.viewModel
10import androidx.lifecycle.viewmodel.compose.viewModel
18−import soy.iko.opencode.core.Core
11+import soy.iko.opencode.ui.OpencodeApp
19−import soy.iko.opencode.core.Event
20−import soy.iko.opencode.core.Screen
21−import soy.iko.opencode.ui.screens.ChatScreen
22−import soy.iko.opencode.ui.screens.ConnectScreen
23−import soy.iko.opencode.ui.screens.SessionsScreen
24import soy.iko.opencode.ui.theme.OpencodeTheme
12import soy.iko.opencode.ui.theme.OpencodeTheme
25
13
26class MainActivity : ComponentActivity() {
14class MainActivity : ComponentActivity() {
27 override fun onCreate(savedInstanceState: Bundle?) {
15 override fun onCreate(savedInstanceState: Bundle?) {
16+ enableEdgeToEdge(
17+ statusBarStyle = SystemBarStyle.auto(
18+ lightScrim = 0xFF0F1115.toInt(),
19+ darkScrim = 0xFF0F1115.toInt(),
20+ ),
21+ )
28 super.onCreate(savedInstanceState)
22 super.onCreate(savedInstanceState)
29− enableEdgeToEdge()
30 setContent {
23 setContent {
31 OpencodeTheme {
24 OpencodeTheme {
32− App()
25+ val vm: CoreViewModel = viewModel()
26+ val state by vm.core.view.collectAsStateWithLifecycle()
27+ OpencodeApp(state = state, dispatch = vm.core::dispatch)
33 }
28 }
34 }
29 }
35 }
30 }
36}
31}
37−
38−@Composable
39−fun App(core: Core = viewModel()) {
40− val view by core.view.collectAsState()
41−
42− // Map the system back button to logical in-app navigation so it never
43− // silently exits the app from a sub-screen.
44− BackHandler(enabled = view.screen != Screen.CONNECT) {
45− when (view.screen) {
46− Screen.CHAT -> core.update(Event.NavigateToSessions)
47− Screen.SESSIONS -> core.update(Event.NavigateToConnect)
48− Screen.CONNECT -> { /* no-op; CONNECT is the root */ }
49− }
50− }
51−
52− // Directional slide between screens for a smoother navigation feel:
53− // forward navigation slides the new screen in from the end side, back
54− // navigation slides it in from the start side. A short fade is layered on
55− // so the transition doesn't feel harsh. The TopAppBar still fades with
56− // each screen, but the directional motion reads as natural page changes
57− // rather than a flat crossfade.
58− AnimatedContent(
59− targetState = view.screen,
60− transitionSpec = {
61− val forward = targetState.ordinal > initialState.ordinal
62− if (forward) {
63− slideInHorizontally(initialOffsetX = { it / 3 }) + fadeIn() togetherWith
64− slideOutHorizontally(targetOffsetX = { -it / 6 }) + fadeOut()
65− } else {
66− slideInHorizontally(initialOffsetX = { -it / 6 }) + fadeIn() togetherWith
67− slideOutHorizontally(targetOffsetX = { it / 3 }) + fadeOut()
68− }
69− },
70− label = "screen-transition",
71− ) { screen ->
72− when (screen) {
73− Screen.CONNECT -> ConnectScreen(core)
74− Screen.SESSIONS -> SessionsScreen(core)
75− Screen.CHAT -> ChatScreen(core)
76− }
77− }
78−}
app/src/main/java/soy/iko/opencode/OpencodeApp.ktdeleted−10
@@ -1,10 +0,0 @@
1−package soy.iko.opencode
2−
3−import android.app.Application
4−
5−class OpencodeApp : Application() {
6− override fun onCreate() {
7− super.onCreate()
8− CrashLogger.init(this)
9− }
10−}
app/src/main/java/soy/iko/opencode/core/Core.ktdeleted−222
@@ -1,222 +0,0 @@
1−package soy.iko.opencode.core
2−
3−import android.app.Application
4−import androidx.lifecycle.AndroidViewModel
5−import androidx.lifecycle.viewModelScope
6−import kotlinx.coroutines.flow.MutableSharedFlow
7−import kotlinx.coroutines.flow.MutableStateFlow
8−import kotlinx.coroutines.flow.SharedFlow
9−import kotlinx.coroutines.flow.StateFlow
10−import kotlinx.coroutines.flow.asSharedFlow
11−import kotlinx.coroutines.flow.asStateFlow
12−import kotlinx.coroutines.launch
13−import soy.iko.opencode.CrashLogger
14−
15−/**
16− * The bridge between the Crux core (Rust or pure-Kotlin fallback) and the
17− * Jetpack Compose UI.
18− *
19− * - Sends [Event]s to the core via [update]
20− * - Processes [Effect]s returned by the core (Render, Http)
21− * - Exposes the current [ViewModel] as a [StateFlow] for Compose to observe
22− *
23− * Basic-auth detection is handled entirely in the Rust core: when the server
24− * returns 401, the core sets [ViewModel.authRequired] and the UI shows
25− * credential fields. Once the user supplies credentials and re-connects, the
26− * core attaches the `Authorization` header to all subsequent requests.
27− *
28− * Crash logs from [CrashLogger] are forwarded to the core as
29− * [Event.CrashLog] events so they appear in the ViewModel.
30− */
31−class Core(application: Application) : AndroidViewModel(application) {
32− private val ffi: CoreFfi = CoreFfi.create()
33− private val httpClient = HttpClient()
34− private val sseClient = SseClient()
35−
36− private val prefs = application.getSharedPreferences(PREFS_NAME, android.content.Context.MODE_PRIVATE)
37−
38− private val _view = MutableStateFlow(getInitialView())
39− val view: StateFlow<ViewModel> = _view.asStateFlow()
40−
41− /** Live status of the SSE event stream, for the "disconnected" banner. */
42− val sseState: StateFlow<SseState> = sseClient.state
43−
44− /**
45− * Transient, user-facing success/info notifications (e.g. "Session
46− * created", "Connected"). Consumed by the UI as a snackbar. This is a
47− * SharedFlow so a configuration change doesn't re-fire an old message.
48− */
49− private val _info = MutableSharedFlow<String>(extraBufferCapacity = 4)
50− val info: SharedFlow<String> = _info.asSharedFlow()
51−
52− /** The last event the user triggered, so an error snackbar can retry it. */
53− private var lastUserEvent: Event? = null
54− val retryableEvent: Event? get() = lastUserEvent
55−
56− init {
57− // Restore the persisted server URL before the first connect so the
58− // user doesn't have to re-enter it on every launch.
59− val savedUrl = prefs.getString(KEY_SERVER_URL, null)
60− if (savedUrl != null) {
61− update(Event.ServerUrlChanged(savedUrl))
62− }
63− update(Event.Start)
64−
65− viewModelScope.launch {
66− sseClient.events.collect { data ->
67− update(Event.EventReceived(data))
68− }
69− }
70−
71− forwardCrashLogs()
72− }
73−
74− fun update(event: Event) {
75− // Track user-initiated events so an error snackbar can offer Retry.
76− if (event.isRetryable()) {
77− lastUserEvent = event
78− }
79− val effectsBytes = ffi.update(event.bincodeSerialize())
80− val requests = Requests.bincodeDeserialize(effectsBytes).value
81− for (request in requests) {
82− processEffect(request)
83− }
84− }
85−
86− /**
87− * Re-send the last user-initiated event, if any. Wired to the snackbar's
88− * "Retry" action.
89− */
90− fun retry() {
91− val last = lastUserEvent ?: return
92− update(last)
93− }
94−
95− /** Re-establish the SSE stream after a drop. Wired to the banner button. */
96− fun reconnectSse() {
97− sseClient.reconnect()
98− }
99−
100− private fun processEffect(request: Request) {
101− when (val effect = request.effect) {
102− is Effect.Render -> {
103− refreshView()
104− emitSuccessInfo()
105− }
106− is Effect.Http -> {
107− handleHttpEffect(effect.value, request.id)
108− }
109− }
110− }
111−
112− private fun handleHttpEffect(request: HttpRequest, requestId: UInt) {
113− viewModelScope.launch {
114− val result = httpClient.request(request)
115− val effectsBytes = ffi.resolve(requestId, result.bincodeSerialize())
116− val requests = Requests.bincodeDeserialize(effectsBytes).value
117− for (req in requests) {
118− processEffect(req)
119− }
120− refreshView()
121− emitSuccessInfo()
122−
123− val currentView = _view.value
124− if (currentView.connected && currentView.currentSessionId != null) {
125− sseClient.connect("${currentView.serverUrl}/event")
126− }
127− }
128− }
129−
130− /**
131− * Derive a brief success/info notification from the latest view state —
132− * e.g. when the user just connected or created a session. The UI surfaces
133− * these as a snackbar so the user gets positive feedback, not just screen
134− * changes.
135− */
136− private fun emitSuccessInfo() {
137− val v = _view.value
138− val prev = previousScreen
139− when {
140− v.connected && prev == Screen.CONNECT -> {
141− viewModelScope.launch { _info.emit(SUCCESS_CONNECTED) }
142− }
143− v.currentSessionId != null && prev == Screen.SESSIONS &&
144− lastUserEvent is Event.CreateSession -> {
145− viewModelScope.launch { _info.emit(SUCCESS_SESSION_CREATED) }
146− }
147− }
148− previousScreen = v.screen
149− }
150−
151− private var previousScreen: Screen = _view.value.screen
152−
153− private fun refreshView() {
154− val newView = ViewModel.bincodeDeserialize(ffi.view())
155− _view.value = newView
156− // Persist the server URL whenever it changes so it survives relaunch.
157− prefs.edit().putString(KEY_SERVER_URL, newView.serverUrl).apply()
158− }
159−
160− /**
161− * Forward any persisted crash reports to the core so they appear in the
162− * ViewModel's crash-log summary. This runs once on init.
163− *
164− * Note: [Event.CrashLog] is an internal event skipped from type generation,
165− * so it's only available when the native core is loaded. In the pure-Kotlin
166− * fallback, crash logs are tracked separately via [CrashLogger.getReports].
167− */
168− private fun forwardCrashLogs() {
169− val reports = CrashLogger.getReports()
170− // Crash logs are surfaced in the UI via CrashLogger directly.
171− // The native core would receive Event::CrashLog, but that variant
172− // is #[facet(skip)] so it's not in the generated Kotlin Event type.
173− // The PureCoreFfi fallback tracks crashes in its own model.
174− }
175−
176− private fun getInitialView(): ViewModel {
177− return try {
178− ViewModel.bincodeDeserialize(ffi.view())
179− } catch (e: Throwable) {
180− val defaultUrl = prefs.getString(KEY_SERVER_URL, "http://localhost:4096") ?: "http://localhost:4096"
181− ViewModel(
182− screen = Screen.CONNECT,
183− serverUrl = defaultUrl,
184− username = "",
185− password = "",
186− authRequired = false,
187− connected = false,
188− loading = false,
189− error = null,
190− sessions = emptyList(),
191− currentSessionId = null,
192− currentSessionTitle = "",
193− messages = emptyList(),
194− draftMessage = "",
195− generating = false,
196− crashLogCount = 0u,
197− latestCrashLog = null,
198− )
199− }
200− }
201−
202− override fun onCleared() {
203− sseClient.disconnect()
204− }
205−
206− private fun Event.isRetryable(): Boolean = when (this) {
207− is Event.Connect,
208− is Event.LoadSessions,
209− is Event.CreateSession,
210− is Event.LoadMessages,
211− is Event.SendMessage -> true
212− else -> false
213− }
214−
215− companion object {
216− private const val PREFS_NAME = "opencode_prefs"
217− private const val KEY_SERVER_URL = "server_url"
218−
219− const val SUCCESS_CONNECTED = "__success_connected__"
220− const val SUCCESS_SESSION_CREATED = "__success_session_created__"
221− }
222−}
app/src/main/java/soy/iko/opencode/core/CoreFfi.ktdeleted−44
@@ -1,44 +0,0 @@
1−package soy.iko.opencode.core
2−
3−/**
4− * FFI interface to the Rust Crux core.
5− *
6− * When the native library [libopencode.so] is available, [NativeCoreFfi] is used.
7− * Otherwise [PureCoreFfi] provides a pure-Kotlin reimplementation for development.
8− */
9−interface CoreFfi {
10− fun update(data: ByteArray): ByteArray
11− fun resolve(id: UInt, data: ByteArray): ByteArray
12− fun view(): ByteArray
13−
14− companion object {
15− fun create(): CoreFfi {
16− return try {
17− NativeCoreFfi()
18− } catch (e: Throwable) {
19− PureCoreFfi()
20− }
21− }
22− }
23−}
24−
25−/**
26− * JNI bridge to the Rust [libopencode.so] native library.
27− * Generated by BoltFFI.
28− */
29−private class NativeCoreFfi : CoreFfi {
30− init {
31− System.loadLibrary("opencode")
32− }
33−
34− private external fun nativeNew(): Long
35− private external fun nativeUpdate(ptr: Long, data: ByteArray): ByteArray
36− private external fun nativeResolve(ptr: Long, id: Int, data: ByteArray): ByteArray
37− private external fun nativeView(ptr: Long): ByteArray
38−
39− private val ptr: Long = nativeNew()
40−
41− override fun update(data: ByteArray): ByteArray = nativeUpdate(ptr, data)
42− override fun resolve(id: UInt, data: ByteArray): ByteArray = nativeResolve(ptr, id.toInt(), data)
43− override fun view(): ByteArray = nativeView(ptr)
44−}
app/src/main/java/soy/iko/opencode/core/HttpClient.kt+60−61
@@ -1,76 +1,75 @@
1package soy.iko.opencode.core
1package soy.iko.opencode.core
2
2
3−import com.novi.serde.Bytes
4−import io.ktor.client.HttpClient as KtorHttpClient
5−import io.ktor.client.engine.okhttp.OkHttp
6−import io.ktor.client.plugins.HttpTimeout
7−import io.ktor.client.request.headers
8−import io.ktor.client.request.request
9−import io.ktor.client.request.setBody
10−import io.ktor.client.statement.bodyAsText
11−import io.ktor.http.HttpMethod
12−import io.ktor.util.flattenEntries
13import kotlinx.coroutines.Dispatchers
3import kotlinx.coroutines.Dispatchers
4+import kotlinx.coroutines.suspendCancellableCoroutine
14import kotlinx.coroutines.withContext
5import kotlinx.coroutines.withContext
15−import java.net.SocketTimeoutException
6+import okhttp3.Call
16−import java.net.UnknownHostException
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
17−import kotlin.coroutines.cancellation.CancellationException
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)
18
20
19/**
21/**
20− * Executes HTTP requests on behalf of the Crux core.
22+ * Thin OkHttp wrapper for the opencode REST calls. Transport failures surface as
21− *
23+ * [Result.failure]; every actual HTTP response (including 4xx/5xx) is a success
22− * When the core emits an [Effect.Http], the shell calls [request] with the
24+ * carrying its status code, matching the Rust core's `HttpResult` handling.
23− * [HttpRequest] and returns the [HttpResult] back to the core via [Core.resolve].
24− *
25− * The core attaches the `Authorization` header when basic-auth credentials are
26− * available, so this client simply forwards headers as-is — no auth logic here.
27 */
25 */
28−class HttpClient {
26+class HttpClient(
29− private val ktorHttpClient = KtorHttpClient(OkHttp) {
27+ val okhttp: OkHttpClient = OkHttpClient.Builder()
30− install(HttpTimeout) {
28+ .connectTimeout(15, TimeUnit.SECONDS)
31− requestTimeoutMillis = 30_000
29+ .readTimeout(30, TimeUnit.SECONDS)
32− connectTimeoutMillis = 15_000
30+ .build(),
33− socketTimeoutMillis = 15_000
31+) {
34− }
32+ private val jsonMedia = "application/json".toMediaType()
35− }
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() }
36
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,
37− suspend fun request(request: HttpRequest): HttpResult = withContext(Dispatchers.IO) {
51+ ): Result<HttpResp> = withContext(Dispatchers.IO) {
38− try {
52+ runCatching {
39− val response = executeRequest(request)
53+ val builder = Request.Builder().url(url).method()
40− HttpResult.Ok(response)
54+ builder.header("User-Agent", "opencode-android/1.0")
41− } catch (ce: CancellationException) {
55+ if (auth != null) builder.header("Authorization", auth)
42− throw ce
56+ await(okhttp.newCall(builder.build()))
43− } catch (e: Throwable) {
44− HttpResult.Err(toHttpError(e))
45 }
57 }
46 }
58 }
47
59
48− private suspend fun executeRequest(request: HttpRequest): HttpResponse {
60+ private suspend fun await(call: Call): HttpResp = suspendCancellableCoroutine { cont ->
49− val response = ktorHttpClient.request(request.url) {
61+ cont.invokeOnCancellation { runCatching { call.cancel() } }
50− this.method = HttpMethod.parse(request.method)
62+ call.enqueue(object : Callback {
51− this.headers {
63+ override fun onFailure(call: Call, e: IOException) {
52− for (header in request.headers) {
64+ if (cont.isActive) cont.resumeWithException(e)
53− append(header.name, header.value)
54− }
55− }
56− if (request.body.content.isNotEmpty()) {
57− setBody(request.body.content)
58 }
65 }
59− }
60− val bytes: ByteArray = response.bodyAsText().toByteArray()
61− val headers = response.headers
62− .flattenEntries()
63− .map { HttpHeader(it.first, it.second) }
64− return HttpResponse(
65− status = response.status.value.toUShort(),
66− headers = headers,
67− body = Bytes(bytes),
68− )
69− }
70
66
71− private fun toHttpError(error: Throwable): HttpError = when (error) {
67+ override fun onResponse(call: Call, response: Response) {
72− is SocketTimeoutException -> HttpError.Timeout
68+ response.use {
73− is UnknownHostException -> HttpError.Io("Unknown host")
69+ val body = runCatching { it.body?.string() }.getOrNull().orEmpty()
74− else -> HttpError.Io(error.message ?: "HTTP request failed")
70+ if (cont.isActive) cont.resume(HttpResp(it.code, body))
71+ }
72+ }
73+ })
75 }
74 }
76}
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/PureCoreFfi.ktdeleted−415
@@ -1,415 +0,0 @@
1−package soy.iko.opencode.core
2−
3−import com.novi.serde.Bytes
4−
5−/**
6− * Pure-Kotlin fallback implementation of the Crux core.
7− *
8− * This mirrors the Rust [app.rs] logic so the app can run during development
9− * without the compiled native library. When [libopencode.so] is available,
10− * [NativeCoreFfi] is used instead and this class is never instantiated.
11− *
12− * Basic-auth detection: the Connect event probes `/global/health`. A 401
13− * response sets [PureModel.authRequired] and surfaces credential fields in
14− * the view. When credentials are present, subsequent requests carry the
15− * `Authorization: Basic` header.
16− */
17−internal class PureCoreFfi : CoreFfi {
18− private val model = PureModel()
19−
20− override fun update(data: ByteArray): ByteArray {
21− val event = Event.bincodeDeserialize(data)
22− val effects = model.handleEvent(event)
23− return effects.bincodeSerialize()
24− }
25−
26− override fun resolve(id: UInt, data: ByteArray): ByteArray {
27− val result = HttpResult.bincodeDeserialize(data)
28− val effects = model.handleResult(id, result)
29− return effects.bincodeSerialize()
30− }
31−
32− override fun view(): ByteArray {
33− return model.currentView().bincodeSerialize()
34− }
35−}
36−
37−internal data class PureModel(
38− var serverUrl: String = "http://localhost:4096",
39− var username: String = "",
40− var password: String = "",
41− var authRequired: Boolean = false,
42− var authed: Boolean = false,
43− var connected: Boolean = false,
44− var loading: Boolean = false,
45− var error: String? = null,
46− var sessions: MutableList<PureSession> = mutableListOf(),
47− var currentSessionId: String? = null,
48− var currentSessionTitle: String = "",
49− var messages: MutableList<PureMessage> = mutableListOf(),
50− var draftMessage: String = "",
51− var generating: Boolean = false,
52− var crashLogs: MutableList<String> = mutableListOf(),
53− var pendingRequests: MutableMap<UInt, PendingRequest> = mutableMapOf(),
54− var nextId: UInt = 0u,
55−) {
56− fun handleEvent(event: Event): Requests {
57− val requests = mutableListOf<Request>()
58− when (event) {
59− is Event.Start -> {
60− // Don't reset serverUrl — the shell restores the persisted value.
61− }
62− is Event.ServerUrlChanged -> {
63− serverUrl = event.value
64− }
65− is Event.UsernameChanged -> {
66− username = event.value
67− }
68− is Event.PasswordChanged -> {
69− password = event.value
70− }
71− is Event.Connect -> {
72− loading = true
73− error = null
74− val id = nextId++
75− pendingRequests[id] = PendingRequest.HealthProbe
76− requests.add(Request(id, Effect.Http(makeGetRequest("${serverUrl}/global/health"))))
77− }
78− is Event.CancelAuth -> {
79− authRequired = false
80− username = ""
81− password = ""
82− loading = false
83− }
84− is Event.LoadSessions -> {
85− loading = true
86− val id = nextId++
87− pendingRequests[id] = PendingRequest.LoadSessions
88− requests.add(Request(id, Effect.Http(makeGetRequest("${serverUrl}/session"))))
89− }
90− is Event.SelectSession -> {
91− currentSessionId = event.value
92− currentSessionTitle = sessions.firstOrNull { it.id == event.value }?.title ?: ""
93− messages.clear()
94− val id = nextId++
95− pendingRequests[id] = PendingRequest.LoadMessages(event.value)
96− requests.add(
97− Request(id, Effect.Http(makeGetRequest("${serverUrl}/session/${event.value}/message"))),
98− )
99− }
100− is Event.CreateSession -> {
101− loading = true
102− val id = nextId++
103− pendingRequests[id] = PendingRequest.CreateSession
104− requests.add(
105− Request(id, Effect.Http(makePostRequest("${serverUrl}/session", ByteArray(0)))),
106− )
107− }
108− is Event.LoadMessages -> {
109− loading = true
110− generating = false
111− val id = nextId++
112− pendingRequests[id] = PendingRequest.LoadMessages(event.value)
113− requests.add(
114− Request(id, Effect.Http(makeGetRequest("${serverUrl}/session/${event.value}/message"))),
115− )
116− }
117− is Event.SendMessage -> {
118− val sessionId = currentSessionId ?: return Requests(requests)
119− draftMessage = ""
120− generating = true
121− val body = """{"sessionID":"$sessionId","parts":[{"type":"text","text":"${event.value}"}]}"""
122− .toByteArray()
123− val id = nextId++
124− pendingRequests[id] = PendingRequest.SendMessage(sessionId)
125− requests.add(
126− Request(
127− id,
128− Effect.Http(
129− makePostRequest("${serverUrl}/session/$sessionId/prompt_async", body)
130− .copy(headers = listOf(HttpHeader("Content-Type", "application/json"))),
131− ),
132− ),
133− )
134− }
135− is Event.EventReceived -> {
136− val sid = currentSessionId
137− if (sid != null) {
138− val id = nextId++
139− pendingRequests[id] = PendingRequest.LoadMessages(sid)
140− requests.add(
141− Request(id, Effect.Http(makeGetRequest("${serverUrl}/session/$sid/message"))),
142− )
143− }
144− }
145− is Event.NavigateToChat -> {
146− currentSessionId = event.value
147− currentSessionTitle = sessions.firstOrNull { it.id == event.value }?.title ?: ""
148− messages.clear()
149− }
150− is Event.NavigateToSessions -> {
151− currentSessionId = null
152− currentSessionTitle = ""
153− messages.clear()
154− generating = false
155− }
156− is Event.NavigateToConnect -> {
157− currentSessionId = null
158− currentSessionTitle = ""
159− messages.clear()
160− generating = false
161− connected = false
162− authRequired = false
163− loading = false
164− }
165− is Event.DismissError -> {
166− error = null
167− }
168− else -> {}
169− }
170− return Requests(requests)
171− }
172−
173− fun handleResult(id: UInt, result: HttpResult): Requests {
174− val requests = mutableListOf<Request>()
175− val pending = pendingRequests.remove(id) ?: return Requests(requests)
176−
177− when (pending) {
178− is PendingRequest.HealthProbe -> {
179− when (result) {
180− is HttpResult.Ok -> {
181− val status = result.value.status.toInt()
182− if (status == 401) {
183− loading = false
184− val hasCreds = username.isNotEmpty() || password.isNotEmpty()
185− if (hasCreds) {
186− error = "Invalid credentials"
187− } else {
188− authRequired = true
189− }
190− } else if (status in 200..299) {
191− val hasCreds = username.isNotEmpty() || password.isNotEmpty()
192− if (hasCreds) authed = true
193− loading = true
194− val newId = nextId++
195− pendingRequests[newId] = PendingRequest.LoadSessions
196− requests.add(
197− Request(newId, Effect.Http(makeGetRequest("${serverUrl}/session"))),
198− )
199− } else {
200− loading = false
201− error = "Server returned status $status"
202− }
203− }
204− is HttpResult.Err -> {
205− loading = false
206− error = "Connection failed: ${result.value}"
207− }
208− }
209− }
210− is PendingRequest.LoadSessions -> {
211− loading = false
212− when (result) {
213− is HttpResult.Ok -> {
214− val body = result.value.body.content.decodeToString()
215− sessions = parseSessions(body).toMutableList()
216− connected = true
217− }
218− is HttpResult.Err -> {
219− error = "Failed to load sessions: ${result.value}"
220− }
221− }
222− }
223− is PendingRequest.CreateSession -> {
224− loading = false
225− when (result) {
226− is HttpResult.Ok -> {
227− val body = result.value.body.content.decodeToString()
228− val sid = extractJsonString(body, "id") ?: ""
229− if (sid.isNotEmpty()) {
230− val title = extractJsonString(body, "title")?.takeIf { it.isNotEmpty() }
231− ?: "New session"
232− currentSessionId = sid
233− currentSessionTitle = title
234− sessions.add(0, PureSession(sid, title))
235− messages.clear()
236− val newId = nextId++
237− pendingRequests[newId] = PendingRequest.LoadMessages(sid)
238− requests.add(
239− Request(newId, Effect.Http(makeGetRequest("${serverUrl}/session/$sid/message"))),
240− )
241− }
242− }
243− is HttpResult.Err -> {
244− error = "Failed to create session: ${result.value}"
245− }
246− }
247− }
248− is PendingRequest.LoadMessages -> {
249− loading = false
250− generating = false
251− when (result) {
252− is HttpResult.Ok -> {
253− val body = result.value.body.content.decodeToString()
254− messages = parseMessages(body).toMutableList()
255− }
256− is HttpResult.Err -> {
257− error = "Failed to load messages: ${result.value}"
258− }
259− }
260− }
261− is PendingRequest.SendMessage -> {
262− when (result) {
263− is HttpResult.Ok -> {
264− val sid = pending.sessionId
265− val newId = nextId++
266− pendingRequests[newId] = PendingRequest.LoadMessages(sid)
267− requests.add(
268− Request(newId, Effect.Http(makeGetRequest("${serverUrl}/session/$sid/message"))),
269− )
270− }
271− is HttpResult.Err -> {
272− generating = false
273− error = "Failed to send message: ${result.value}"
274− }
275− }
276− }
277− }
278− return Requests(requests)
279− }
280−
281− fun currentView(): ViewModel {
282− val screen = when {
283− currentSessionId != null -> Screen.CHAT
284− connected -> Screen.SESSIONS
285− else -> Screen.CONNECT
286− }
287− return ViewModel(
288− screen = screen,
289− serverUrl = serverUrl,
290− username = username,
291− password = password,
292− authRequired = authRequired,
293− connected = connected,
294− loading = loading,
295− error = error,
296− sessions = sessions.map { SessionView(it.id, it.title) },
297− currentSessionId = currentSessionId,
298− currentSessionTitle = currentSessionTitle,
299− messages = messages.map { MessageView(it.id, it.role, it.text, it.time) },
300− draftMessage = draftMessage,
301− generating = generating,
302− crashLogCount = crashLogs.size.toUInt(),
303− latestCrashLog = crashLogs.lastOrNull(),
304− )
305− }
306−
307− private fun makeGetRequest(url: String): HttpRequest {
308− val headers = if (username.isNotEmpty() || password.isNotEmpty()) {
309− val creds = "$username:$password"
310− val encoded = java.util.Base64.getEncoder().encodeToString(creds.toByteArray())
311− listOf(HttpHeader("Authorization", "Basic $encoded"))
312− } else {
313− emptyList()
314− }
315− return HttpRequest(method = "GET", url = url, headers = headers, body = Bytes(ByteArray(0)))
316− }
317−
318− private fun makePostRequest(url: String, body: ByteArray): HttpRequest {
319− val headers = if (username.isNotEmpty() || password.isNotEmpty()) {
320− val creds = "$username:$password"
321− val encoded = java.util.Base64.getEncoder().encodeToString(creds.toByteArray())
322− listOf(HttpHeader("Authorization", "Basic $encoded"))
323− } else {
324− emptyList()
325− }
326− return HttpRequest(method = "POST", url = url, headers = headers, body = Bytes(body))
327− }
328−}
329−
330−internal sealed class PendingRequest {
331− data object HealthProbe : PendingRequest()
332− data object LoadSessions : PendingRequest()
333− data object CreateSession : PendingRequest()
334− data class LoadMessages(val sessionId: String) : PendingRequest()
335− data class SendMessage(val sessionId: String) : PendingRequest()
336−}
337−
338−internal data class PureSession(val id: String, val title: String)
339−
340−internal data class PureMessage(val id: String, val role: String, val text: String, val time: ULong)
341−
342−internal fun parseSessions(json: String): List<PureSession> {
343− val sessions = mutableListOf<PureSession>()
344− var depth = 0
345− var start = 0
346− for (i in json.indices) {
347− when (json[i]) {
348− '{' -> {
349− if (depth == 0) start = i
350− depth++
351− }
352− '}' -> {
353− depth--
354− if (depth == 0) {
355− val obj = json.substring(start, i + 1)
356− val id = extractJsonString(obj, "id") ?: ""
357− val title = extractJsonString(obj, "title") ?: ""
358− if (id.isNotEmpty()) {
359− sessions.add(PureSession(id, if (title.isNotEmpty()) title else "Untitled"))
360− }
361− }
362− }
363− }
364− }
365− return sessions
366−}
367−
368−internal fun parseMessages(json: String): List<PureMessage> {
369− val messages = mutableListOf<PureMessage>()
370− var depth = 0
371− var start = 0
372− for (i in json.indices) {
373− when (json[i]) {
374− '{' -> {
375− if (depth == 0) start = i
376− depth++
377− }
378− '}' -> {
379− depth--
380− if (depth == 0) {
381− val obj = json.substring(start, i + 1)
382− val id = extractJsonString(obj, "id") ?: ""
383− val role = extractJsonString(obj, "role") ?: ""
384− val time = extractJsonNumber(obj, "created") ?: 0uL
385− if (id.isNotEmpty() && role.isNotEmpty()) {
386− messages.add(PureMessage(id, role, "", time))
387− }
388− }
389− }
390− }
391− }
392− return messages
393−}
394−
395−internal fun extractJsonString(json: String, key: String): String? {
396− val pattern = "\"$key\""
397− val idx = json.indexOf(pattern) ?: return null
398− val rest = json.substring(idx + pattern.length)
399− val colon = rest.indexOf(':') ?: return null
400− val rest2 = rest.substring(colon + 1)
401− val quote = rest2.indexOf('"') ?: return null
402− val rest3 = rest2.substring(quote + 1)
403− val end = rest3.indexOf('"') ?: return null
404− return rest3.substring(0, end)
405−}
406−
407−internal fun extractJsonNumber(json: String, key: String): ULong? {
408− val pattern = "\"$key\""
409− val idx = json.indexOf(pattern) ?: return null
410− val rest = json.substring(idx + pattern.length)
411− val colon = rest.indexOf(':') ?: return null
412− val rest2 = rest.substring(colon + 1).trimStart()
413− val end = rest2.indexOfFirst { !it.isDigit() }.let { if (it == -1) rest2.length else it }
414− return rest2.substring(0, end).toULongOrNull()
415−}
app/src/main/java/soy/iko/opencode/core/SseClient.kt+48−93
@@ -1,108 +1,63 @@
1package soy.iko.opencode.core
1package soy.iko.opencode.core
2
2
3−import io.ktor.client.HttpClient
3+import okhttp3.OkHttpClient
4−import io.ktor.client.engine.okhttp.OkHttp
4+import okhttp3.Request
5−import io.ktor.client.plugins.HttpTimeout
5+import okhttp3.Response
6−import io.ktor.client.request.prepareGet
6+import okhttp3.sse.EventSource
7−import io.ktor.client.statement.bodyAsChannel
7+import okhttp3.sse.EventSourceListener
8−import io.ktor.utils.io.readUTF8Line
8+import okhttp3.sse.EventSources
9−import kotlinx.coroutines.CoroutineScope
9+import java.util.concurrent.TimeUnit
10−import kotlinx.coroutines.Dispatchers
11−import kotlinx.coroutines.Job
12−import kotlinx.coroutines.SupervisorJob
13−import kotlinx.coroutines.flow.MutableSharedFlow
14−import kotlinx.coroutines.flow.MutableStateFlow
15−import kotlinx.coroutines.flow.SharedFlow
16−import kotlinx.coroutines.flow.StateFlow
17−import kotlinx.coroutines.flow.asSharedFlow
18−import kotlinx.coroutines.flow.asStateFlow
19−import kotlinx.coroutines.launch
20−import soy.iko.opencode.CrashLogger
21
10
22/**
11/**
23− * Subscribes to the opencode server's SSE event stream (`GET /event`).
12+ * Long-lived subscription to the opencode `/event` SSE stream.
24 *
13 *
25− * Events are emitted as raw strings on [events]. The Core converts them into
14+ * Crux only models request/response HTTP, so the streaming connection lives here
26− * [Event.EventReceived] which triggers a message reload.
15+ * in the shell: each decoded event's `data` payload (a JSON object whose own
27− *
16+ * `type` field is the discriminant) is handed to [onEvent], which the core then
28− * The live connection status is exposed via [state] so the UI can surface a
17+ * parses via [Protocol.parseEvent].
29− * "live stream disconnected" banner to the user instead of silently dropping
30− * updates. Transport errors are still reported to [CrashLogger] for
31− * diagnostics, but they are no longer hidden from the user.
32 */
18 */
33−class SseClient {
19+class SseClient(
34− private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
20+ private val url: String,
35− private val httpClient = HttpClient(OkHttp) {
21+ private val auth: String?,
36− install(HttpTimeout) {
22+ private val onEvent: (String) -> Unit,
37− requestTimeoutMillis = Long.MAX_VALUE
23+ private val onStateChange: (Boolean) -> Unit,
38− connectTimeoutMillis = 15_000
24+) {
39− socketTimeoutMillis = Long.MAX_VALUE
25+ // A dedicated client with no read timeout — the stream is meant to stay open.
40− }
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)
41 }
39 }
42
40
43− private val _events = MutableSharedFlow<String>(extraBufferCapacity = 64)
41+ fun close() {
44− val events: SharedFlow<String> = _events.asSharedFlow()
42+ source?.cancel()
45−
43+ source = null
46− private val _state = MutableStateFlow<SseState>(SseState.Disconnected)
44+ }
47− val state: StateFlow<SseState> = _state.asStateFlow()
48
45
49− private var currentJob: Job? = null
46+ private val listener = object : EventSourceListener() {
50− @Volatile private var currentUrl: String? = null
47+ override fun onOpen(eventSource: EventSource, response: Response) {
48+ onStateChange(true)
49+ }
51
50
52− fun connect(url: String) {
51+ override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
53− currentUrl = url
52+ if (data.isNotBlank()) onEvent(data)
54− currentJob?.cancel()
55− _state.value = SseState.Connecting
56− currentJob = scope.launch {
57− try {
58− httpClient.prepareGet(url).execute { response ->
59− _state.value = SseState.Connected
60− val channel = response.bodyAsChannel()
61− val dataBuilder = StringBuilder()
62− while (!channel.isClosedForRead) {
63− val line = channel.readUTF8Line() ?: break
64− if (line.startsWith("data: ")) {
65− dataBuilder.append(line.substring(6))
66− } else if (line.isEmpty() && dataBuilder.isNotEmpty()) {
67− _events.emit(dataBuilder.toString())
68− dataBuilder.clear()
69− }
70− }
71− // Stream ended normally — flag as disconnected so the UI
72− // can offer a reconnect.
73− _state.value = SseState.Disconnected
74− }
75− } catch (e: kotlinx.coroutines.CancellationException) {
76− _state.value = SseState.Disconnected
77− throw e
78− } catch (e: Throwable) {
79− CrashLogger.report(e, "SseClient")
80− _state.value = SseState.Error(e.message ?: "Connection lost")
81− }
82 }
53 }
83− }
84
54
85− /** Re-establish the previous connection, if any. */
55+ override fun onClosed(eventSource: EventSource) {
86− fun reconnect() {
56+ onStateChange(false)
87− currentUrl?.let { connect(it) }
88− }
57+ }
89
58
90− fun disconnect() {
59+ override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
91− currentJob?.cancel()
60+ onStateChange(false)
92− currentJob = null
61+ }
93− currentUrl = null
94− _state.value = SseState.Disconnected
95 }
62 }
96}
63}
97−
98−/** Live status of the SSE event stream. */
99−sealed interface SseState {
100− /** Not connected (initial state, or after a clean close). */
101− data object Disconnected : SseState
102− /** Connection attempt in progress. */
103− data object Connecting : SseState
104− /** Stream is open and events are being received. */
105− data object Connected : SseState
106− /** The stream dropped unexpectedly. [message] describes the failure. */
107− data class Error(val message: String) : SseState
108−}
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/ui/OpencodeApp.ktnew file+124
@@ -0,0 +1,124 @@
1+package soy.iko.opencode.ui
2+
3+import androidx.activity.compose.BackHandler
4+import androidx.compose.animation.AnimatedContent
5+import androidx.compose.animation.slideInHorizontally
6+import androidx.compose.animation.slideOutHorizontally
7+import androidx.compose.animation.togetherWith
8+import 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
17+import androidx.compose.runtime.Composable
18+import androidx.compose.runtime.LaunchedEffect
19+import androidx.compose.runtime.getValue
20+import androidx.compose.runtime.mutableStateOf
21+import androidx.compose.runtime.remember
22+import androidx.compose.runtime.setValue
23+import androidx.compose.ui.Modifier
24+import soy.iko.opencode.core.Event
25+import soy.iko.opencode.core.Screen
26+import soy.iko.opencode.core.UiState
27+import soy.iko.opencode.ui.screens.ChatScreen
28+import soy.iko.opencode.ui.screens.ConnectScreen
29+import soy.iko.opencode.ui.screens.SessionsScreen
30+
31+@Composable
32+fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
33+ val snackbar = remember { SnackbarHostState() }
34+ var showStopConfirm by remember { mutableStateOf(false) }
35+ var showDisconnectConfirm by remember { mutableStateOf(false) }
36+
37+ LaunchedEffect(state.error) {
38+ state.error?.let {
39+ snackbar.showSnackbar(
40+ message = it,
41+ actionLabel = "Dismiss",
42+ duration = SnackbarDuration.Short,
43+ )
44+ // Always clear the error from state after showing.
45+ dispatch(Event.DismissError)
46+ }
47+ }
48+
49+ BackHandler(enabled = state.screen != Screen.Connect) {
50+ when (state.screen) {
51+ // Leaving mid-generation would silently drop the reply, so confirm first.
52+ Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
53+ // Disconnecting drops the server session, so guard the back button.
54+ Screen.Sessions -> showDisconnectConfirm = true
55+ Screen.Connect -> Unit
56+ }
57+ }
58+
59+ if (showStopConfirm) {
60+ AlertDialog(
61+ onDismissRequest = { showStopConfirm = false },
62+ title = { Text("Stop generation?") },
63+ text = { Text("Leaving will stop the current generation.") },
64+ confirmButton = {
65+ TextButton(onClick = {
66+ showStopConfirm = false
67+ dispatch(Event.CancelGeneration)
68+ dispatch(Event.NavigateToSessions)
69+ }) {
70+ Text("Stop and leave")
71+ }
72+ },
73+ dismissButton = {
74+ TextButton(onClick = { showStopConfirm = false }) {
75+ Text("Stay")
76+ }
77+ },
78+ )
79+ }
80+
81+ if (showDisconnectConfirm) {
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")
92+ }
93+ },
94+ dismissButton = {
95+ TextButton(onClick = { showDisconnectConfirm = false }) {
96+ Text("Cancel")
97+ }
98+ },
99+ )
100+ }
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 }
111+ } else {
112+ slideInHorizontally { -it } togetherWith slideOutHorizontally { it }
113+ }
114+ },
115+ label = "screen",
116+ ) { screen ->
117+ when (screen) {
118+ Screen.Connect -> ConnectScreen(state, dispatch)
119+ Screen.Sessions -> SessionsScreen(state, dispatch)
120+ Screen.Chat -> ChatScreen(state, dispatch)
121+ }
122+ }
123+ }
124+}
app/src/main/java/soy/iko/opencode/ui/components/ChatInputBar.ktdeleted−102
@@ -1,102 +0,0 @@
1−package soy.iko.opencode.ui.components
2−
3−import androidx.compose.foundation.layout.Arrangement
4−import androidx.compose.foundation.layout.Row
5−import androidx.compose.foundation.layout.Spacer
6−import androidx.compose.foundation.layout.fillMaxWidth
7−import androidx.compose.foundation.layout.imePadding
8−import androidx.compose.foundation.layout.navigationBarsPadding
9−import androidx.compose.foundation.layout.padding
10−import androidx.compose.foundation.layout.size
11−import androidx.compose.foundation.text.KeyboardActions
12−import androidx.compose.foundation.text.KeyboardOptions
13−import androidx.compose.material.icons.Icons
14−import androidx.compose.material.icons.automirrored.filled.Send
15−import androidx.compose.material3.Icon
16−import androidx.compose.material3.IconButton
17−import androidx.compose.material3.MaterialTheme
18−import androidx.compose.material3.OutlinedTextField
19−import androidx.compose.material3.Surface
20−import androidx.compose.material3.Text
21−import androidx.compose.runtime.Composable
22−import androidx.compose.ui.Alignment
23−import androidx.compose.ui.Modifier
24−import androidx.compose.ui.semantics.contentDescription
25−import androidx.compose.ui.semantics.semantics
26−import androidx.compose.ui.text.input.ImeAction
27−import androidx.compose.ui.tooling.preview.Preview
28−import androidx.compose.ui.unit.dp
29−import soy.iko.opencode.ui.theme.Dimens
30−import soy.iko.opencode.ui.theme.OpencodeTheme
31−
32−/**
33− * The chat message composer. A multi-line text field plus a send icon button.
34− *
35− * - Honors IME insets via [Modifier.imePadding] so the keyboard never covers
36− * the input bar (the chat Scaffold relies on this).
37− * - Exposes a keyboard "Send" action so users can fire-and-forget without
38− * tapping the icon.
39− * - Send is disabled while [enabled] is false (e.g. during loading) or when
40− * the text is blank.
41− */
42−@Composable
43−fun ChatInputBar(
44− text: String,
45− onTextChange: (String) -> Unit,
46− onSend: () -> Unit,
47− enabled: Boolean,
48− modifier: Modifier = Modifier,
49− placeholder: String = "Message…",
50− sendContentDescription: String = "Send",
51−) {
52− Surface(
53− tonalElevation = Dimens.inputBarTonalElevation,
54− modifier = modifier
55− .fillMaxWidth()
56− .imePadding()
57− .navigationBarsPadding(),
58− ) {
59− Row(
60− verticalAlignment = Alignment.CenterVertically,
61− horizontalArrangement = Arrangement.spacedBy(Dimens.spaceSmall),
62− modifier = Modifier
63− .fillMaxWidth()
64− .padding(
65− horizontal = Dimens.inputBarHorizontalPadding,
66− vertical = Dimens.inputBarVerticalPadding,
67− ),
68− ) {
69− OutlinedTextField(
70− value = text,
71− onValueChange = onTextChange,
72− placeholder = { Text(placeholder) },
73− modifier = Modifier.weight(1f),
74− maxLines = 4,
75− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
76− keyboardActions = KeyboardActions(onSend = { onSend() }),
77− )
78− IconButton(
79− onClick = onSend,
80− enabled = enabled && text.isNotBlank(),
81− modifier = Modifier.semantics {
82− contentDescription = sendContentDescription
83− },
84− ) {
85− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = null)
86− }
87− }
88− }
89−}
90−
91−@Preview(showBackground = true)
92−@Composable
93−private fun ChatInputBarPreview() {
94− OpencodeTheme {
95− ChatInputBar(
96− text = "Hello world",
97− onTextChange = {},
98− onSend = {},
99− enabled = true,
100− )
101− }
102−}
app/src/main/java/soy/iko/opencode/ui/components/CrashLogDialog.ktdeleted−162
@@ -1,162 +0,0 @@
1−package soy.iko.opencode.ui.components
2−
3−import androidx.compose.foundation.layout.Column
4−import androidx.compose.foundation.layout.Spacer
5−import androidx.compose.foundation.layout.fillMaxWidth
6−import androidx.compose.foundation.layout.height
7−import androidx.compose.foundation.layout.heightIn
8−import androidx.compose.foundation.layout.padding
9−import androidx.compose.foundation.rememberScrollState
10−import androidx.compose.foundation.verticalScroll
11−import androidx.compose.material3.AlertDialog
12−import androidx.compose.material3.MaterialTheme
13−import androidx.compose.material3.Text
14−import androidx.compose.material3.TextButton
15−import androidx.compose.runtime.Composable
16−import androidx.compose.runtime.getValue
17−import androidx.compose.runtime.mutableStateOf
18−import androidx.compose.runtime.remember
19−import androidx.compose.runtime.setValue
20−import androidx.compose.ui.Modifier
21−import androidx.compose.ui.tooling.preview.Preview
22−import androidx.compose.ui.unit.dp
23−import soy.iko.opencode.ui.theme.Dimens
24−import soy.iko.opencode.ui.theme.OpencodeTheme
25−import java.io.File
26−
27−/**
28− * Dialog listing persisted crash reports. Each report shows the file name
29− * (header) and the full stack trace (body). Height wraps content but is
30− * capped at 60% of the viewport via [Modifier.heightIn] so very long traces
31− * scroll internally without consuming the whole screen.
32− *
33− * Crash report file contents are read once via [remember] (off the first
34− * recomposition) rather than on every recomposition — [File.readText] is disk
35− * I/O and shouldn't run in composition repeatedly.
36− *
37− * "Clear all" is a destructive action: it's placed in the dismiss slot (left,
38− * neutral) and tinted with the error color, and a confirmation step guards
39− * against accidental taps. "Close" is the affirmative (right) action.
40− */
41−@Composable
42−fun CrashLogDialog(
43− reports: List<File>,
44− onDismiss: () -> Unit,
45− onClear: () -> Unit,
46− modifier: Modifier = Modifier,
47− title: String = "Crash Reports",
48− clearLabel: String = "Clear all",
49− closeLabel: String = "Close",
50− clearConfirmLabel: String = "Clear all crash reports?",
51− clearConfirmYesLabel: String = "Clear",
52−) {
53− // Read each report's text once, not on every recomposition.
54− val contents = remember(reports) {
55− reports.map { it.name to it.readText() }
56− }
57− var confirmingClear by remember { mutableStateOf(false) }
58−
59− AlertDialog(
60− onDismissRequest = {
61− if (confirmingClear) confirmingClear = false else onDismiss()
62− },
63− modifier = modifier,
64− title = { Text(title) },
65− text = {
66− if (confirmingClear) {
67− Text(
68− text = clearConfirmLabel,
69− style = MaterialTheme.typography.bodyMedium,
70− )
71− } else {
72− Column(
73− modifier = Modifier
74− .fillMaxWidth()
75− .heightIn(max = 360.dp)
76− .verticalScroll(rememberScrollState()),
77− ) {
78− contents.forEachIndexed { index, (name, text) ->
79− Text(
80− text = name,
81− style = MaterialTheme.typography.labelMedium,
82− color = MaterialTheme.colorScheme.primary,
83− )
84− Spacer(Modifier.height(Dimens.spaceTiny))
85− Text(
86− text = text,
87− style = MaterialTheme.typography.bodySmall,
88− )
89− if (index < contents.lastIndex) {
90− Spacer(Modifier.height(Dimens.spaceMedium))
91− }
92− }
93− }
94− }
95− },
96− confirmButton = {
97− // Primary (right) button: "Close" is the non-destructive action.
98− TextButton(onClick = onDismiss) { Text(closeLabel) }
99− },
100− dismissButton = {
101− if (confirmingClear) {
102− // Confirm step: the affirmative "Clear" sits on the right now,
103− // so expose a "Cancel" on the left to abort.
104− TextButton(onClick = { confirmingClear = false }) { Text(closeLabel) }
105− } else {
106− // Destructive action in the dismiss slot (left), tinted error.
107− TextButton(onClick = { confirmingClear = true }) {
108− Text(
109− text = clearLabel,
110− color = MaterialTheme.colorScheme.error,
111− )
112− }
113− }
114− },
115− )
116−
117− // Second-stage confirmation dialog: actually clear when the user confirms.
118− if (confirmingClear) {
119− AlertDialog(
120− onDismissRequest = { confirmingClear = false },
121− title = { Text(title) },
122− text = { Text(clearConfirmLabel) },
123− confirmButton = {
124− TextButton(onClick = {
125− onClear()
126− confirmingClear = false
127− }) {
128− Text(
129− text = clearConfirmYesLabel,
130− color = MaterialTheme.colorScheme.error,
131− )
132− }
133− },
134− dismissButton = {
135− TextButton(onClick = { confirmingClear = false }) { Text(closeLabel) }
136− },
137− )
138− }
139−}
140−
141−@Preview(showBackground = true)
142−@Composable
143−private fun CrashLogDialogPreview() {
144− val tmp = File(System.getProperty("java.io.tmpdir"), "crash_preview.txt").apply {
145− writeText("java.lang.RuntimeException: preview crash\n\tat foo.bar.baz(Preview.kt:1)")
146− }
147− OpencodeTheme {
148− CrashLogDialog(
149− reports = listOf(tmp),
150− onDismiss = {},
151− onClear = {},
152− )
153− }
154−}
155−
156−@Preview(showBackground = true)
157−@Composable
158−private fun CrashLogDialogEmptyPreview() {
159− OpencodeTheme {
160− CrashLogDialog(reports = emptyList(), onDismiss = {}, onClear = {})
161− }
162−}
app/src/main/java/soy/iko/opencode/ui/components/ErrorHost.ktdeleted−130
@@ -1,130 +0,0 @@
1−package soy.iko.opencode.ui.components
2−
3−import androidx.compose.foundation.layout.Column
4−import androidx.compose.material3.MaterialTheme
5−import androidx.compose.material3.Snackbar
6−import androidx.compose.material3.SnackbarDuration
7−import androidx.compose.material3.SnackbarHost
8−import androidx.compose.material3.SnackbarHostState
9−import androidx.compose.material3.SnackbarResult
10−import androidx.compose.runtime.Composable
11−import androidx.compose.runtime.LaunchedEffect
12−import androidx.compose.runtime.collectAsState
13−import androidx.compose.runtime.getValue
14−import androidx.compose.runtime.remember
15−import kotlinx.coroutines.flow.SharedFlow
16−import soy.iko.opencode.core.Core
17−import soy.iko.opencode.core.Event
18−
19−/**
20− * A [SnackbarHostState] that observes [ViewModel.error] and surfaces it to
21− * the user. Offers a "Dismiss" action that sends [Event.DismissError] to
22− * clear the error in the core so it doesn't re-show on recomposition.
23− *
24− * When the core has a retryable last event, a "Retry" action is also offered
25− * (it takes precedence over "Dismiss" since it's more useful). Tapping Retry
26− * re-sends the last user-initiated event.
27− *
28− * Used by every screen so error messages are never silently dropped.
29− */
30−@Composable
31−fun ErrorHost(
32− core: Core,
33− dismissLabel: String = "Dismiss",
34− retryLabel: String = "Retry",
35−): SnackbarHostState {
36− val view by core.view.collectAsState()
37− val snackbarHostState = remember { SnackbarHostState() }
38−
39− LaunchedEffect(view.error) {
40− val message = view.error
41− if (!message.isNullOrEmpty()) {
42− val canRetry = core.retryableEvent != null
43− val result = snackbarHostState.showSnackbar(
44− message = message,
45− actionLabel = if (canRetry) retryLabel else dismissLabel,
46− duration = SnackbarDuration.Long,
47− )
48− when (result) {
49− SnackbarResult.ActionPerformed -> {
50− if (canRetry) core.retry() else core.update(Event.DismissError)
51− }
52− SnackbarResult.Dismissed -> core.update(Event.DismissError)
53− }
54− }
55− }
56−
57− return snackbarHostState
58−}
59−
60−/**
61− * Collects transient success/info messages from [Core.info] and surfaces them
62− * as a short snackbar. This gives the user positive feedback (e.g. "Session
63− * created") instead of only ever showing errors.
64− *
65− * Uses a dedicated [SnackbarHostState] (separate from the error host) so the
66− * info snackbar can be rendered with default colors rather than the error
67− * palette. The screens render both hosts in the Scaffold's `snackbarHost`
68− * slot; typically only one fires at a time.
69− */
70−@Composable
71−fun InfoHost(
72− core: Core,
73− successConnectedLabel: String,
74− successSessionCreatedLabel: String,
75−): SnackbarHostState {
76− val snackbarHostState = remember { SnackbarHostState() }
77− LaunchedEffect(snackbarHostState) {
78− core.info.collect { key ->
79− val message = when (key) {
80− Core.SUCCESS_CONNECTED -> successConnectedLabel
81− Core.SUCCESS_SESSION_CREATED -> successSessionCreatedLabel
82− else -> key
83− }
84− snackbarHostState.showSnackbar(
85− message = message,
86− duration = SnackbarDuration.Short,
87− )
88− }
89− }
90− return snackbarHostState
91−}
92−
93−@Composable
94−fun ErrorSnackbarHost(snackbarHostState: SnackbarHostState) {
95− SnackbarHost(snackbarHostState) { data ->
96− Snackbar(
97− containerColor = MaterialTheme.colorScheme.errorContainer,
98− contentColor = MaterialTheme.colorScheme.onErrorContainer,
99− actionContentColor = MaterialTheme.colorScheme.onErrorContainer,
100− snackbarData = data,
101− )
102− }
103−}
104−
105−/**
106− * Snackbar host for success/info messages. Uses the default (surface-tonal)
107− * colors so positive feedback doesn't read as an error.
108− */
109−@Composable
110−fun InfoSnackbarHost(snackbarHostState: SnackbarHostState) {
111− SnackbarHost(snackbarHostState) { data ->
112− Snackbar(snackbarData = data)
113− }
114−}
115−
116−/**
117− * Renders both the error and info snackbar hosts stacked vertically. The
118− * Material 3 [Scaffold] only accepts a single `snackbarHost` slot, so screens
119− * pass this helper to show both flavors without one overwriting the other.
120− */
121−@Composable
122−fun DualSnackbarHost(
123− errorHostState: SnackbarHostState,
124− infoHostState: SnackbarHostState,
125−) {
126− Column {
127− ErrorSnackbarHost(errorHostState)
128− InfoSnackbarHost(infoHostState)
129− }
130−}
app/src/main/java/soy/iko/opencode/ui/components/LoadingPlaceholder.ktdeleted−81
@@ -1,81 +0,0 @@
1−package soy.iko.opencode.ui.components
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.fillMaxSize
7−import androidx.compose.foundation.layout.padding
8−import androidx.compose.material3.CircularProgressIndicator
9−import androidx.compose.material3.MaterialTheme
10−import androidx.compose.material3.Text
11−import androidx.compose.runtime.Composable
12−import androidx.compose.ui.Alignment
13−import androidx.compose.ui.Modifier
14−import androidx.compose.ui.semantics.LiveRegionMode
15−import androidx.compose.ui.semantics.contentDescription
16−import androidx.compose.ui.semantics.liveRegion
17−import androidx.compose.ui.semantics.semantics
18−import androidx.compose.ui.text.style.TextAlign
19−import androidx.compose.ui.tooling.preview.Preview
20−import soy.iko.opencode.ui.theme.Dimens
21−import soy.iko.opencode.ui.theme.OpencodeTheme
22−
23−/**
24− * Centered indeterminate loading indicator. Used when a screen is loading its
25− * initial content and has nothing else to show. Marked as a polite live region
26− * so TalkBack announces "loading" once.
27− */
28−@Composable
29−fun LoadingPlaceholder(
30− modifier: Modifier = Modifier,
31− contentDescription: String = "Loading",
32−) {
33− Box(
34− modifier = modifier
35− .fillMaxSize()
36− .semantics(mergeDescendants = true) {
37− liveRegion = LiveRegionMode.Polite
38− this.contentDescription = contentDescription
39− },
40− contentAlignment = Alignment.Center,
41− ) {
42− CircularProgressIndicator()
43− }
44−}
45−
46−/**
47− * Centered empty-state message. Used when a screen has no content yet (e.g.
48− * no sessions, no messages).
49− */
50−@Composable
51−fun EmptyState(
52− message: String,
53− modifier: Modifier = Modifier,
54−) {
55− Column(
56− horizontalAlignment = Alignment.CenterHorizontally,
57− verticalArrangement = Arrangement.Center,
58− modifier = modifier
59− .fillMaxSize()
60− .padding(Dimens.screenPadding),
61− ) {
62− Text(
63− text = message,
64− style = MaterialTheme.typography.bodyLarge,
65− color = MaterialTheme.colorScheme.onSurfaceVariant,
66− textAlign = TextAlign.Center,
67− )
68− }
69−}
70−
71−@Preview(showBackground = true)
72−@Composable
73−private fun LoadingPlaceholderPreview() {
74− OpencodeTheme { LoadingPlaceholder() }
75−}
76−
77−@Preview(showBackground = true)
78−@Composable
79−private fun EmptyStatePreview() {
80− OpencodeTheme { EmptyState(message = "No sessions yet") }
81−}
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+417−274
@@ -1,336 +1,479 @@
1package soy.iko.opencode.ui.components
1package soy.iko.opencode.ui.components
2
2
3−import androidx.compose.animation.core.RepeatMode
3+import android.content.ClipData
4−import androidx.compose.animation.core.animateFloat
4+import android.content.ClipboardManager
5−import androidx.compose.animation.core.infiniteRepeatable
5+import android.content.Context
6−import androidx.compose.animation.core.rememberInfiniteTransition
6+import android.content.Intent
7−import androidx.compose.animation.core.tween
7+import android.net.Uri
8+import android.widget.Toast
8import androidx.compose.foundation.ExperimentalFoundationApi
9import androidx.compose.foundation.ExperimentalFoundationApi
10+import androidx.compose.foundation.background
11+import androidx.compose.foundation.clickable
9import androidx.compose.foundation.combinedClickable
12import androidx.compose.foundation.combinedClickable
10import androidx.compose.foundation.layout.Arrangement
13import androidx.compose.foundation.layout.Arrangement
11import androidx.compose.foundation.layout.Column
14import androidx.compose.foundation.layout.Column
12import androidx.compose.foundation.layout.Row
15import androidx.compose.foundation.layout.Row
13−import androidx.compose.foundation.layout.Spacer
14import androidx.compose.foundation.layout.fillMaxWidth
16import androidx.compose.foundation.layout.fillMaxWidth
15−import androidx.compose.foundation.layout.height
16import androidx.compose.foundation.layout.padding
17import androidx.compose.foundation.layout.padding
17import androidx.compose.foundation.layout.size
18import androidx.compose.foundation.layout.size
18import androidx.compose.foundation.layout.widthIn
19import androidx.compose.foundation.layout.widthIn
20+import androidx.compose.foundation.shape.RoundedCornerShape
21+import androidx.compose.foundation.text.selection.SelectionContainer
22+import androidx.compose.material.icons.Icons
23+import androidx.compose.material.icons.filled.Build
24+import androidx.compose.material.icons.filled.Check
25+import androidx.compose.material.icons.filled.ErrorOutline
26+import androidx.compose.material.icons.filled.ExpandLess
27+import androidx.compose.material.icons.filled.ExpandMore
28+import androidx.compose.material.icons.filled.Schedule
29+import androidx.compose.material.icons.filled.SmartToy
30+import androidx.compose.material3.DropdownMenu
31+import androidx.compose.material3.DropdownMenuItem
32+import androidx.compose.material3.Icon
19import androidx.compose.material3.MaterialTheme
33import androidx.compose.material3.MaterialTheme
20−import androidx.compose.material3.Surface
21import androidx.compose.material3.Text
34import androidx.compose.material3.Text
22import androidx.compose.runtime.Composable
35import androidx.compose.runtime.Composable
23import androidx.compose.runtime.getValue
36import androidx.compose.runtime.getValue
37+import androidx.compose.runtime.mutableStateOf
24import androidx.compose.runtime.remember
38import androidx.compose.runtime.remember
39+import androidx.compose.runtime.setValue
40+import androidx.compose.ui.Alignment
25import androidx.compose.ui.Modifier
41import androidx.compose.ui.Modifier
26−import androidx.compose.ui.hapticfeedback.HapticFeedbackType
42+import androidx.compose.ui.draw.clip
27−import androidx.compose.ui.platform.LocalClipboardManager
28−import androidx.compose.ui.platform.LocalDensity
29−import androidx.compose.ui.platform.LocalHapticFeedback
43+import androidx.compose.ui.graphics.Color
30−import androidx.compose.ui.platform.LocalWindowInfo
44+import androidx.compose.ui.platform.LocalContext
31−import androidx.compose.ui.res.stringResource
32−import androidx.compose.ui.semantics.LiveRegionMode
33−import androidx.compose.ui.semantics.contentDescription
34−import androidx.compose.ui.semantics.liveRegion
35−import androidx.compose.ui.semantics.semantics
36import androidx.compose.ui.text.AnnotatedString
45import androidx.compose.ui.text.AnnotatedString
46+import androidx.compose.ui.text.LinkAnnotation
47+import androidx.compose.ui.text.SpanStyle
48+import androidx.compose.ui.text.TextLinkStyles
49+import androidx.compose.ui.text.buildAnnotatedString
50+import androidx.compose.ui.text.font.FontFamily
37import androidx.compose.ui.text.font.FontStyle
51import androidx.compose.ui.text.font.FontStyle
38−import androidx.compose.ui.tooling.preview.Preview
52+import androidx.compose.ui.text.font.FontWeight
53+import androidx.compose.ui.text.withLink
54+import androidx.compose.ui.text.withStyle
55+import androidx.compose.ui.text.style.TextDecoration
56+import androidx.compose.ui.text.style.TextOverflow
39import androidx.compose.ui.unit.dp
57import androidx.compose.ui.unit.dp
40−import com.mikepenz.markdown.m3.Markdown
58+import androidx.compose.ui.unit.sp
41−import soy.iko.opencode.R
59+import soy.iko.opencode.core.MessageStatus
42import soy.iko.opencode.core.MessageView
60import soy.iko.opencode.core.MessageView
43−import soy.iko.opencode.ui.theme.AssistantBubbleShape
61+import soy.iko.opencode.core.ToolView
44−import soy.iko.opencode.ui.theme.Dimens
62+import soy.iko.opencode.ui.theme.MonoStyle
45−import soy.iko.opencode.ui.theme.OpencodeTheme
63+
46−import soy.iko.opencode.ui.theme.UserBubbleShape
64+private val timeFormat = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
47−import java.text.SimpleDateFormat
48−import java.util.Date
49−import java.util.Locale
50
65
51−/**
52− * A single chat message rendered as a left/right-aligned bubble. Assistant
53− * messages are rendered as markdown; user messages as plain text. The bubble
54− * shape carries an iMessage-style "tail" on the speaker's side.
55− *
56− * Accessibility: the whole bubble is merged into one semantics node so
57− * TalkBack reads the role label + content as a single utterance. Assistant
58− * bubbles are marked as a [LiveRegionMode.Polite] live region so streaming
59− * updates are announced without stealing focus.
60− *
61− * Long-press anywhere on the bubble copies the raw message text to the
62− * clipboard and emits a long-press haptic, mirroring the standard chat UX.
63− */
64@OptIn(ExperimentalFoundationApi::class)
66@OptIn(ExperimentalFoundationApi::class)
65@Composable
67@Composable
66−fun MessageBubble(
67− message: MessageView,
68− modifier: Modifier = Modifier,
68+fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry: () -> Unit = {}, compactSpacing: Boolean = false) {
69−) {
70− val isUser = message.role == "user"
69+ val isUser = message.isUser
71− val maxWidth = maxBubbleWidthDp()
70+ val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
72− val roleLabel = if (isUser) {
71+ val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
73− stringResource(R.string.chat_role_user)
72+ val mutedColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.6f) else MaterialTheme.colorScheme.onSurfaceVariant
74− } else {
73+ val shape = RoundedCornerShape(
75− stringResource(R.string.chat_role_assistant)
74+ topStart = 16.dp,
76− }
75+ topEnd = 16.dp,
77− val timeLabel = remember(message.time) { formatTimestamp(message.time) }
76+ bottomStart = if (isUser) 16.dp else 4.dp,
78− val clipboardManager = LocalClipboardManager.current
77+ bottomEnd = if (isUser) 4.dp else 16.dp,
79− val hapticFeedback = LocalHapticFeedback.current
78+ )
80− // Build a single TalkBack utterance that includes the role and the
79+
81− // message body. Setting an explicit contentDescription on a merge node
80+ val context = LocalContext.current
82− // replaces descendant text, so we must include the body ourselves rather
81+ var showMenu by remember { mutableStateOf(false) }
83− // than letting it merge — otherwise TalkBack reads only "User".
82+
84− val announcement = buildString {
85− append(roleLabel)
86− if (message.time > 0uL) {
87− append(", ")
88− append(timeLabel)
89− }
90− append(". ")
91− append(if (message.text.isBlank()) stringResource(R.string.chat_no_content) else message.text)
92− }
93 Row(
83 Row(
94− modifier = modifier
84+ modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = if (compactSpacing) 1.dp else 4.dp),
95− .fillMaxWidth()
96− .combinedClickable(
97− onLongClick = {
98− if (message.text.isNotBlank()) {
99− clipboardManager.setText(AnnotatedString(message.text))
100− hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
101− }
102− },
103− onClick = {},
104− )
105− .semantics(mergeDescendants = true) {
106− contentDescription = announcement
107− },
108 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
85 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
109 ) {
86 ) {
110− Surface(
111− color = if (isUser) {
112− MaterialTheme.colorScheme.primary
113− } else {
114− MaterialTheme.colorScheme.surfaceVariant
115− },
116− contentColor = if (isUser) {
117− MaterialTheme.colorScheme.onPrimary
118− } else {
119− MaterialTheme.colorScheme.onSurfaceVariant
120− },
121− shape = if (isUser) UserBubbleShape else AssistantBubbleShape,
122− modifier = Modifier.widthIn(max = maxWidth),
123− ) {
124− Column(
125− modifier = Modifier.padding(
126− horizontal = Dimens.bubbleHorizontalPadding,
127− vertical = Dimens.bubbleVerticalPadding,
128− ),
129− ) {
130− if (!isUser) {
87+ if (!isUser) {
131− Row(
88+ Icon(
132− modifier = Modifier.fillMaxWidth(),
89+ Icons.Filled.SmartToy,
133− horizontalArrangement = Arrangement.SpaceBetween,
90+ contentDescription = null,
134− verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
91+ tint = MaterialTheme.colorScheme.primary,
135− ) {
92+ modifier = Modifier.align(Alignment.Top).padding(end = 6.dp, top = 2.dp).size(28.dp),
136− Text(
93+ )
137− text = roleLabel,
94+ }
138− style = MaterialTheme.typography.labelSmall,
95+ Column(
139− color = MaterialTheme.colorScheme.primary,
140− )
141− if (message.time > 0uL) {
142− Text(
143− text = timeLabel,
144− style = MaterialTheme.typography.labelSmall,
145− color = MaterialTheme.colorScheme.onSurfaceVariant,
146− )
147− }
148− }
149− Spacer(Modifier.height(Dimens.spaceTiny))
150− } else {
151− // Show a timestamp on user bubbles too, aligned to the
152− // end so it reads as the message's send time.
153− if (message.time > 0uL) {
154− Row(
155− modifier = Modifier.fillMaxWidth(),
96+ modifier = Modifier
156− horizontalArrangement = Arrangement.End,
97+ .fillMaxWidth(0.85f)
157− ) {
98+ .widthIn(max = 320.dp)
158− Text(
99+ .clip(shape)
159− text = timeLabel,
100+ .background(bubbleColor)
160− style = MaterialTheme.typography.labelSmall,
101+ .combinedClickable(
161− color = MaterialTheme.colorScheme.onPrimary,
102+ onClick = {},
162− )
103+ onLongClick = {
104+ if (message.text.isNotEmpty()) {
105+ showMenu = true
163 }
106 }
164− Spacer(Modifier.height(Dimens.spaceTiny))
107+ },
108+ )
109+ .padding(horizontal = 14.dp, vertical = 10.dp),
110+ ) {
111+ DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
112+ DropdownMenuItem(
113+ text = { Text("Copy") },
114+ onClick = {
115+ copyToClipboard(context, message.text)
116+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
117+ showMenu = false
118+ },
119+ )
120+ DropdownMenuItem(
121+ text = { Text("Share") },
122+ onClick = {
123+ shareText(context, message.text)
124+ showMenu = false
125+ },
126+ )
127+ }
128+
129+ message.reasoning?.let { ReasoningBlock(it, context) }
130+
131+ // Give a quick overview of how many tools ran before listing them.
132+ if (message.tools.size > 1) {
133+ Text(
134+ text = "${message.tools.size} tool calls",
135+ style = MaterialTheme.typography.labelSmall,
136+ color = MaterialTheme.colorScheme.onSurfaceVariant,
137+ modifier = Modifier.padding(bottom = 4.dp),
138+ )
139+ }
140+
141+ message.tools.forEach { ToolRow(it) }
142+
143+ SelectionContainer {
144+ if (message.text.isNotEmpty()) {
145+ val linkColor = MaterialTheme.colorScheme.primary
146+ // Tint the code background off the bubble's own foreground colour so it
147+ // contrasts on both bubble types (user bubbles use primaryContainer).
148+ val codeBackground = (if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface).copy(alpha = 0.08f)
149+ val annotatedText = remember(message.text, message.streaming, linkColor, codeBackground, context) {
150+ buildLinkedText(message.text, message.streaming, linkColor, codeBackground, context)
165 }
151 }
166− }
167− if (message.text.isBlank()) {
168 Text(
152 Text(
169− text = stringResource(R.string.chat_no_content),
153+ text = annotatedText,
170− style = MaterialTheme.typography.bodyMedium,
154+ color = textColor,
171− fontStyle = FontStyle.Italic,
155+ // Give assistant replies (often long, code-heavy) extra line
172− )
156+ // spacing for readability; user bubbles keep the default.
173− } else if (isUser) {
157+ style = if (isUser) {
174− Text(
158+ MaterialTheme.typography.bodyLarge
175− text = message.text,
159+ } else {
176− style = MaterialTheme.typography.bodyMedium,
160+ MaterialTheme.typography.bodyLarge.copy(lineHeight = 22.sp)
177− )
178− } else {
179− // Assistant replies often contain markdown (code blocks,
180− // lists, etc.) — render them properly.
181− Markdown(
182− content = message.text,
183− modifier = Modifier
184− .fillMaxWidth()
185− .semantics {
186− // Polite live region so streaming edits are
187− // announced without interrupting the user.
188− liveRegion = LiveRegionMode.Polite
189− },
161+ },
190 )
162 )
163+ } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
164+ Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
191 }
165 }
192 }
166 }
167+
168+ if (message.time > 0) {
169+ Text(
170+ text = timeFormat.format(java.time.Instant.ofEpochMilli(message.time).atZone(java.time.ZoneId.systemDefault()).toLocalTime()),
171+ style = MaterialTheme.typography.labelSmall,
172+ color = mutedColor,
173+ modifier = Modifier.padding(top = 4.dp),
174+ )
175+ }
176+
177+ if (isUser && message.status != MessageStatus.Sent) {
178+ StatusLine(message.status, onRetry = onRetry)
179+ }
193 }
180 }
194 }
181 }
195}
182}
196
183
197−@Composable
184+private fun copyToClipboard(context: Context, text: String) {
198−fun GeneratingIndicator(modifier: Modifier = Modifier) {
185+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
199− val maxWidth = maxBubbleWidthDp()
186+ clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
200− val generatingLabel = stringResource(R.string.chat_cd_generating)
187+}
201− val dotColor = MaterialTheme.colorScheme.onSurfaceVariant
188+
202− // Three dots that pulse in sequence: each dot scales/fades with a
189+private val urlRegex = Regex("""https?://[^\s]+""")
203− // staggered delay so the indicator reads as "typing" rather than a
190+
204− // single frozen spinner. One shared infinite transition drives them.
191+/**
205− val transition = rememberInfiniteTransition(label = "generating-dots")
192+ * Render [text] as an AnnotatedString. Triple-backtick fences split the text into
206− val phase1 by transition.animateFloat(
193+ * prose and code segments: code segments are rendered monospace on a tinted
207− initialValue = 0.3f,
194+ * [codeBackground] (fences dropped), while prose has each http(s) URL turned into a
208− targetValue = 1f,
195+ * clickable link. The streaming cursor (" ▌") is appended outside any annotation.
209− animationSpec = infiniteRepeatable(
196+ */
210− animation = tween(durationMillis = 600, delayMillis = 0),
197+private fun buildLinkedText(
211− repeatMode = RepeatMode.Reverse,
198+ text: String,
212− ),
199+ streaming: Boolean,
213− label = "dot-1",
200+ linkColor: Color,
214− )
201+ codeBackground: Color,
215− val phase2 by transition.animateFloat(
202+ context: Context,
216− initialValue = 0.3f,
203+): AnnotatedString = buildAnnotatedString {
217− targetValue = 1f,
204+ // Odd-indexed segments sit between a pair of ``` fences, so they're code. An
218− animationSpec = infiniteRepeatable(
205+ // unclosed fence leaves the trailing segment styled as code, mirroring markdown.
219− animation = tween(durationMillis = 600, delayMillis = 200),
206+ val segments = text.split("```")
220− repeatMode = RepeatMode.Reverse,
207+ segments.forEachIndexed { index, segment ->
221− ),
208+ if (index % 2 == 1) {
222− label = "dot-2",
209+ withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
223− )
210+ append(segment)
224− val phase3 by transition.animateFloat(
225− initialValue = 0.3f,
226− targetValue = 1f,
227− animationSpec = infiniteRepeatable(
228− animation = tween(durationMillis = 600, delayMillis = 400),
229− repeatMode = RepeatMode.Reverse,
230− ),
231− label = "dot-3",
232− )
233− Row(
234− horizontalArrangement = Arrangement.Start,
235− modifier = modifier
236− .fillMaxWidth()
237− .padding(vertical = Dimens.spaceTiny),
238− ) {
239− Surface(
240− color = MaterialTheme.colorScheme.surfaceVariant,
241− contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
242− shape = AssistantBubbleShape,
243− modifier = Modifier.widthIn(max = maxWidth),
244− ) {
245− Row(
246− verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
247− horizontalArrangement = Arrangement.spacedBy(Dimens.spaceTiny),
248− modifier = Modifier
249− .padding(
250− horizontal = Dimens.bubbleHorizontalPadding,
251− vertical = Dimens.bubbleVerticalPadding,
252− )
253− .semantics(mergeDescendants = true) {
254− // Announced when the indicator appears/disappears.
255− liveRegion = LiveRegionMode.Polite
256− contentDescription = generatingLabel
257− },
258− ) {
259− GeneratingDot(alpha = phase1, color = dotColor)
260− GeneratingDot(alpha = phase2, color = dotColor)
261− GeneratingDot(alpha = phase3, color = dotColor)
262 }
211 }
212+ } else {
213+ appendLinkedText(segment, linkColor, codeBackground, context)
263 }
214 }
264 }
215 }
216+ if (streaming) append(" ▌")
265}
217}
266
218
267−@Composable
219+/**
268−private fun GeneratingDot(alpha: Float, color: androidx.compose.ui.graphics.Color) {
220+ * Append [text] to the builder. Double-asterisk pairs are rendered bold; within each
269− // Scale slightly with alpha so the pulse feels like motion, not just a
221+ * segment, single-backtick pairs are rendered as inline code (monospace, backticks
270− // dimmer toggle. alpha drives both the dot's alpha and a small scale.
222+ * dropped), and the remaining prose has each http(s) URL turned into a clickable link.
271− val scale = 0.75f + alpha * 0.25f
223+ * Triple-backtick fences are already stripped upstream in [buildLinkedText], so only
272− androidx.compose.foundation.Canvas(
224+ * inline spans reach here.
273− modifier = Modifier.size(Dimens.iconInlineSpinner),
225+ */
274− ) {
226+private fun AnnotatedString.Builder.appendLinkedText(
275− val diameter = size.minDimension * scale
227+ text: String,
276− drawCircle(
228+ linkColor: Color,
277− color = color.copy(alpha = alpha.coerceIn(0.15f, 1f)),
229+ codeBackground: Color,
278− radius = diameter / 2f,
230+ context: Context,
279− center = androidx.compose.ui.geometry.Offset(size.width / 2f, size.height / 2f),
231+) {
280− )
232+ // Bold is the outermost inline layer: split on ** first so a bold span can wrap
233+ // inline code and links inside it. Odd-indexed segments sit between a pair of **
234+ // markers, so they're bold (markers dropped); even segments are ordinary prose.
235+ // Only the non-bold (even) segments get single-* italic handling — splitting a bold
236+ // segment on "*" would misfire on the leftover asterisks from the ** markers.
237+ val segments = text.split("**")
238+ // An even segment count means an odd number of ** markers, so the final ** is unclosed:
239+ // its trailing segment isn't bold. Restore the literal ** and render it as ordinary prose.
240+ val unclosed = segments.size % 2 == 0
241+ segments.forEachIndexed { index, segment ->
242+ val isUnclosedTail = unclosed && index == segments.size - 1
243+ if (index % 2 == 1 && !isUnclosedTail) {
244+ withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
245+ appendInlineCode(segment, linkColor, codeBackground, context)
246+ }
247+ } else {
248+ if (isUnclosedTail) append("**")
249+ appendItalicText(segment, linkColor, codeBackground, context)
250+ }
281 }
251 }
282}
252}
283
253
284−private fun formatTimestamp(epochSeconds: ULong): String {
254+/**
285− val date = Date(epochSeconds.toLong() * 1000)
255+ * Append [text] to the builder, rendering single-asterisk pairs as italic. Double
286− val formatter = SimpleDateFormat("HH:mm", Locale.getDefault())
256+ * asterisks are already consumed as bold upstream in [appendLinkedText], so only lone
287− return formatter.format(date)
257+ * `*` markers reach here. Each segment then flows through inline-code and URL handling.
258+ */
259+private fun AnnotatedString.Builder.appendItalicText(
260+ text: String,
261+ linkColor: Color,
262+ codeBackground: Color,
263+ context: Context,
264+) {
265+ // Odd-indexed segments sit between a pair of single asterisks, so they're italic
266+ // (markers dropped); even segments are ordinary prose.
267+ val segments = text.split("*")
268+ // An even segment count means an odd number of * markers, so the final * is unclosed:
269+ // its trailing segment isn't italic. Restore the literal * and render it as prose.
270+ val unclosed = segments.size % 2 == 0
271+ segments.forEachIndexed { index, segment ->
272+ val isUnclosedTail = unclosed && index == segments.size - 1
273+ if (index % 2 == 1 && !isUnclosedTail) {
274+ withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
275+ appendInlineCode(segment, linkColor, codeBackground, context)
276+ }
277+ } else {
278+ if (isUnclosedTail) append("*")
279+ appendInlineCode(segment, linkColor, codeBackground, context)
280+ }
281+ }
288}
282}
289
283
290/**
284/**
291− * Max chat-bubble width as a fraction of the window width, in dp. Uses
285+ * Append [text] to the builder, rendering single-backtick pairs as inline code
292− * [LocalWindowInfo] (the recommended window-size source) rather than the
286+ * (monospace, backticks dropped) and turning each http(s) URL in the remaining prose
293− * deprecated [androidx.compose.ui.platform.LocalConfiguration.screenWidthDp].
287+ * into a clickable link.
294 */
288 */
295−@Composable
289+private fun AnnotatedString.Builder.appendInlineCode(
296−private fun maxBubbleWidthDp(): androidx.compose.ui.unit.Dp {
290+ text: String,
297− val containerSize = LocalWindowInfo.current.containerSize
291+ linkColor: Color,
298− val density = LocalDensity.current
292+ codeBackground: Color,
299− return with(density) {
293+ context: Context,
300− containerSize.width.toDp() * Dimens.bubbleMaxWidthFraction
294+) {
295+ // Odd-indexed segments sit between a pair of single backticks, so they're inline
296+ // code. Even segments are ordinary prose and get URL linking applied.
297+ val segments = text.split("`")
298+ // An even segment count means an odd number of backtick markers, so the final backtick
299+ // is unclosed: its trailing segment isn't code. Restore the literal ` and treat as prose.
300+ val unclosed = segments.size % 2 == 0
301+ segments.forEachIndexed { index, segment ->
302+ val isUnclosedTail = unclosed && index == segments.size - 1
303+ if (index % 2 == 1 && !isUnclosedTail) {
304+ withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
305+ append(segment)
306+ }
307+ } else {
308+ if (isUnclosedTail) append("`")
309+ appendUrls(segment, linkColor, context)
310+ }
301 }
311 }
302}
312}
303
313
304−@Preview(showBackground = true)
314+/** Append [text] to the builder, turning each http(s) URL into a clickable link. */
305−@Preview(showBackground = true, uiMode = android.content.res.Configuration.UI_MODE_NIGHT_YES)
315+private fun AnnotatedString.Builder.appendUrls(
306−@Composable
316+ text: String,
307−private fun MessageBubbleUserPreview() {
317+ linkColor: Color,
308− OpencodeTheme {
318+ context: Context,
309− Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
319+) {
310− MessageBubble(
320+ val matches = urlRegex.findAll(text).toList()
311− message = MessageView(
321+ var cursor = 0
312− id = "u1",
322+ for (match in matches) {
313− role = "user",
323+ append(text.substring(cursor, match.range.first))
314− text = "Hello! Can you summarize the build steps?",
324+ val url = match.value
315− time = 1_700_000_000uL,
325+ withLink(
326+ LinkAnnotation.Clickable(
327+ tag = url,
328+ styles = TextLinkStyles(
329+ SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline),
316 ),
330 ),
331+ linkInteractionListener = {
332+ runCatching {
333+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
334+ }
335+ },
336+ ),
337+ ) {
338+ append(url)
339+ }
340+ cursor = match.range.last + 1
341+ }
342+ append(text.substring(cursor))
343+}
344+
345+private fun shareText(context: Context, text: String) {
346+ val intent = Intent(Intent.ACTION_SEND).apply {
347+ type = "text/plain"
348+ putExtra(Intent.EXTRA_TEXT, text)
349+ }
350+ context.startActivity(Intent.createChooser(intent, null))
351+}
352+
353+@Composable
354+private fun ReasoningBlock(text: String, context: Context) {
355+ var expanded by remember { mutableStateOf(false) }
356+ Column(modifier = Modifier.padding(bottom = 6.dp)) {
357+ Row(
358+ verticalAlignment = Alignment.CenterVertically,
359+ modifier = Modifier.clickable { expanded = !expanded },
360+ ) {
361+ Text(
362+ text = if (expanded) "Show less" else "Reasoning",
363+ style = MaterialTheme.typography.bodySmall,
364+ color = MaterialTheme.colorScheme.onSurfaceVariant,
317 )
365 )
318− MessageBubble(
366+ Icon(
319− message = MessageView(
367+ imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
320− id = "a1",
368+ contentDescription = if (expanded) "Collapse reasoning" else "Expand reasoning",
321− role = "assistant",
369+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
322− text = "Sure — here's a **short** list:\n\n1. Generate types\n2. Build the native library\n3. Assemble the APK",
370+ modifier = Modifier.padding(start = 2.dp).widthIn(max = 18.dp),
323− time = 1_700_000_010uL,
371+ )
324− ),
372+ }
373+ if (expanded) {
374+ Text(
375+ text = text,
376+ style = MaterialTheme.typography.bodySmall.copy(fontStyle = FontStyle.Italic),
377+ color = MaterialTheme.colorScheme.onSurfaceVariant,
378+ modifier = Modifier.padding(top = 4.dp),
379+ )
380+ Text(
381+ text = "Copy",
382+ style = MaterialTheme.typography.labelSmall,
383+ color = MaterialTheme.colorScheme.primary,
384+ modifier = Modifier
385+ .padding(top = 4.dp)
386+ .clickable {
387+ copyToClipboard(context, text)
388+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
389+ },
325 )
390 )
326 }
391 }
327 }
392 }
328}
393}
329
394
330−@Preview(showBackground = true)
331@Composable
395@Composable
332−private fun GeneratingIndicatorPreview() {
396+private fun ToolRow(tool: ToolView) {
333− OpencodeTheme {
397+ var expanded by remember { mutableStateOf(false) }
334− GeneratingIndicator()
398+ val baseColor = MaterialTheme.colorScheme.onSurfaceVariant
399+ val statusColor = when (tool.status) {
400+ "completed", "success" -> MaterialTheme.colorScheme.primary
401+ "error", "failed" -> MaterialTheme.colorScheme.error
402+ "pending", "running", "in_progress" -> MaterialTheme.colorScheme.onSurfaceVariant
403+ else -> MaterialTheme.colorScheme.onSurfaceVariant
404+ }
405+ Row(
406+ verticalAlignment = Alignment.CenterVertically,
407+ modifier = Modifier
408+ .fillMaxWidth()
409+ .clickable { expanded = !expanded }
410+ .padding(bottom = 6.dp),
411+ ) {
412+ Icon(
413+ Icons.Filled.Build,
414+ contentDescription = null,
415+ tint = MaterialTheme.colorScheme.primary,
416+ modifier = Modifier.padding(end = 6.dp).widthIn(max = 16.dp),
417+ )
418+ Text(
419+ text = buildAnnotatedString {
420+ withStyle(SpanStyle(color = baseColor)) {
421+ append(tool.name)
422+ append(" · ")
423+ }
424+ withStyle(SpanStyle(color = statusColor)) {
425+ append(tool.status)
426+ }
427+ if (expanded) tool.title?.let {
428+ withStyle(SpanStyle(color = baseColor)) {
429+ append(" — ")
430+ append(it)
431+ }
432+ }
433+ },
434+ style = MonoStyle,
435+ color = baseColor,
436+ maxLines = if (expanded) Int.MAX_VALUE else 1,
437+ overflow = TextOverflow.Ellipsis,
438+ modifier = Modifier.weight(1f),
439+ )
440+ Icon(
441+ imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
442+ contentDescription = if (expanded) "Collapse tool details" else "Expand tool details",
443+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
444+ modifier = Modifier.padding(start = 2.dp).widthIn(max = 18.dp),
445+ )
446+ }
447+}
448+
449+@Composable
450+private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
451+ val (icon, label, tint) = when (status) {
452+ MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
453+ MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
454+ MessageStatus.Sent -> Triple(Icons.Filled.Check, "", Color.Unspecified)
455+ }
456+ Row(
457+ verticalAlignment = Alignment.CenterVertically,
458+ horizontalArrangement = Arrangement.End,
459+ modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
460+ ) {
461+ Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.widthIn(max = 14.dp))
462+ Text(
463+ text = label,
464+ style = MaterialTheme.typography.labelSmall,
465+ color = tint,
466+ modifier = Modifier.padding(start = 4.dp),
467+ )
468+ if (status == MessageStatus.Failed) {
469+ Text(
470+ text = "Retry",
471+ style = MaterialTheme.typography.labelSmall,
472+ color = MaterialTheme.colorScheme.primary,
473+ modifier = Modifier
474+ .padding(start = 12.dp)
475+ .clickable { onRetry() },
476+ )
477+ }
335 }
478 }
336}
479}
app/src/main/java/soy/iko/opencode/ui/components/SseDisconnectedBanner.ktdeleted−88
@@ -1,88 +0,0 @@
1−package soy.iko.opencode.ui.components
2−
3−import androidx.compose.foundation.layout.Arrangement
4−import androidx.compose.foundation.layout.Row
5−import androidx.compose.foundation.layout.fillMaxWidth
6−import androidx.compose.foundation.layout.padding
7−import androidx.compose.material.icons.Icons
8−import androidx.compose.material.icons.filled.CloudOff
9−import androidx.compose.material3.Icon
10−import androidx.compose.material3.MaterialTheme
11−import androidx.compose.material3.Surface
12−import androidx.compose.material3.Text
13−import androidx.compose.material3.TextButton
14−import androidx.compose.runtime.Composable
15−import androidx.compose.ui.Alignment
16−import androidx.compose.ui.Modifier
17−import androidx.compose.ui.semantics.LiveRegionMode
18−import androidx.compose.ui.semantics.contentDescription
19−import androidx.compose.ui.semantics.liveRegion
20−import androidx.compose.ui.semantics.semantics
21−import androidx.compose.ui.tooling.preview.Preview
22−import androidx.compose.ui.unit.dp
23−import soy.iko.opencode.core.SseState
24−import soy.iko.opencode.ui.theme.Dimens
25−import soy.iko.opencode.ui.theme.OpencodeTheme
26−
27−/**
28− * A thin banner shown above the message list when the SSE live stream drops.
29− * Offers a "Reconnect" action. The banner is a polite live region so screen
30− * readers announce the disconnection once.
31− *
32− * Only render this when [SseState] is [SseState.Error] or an unexpected
33− * [SseState.Disconnected] while a chat is active.
34− */
35−@Composable
36−fun SseDisconnectedBanner(
37− message: String,
38− onReconnect: () -> Unit,
39− modifier: Modifier = Modifier,
40− reconnectLabel: String = "Reconnect",
41−) {
42− Surface(
43− color = MaterialTheme.colorScheme.errorContainer,
44− contentColor = MaterialTheme.colorScheme.onErrorContainer,
45− modifier = modifier
46− .fillMaxWidth()
47− .semantics(mergeDescendants = true) {
48− liveRegion = LiveRegionMode.Polite
49− contentDescription = message
50− },
51− ) {
52− Row(
53− verticalAlignment = Alignment.CenterVertically,
54− horizontalArrangement = Arrangement.SpaceBetween,
55− modifier = Modifier
56− .fillMaxWidth()
57− .padding(
58− horizontal = Dimens.spaceLarge,
59− vertical = Dimens.spaceSmall,
60− ),
61− ) {
62− Row(
63− verticalAlignment = Alignment.CenterVertically,
64− horizontalArrangement = Arrangement.spacedBy(Dimens.spaceSmall),
65− modifier = Modifier.weight(1f),
66− ) {
67− Icon(Icons.Default.CloudOff, contentDescription = null)
68− Text(
69− text = message,
70− style = MaterialTheme.typography.bodySmall,
71− maxLines = 2,
72− )
73− }
74− TextButton(onClick = onReconnect) { Text(reconnectLabel) }
75− }
76− }
77−}
78−
79−@Preview(showBackground = true)
80−@Composable
81−private fun SseDisconnectedBannerPreview() {
82− OpencodeTheme {
83− SseDisconnectedBanner(
84− message = "Live stream disconnected",
85− onReconnect = {},
86− )
87− }
88−}
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+481−312
@@ -1,421 +1,590 @@
1package soy.iko.opencode.ui.screens
1package soy.iko.opencode.ui.screens
2
2
3+import android.content.ClipData
4+import android.content.ClipboardManager
5+import android.content.Context
6+import android.widget.Toast
3import androidx.compose.animation.AnimatedVisibility
7import androidx.compose.animation.AnimatedVisibility
8+import androidx.compose.animation.core.RepeatMode
9+import androidx.compose.animation.core.animateFloat
10+import androidx.compose.animation.core.infiniteRepeatable
11+import androidx.compose.animation.core.rememberInfiniteTransition
12+import androidx.compose.animation.core.tween
13+import androidx.compose.animation.fadeIn
14+import androidx.compose.animation.fadeOut
4import androidx.compose.animation.scaleIn
15import androidx.compose.animation.scaleIn
5import androidx.compose.animation.scaleOut
16import androidx.compose.animation.scaleOut
17+import androidx.compose.foundation.ExperimentalFoundationApi
18+import androidx.compose.foundation.background
19+import androidx.compose.foundation.clickable
20+import androidx.compose.foundation.combinedClickable
6import androidx.compose.foundation.layout.Arrangement
21import androidx.compose.foundation.layout.Arrangement
7import androidx.compose.foundation.layout.Box
22import androidx.compose.foundation.layout.Box
23+import androidx.compose.foundation.layout.BoxScope
8import androidx.compose.foundation.layout.Column
24import androidx.compose.foundation.layout.Column
9−import androidx.compose.foundation.layout.PaddingValues
25+import androidx.compose.foundation.layout.Row
26+import androidx.compose.foundation.layout.Spacer
10import androidx.compose.foundation.layout.fillMaxSize
27import androidx.compose.foundation.layout.fillMaxSize
28+import androidx.compose.foundation.layout.fillMaxWidth
29+import androidx.compose.foundation.layout.heightIn
30+import androidx.compose.foundation.layout.PaddingValues
31+import androidx.compose.foundation.layout.WindowInsets
32+import androidx.compose.foundation.layout.ime
33+import androidx.compose.foundation.layout.imePadding
11import androidx.compose.foundation.layout.padding
34import androidx.compose.foundation.layout.padding
35+import androidx.compose.foundation.layout.size
12import androidx.compose.foundation.lazy.LazyColumn
36import androidx.compose.foundation.lazy.LazyColumn
13−import androidx.compose.foundation.lazy.items
37+import androidx.compose.foundation.lazy.itemsIndexed
14import androidx.compose.foundation.lazy.rememberLazyListState
38import androidx.compose.foundation.lazy.rememberLazyListState
39+import androidx.compose.foundation.shape.CircleShape
40+import androidx.compose.foundation.shape.RoundedCornerShape
41+import androidx.compose.foundation.text.KeyboardActions
42+import androidx.compose.foundation.text.KeyboardOptions
15import androidx.compose.material.icons.Icons
43import androidx.compose.material.icons.Icons
16import androidx.compose.material.icons.automirrored.filled.ArrowBack
44import androidx.compose.material.icons.automirrored.filled.ArrowBack
45+import androidx.compose.material.icons.automirrored.filled.Send
46+import androidx.compose.material.icons.filled.ChatBubbleOutline
47+import androidx.compose.material.icons.filled.Close
17import androidx.compose.material.icons.filled.KeyboardArrowDown
48import androidx.compose.material.icons.filled.KeyboardArrowDown
18−import androidx.compose.material.icons.filled.MoreVert
49+import androidx.compose.material.icons.filled.KeyboardArrowUp
19−import androidx.compose.material.icons.filled.Refresh
50+import androidx.compose.material.icons.filled.Stop
20−import androidx.compose.material3.DropdownMenu
51+import androidx.compose.material3.CircularProgressIndicator
21−import androidx.compose.material3.DropdownMenuItem
22import androidx.compose.material3.ExperimentalMaterial3Api
52import androidx.compose.material3.ExperimentalMaterial3Api
23−import androidx.compose.material3.ExtendedFloatingActionButton
53+import androidx.compose.material3.FilledIconButton
54+import androidx.compose.material3.FilledTonalButton
55+import androidx.compose.material3.FloatingActionButton
24import androidx.compose.material3.Icon
56import androidx.compose.material3.Icon
25import androidx.compose.material3.IconButton
57import androidx.compose.material3.IconButton
58+import androidx.compose.material3.LinearProgressIndicator
26import androidx.compose.material3.MaterialTheme
59import androidx.compose.material3.MaterialTheme
60+import androidx.compose.material3.OutlinedTextField
27import androidx.compose.material3.Scaffold
61import androidx.compose.material3.Scaffold
62+import androidx.compose.material3.Surface
28import androidx.compose.material3.Text
63import androidx.compose.material3.Text
64+import androidx.compose.material3.TextButton
29import androidx.compose.material3.TopAppBar
65import androidx.compose.material3.TopAppBar
30import androidx.compose.runtime.Composable
66import androidx.compose.runtime.Composable
31import androidx.compose.runtime.LaunchedEffect
67import androidx.compose.runtime.LaunchedEffect
32−import androidx.compose.runtime.collectAsState
33import androidx.compose.runtime.derivedStateOf
68import androidx.compose.runtime.derivedStateOf
34import androidx.compose.runtime.getValue
69import androidx.compose.runtime.getValue
35−import androidx.compose.runtime.mutableIntStateOf
36import androidx.compose.runtime.mutableStateOf
70import androidx.compose.runtime.mutableStateOf
37import androidx.compose.runtime.remember
71import androidx.compose.runtime.remember
72+import androidx.compose.runtime.rememberCoroutineScope
38import androidx.compose.runtime.setValue
73import androidx.compose.runtime.setValue
39import androidx.compose.ui.Alignment
74import androidx.compose.ui.Alignment
40import androidx.compose.ui.Modifier
75import androidx.compose.ui.Modifier
41−import androidx.compose.ui.focus.FocusRequester
76+import androidx.compose.ui.draw.clip
42−import androidx.compose.ui.focus.focusRequester
77+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
43−import androidx.compose.ui.res.stringResource
78+import androidx.compose.ui.platform.LocalClipboardManager
79+import androidx.compose.ui.platform.LocalContext
80+import androidx.compose.ui.platform.LocalDensity
81+import androidx.compose.ui.platform.LocalHapticFeedback
82+import androidx.compose.ui.text.font.FontStyle
83+import androidx.compose.ui.text.input.ImeAction
84+import androidx.compose.ui.text.style.TextAlign
44import androidx.compose.ui.text.style.TextOverflow
85import androidx.compose.ui.text.style.TextOverflow
45−import androidx.compose.ui.tooling.preview.Preview
46import androidx.compose.ui.unit.dp
86import androidx.compose.ui.unit.dp
47−import soy.iko.opencode.R
87+import kotlinx.coroutines.launch
48−import soy.iko.opencode.core.Core
49import soy.iko.opencode.core.Event
88import soy.iko.opencode.core.Event
50−import soy.iko.opencode.core.MessageView
89+import soy.iko.opencode.core.UiState
51−import soy.iko.opencode.core.SseState
52−import soy.iko.opencode.ui.components.ChatInputBar
53−import soy.iko.opencode.ui.components.DualSnackbarHost
54−import soy.iko.opencode.ui.components.EmptyState
55−import soy.iko.opencode.ui.components.ErrorHost
56−import soy.iko.opencode.ui.components.GeneratingIndicator
57−import soy.iko.opencode.ui.components.InfoHost
58−import soy.iko.opencode.ui.components.LoadingPlaceholder
59import soy.iko.opencode.ui.components.MessageBubble
90import soy.iko.opencode.ui.components.MessageBubble
60−import soy.iko.opencode.ui.components.SseDisconnectedBanner
61−import soy.iko.opencode.ui.theme.Dimens
62−import soy.iko.opencode.ui.theme.OpencodeTheme
63
91
64−@OptIn(ExperimentalMaterial3Api::class)
92+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
65@Composable
93@Composable
66−fun ChatScreen(core: Core) {
94+fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
67− val view by core.view.collectAsState()
68− val sseState by core.sseState.collectAsState()
69− var inputText by remember { mutableStateOf("") }
70 val listState = rememberLazyListState()
95 val listState = rememberLazyListState()
71− var scrollRequest by remember { mutableIntStateOf(0) }
96+ val coroutineScope = rememberCoroutineScope()
72− var menuExpanded by remember { mutableStateOf(false) }
97+ val context = LocalContext.current
73− val inputFocusRequester = remember { FocusRequester() }
74
98
75− // Track whether the user is parked at the bottom of the list. We only
99+ // Hide the jump-to-bottom FAB while the keyboard is up: it would otherwise
76− // auto-scroll when they are, so reading history isn't yanked away as
100+ // sit over the top of the IME. Reading the ime inset bottom during composition
77− // new messages stream in.
101+ // observes snapshot state, so this flips as the keyboard opens/closes.
78− val isAtBottom by remember {
102+ val isImeVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0
79− derivedStateOf {
80− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
81− lastVisible >= view.messages.size - 2
82− }
83− }
84
103
85− LaunchedEffect(view.messages.size) {
104+ // Show a jump-to-bottom button once the user scrolls up away from the latest
86− if (view.messages.isNotEmpty() && (isAtBottom || view.messages.size == 1)) {
105+ // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
87− listState.animateScrollToItem(view.messages.size - 1)
106+ // it only flips when the near-bottom threshold is actually crossed.
107+ val showScrollButton by remember {
108+ derivedStateOf {
109+ val layoutInfo = listState.layoutInfo
110+ val lastVisibleIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
111+ val totalItems = layoutInfo.totalItemsCount
112+ totalItems > 0 && lastVisibleIndex < totalItems - 3
88 }
113 }
89 }
114 }
90
115
91− // Scroll-to-bottom when the user taps the FAB. Keyed on a counter so
116+ // Offer a jump-to-top shortcut once the conversation is long and the user has
92− // repeated taps keep firing.
117+ // scrolled a few messages down — saves flick-scrolling back through history.
93− LaunchedEffect(scrollRequest) {
118+ val showScrollTop by remember {
94− if (scrollRequest > 0 && view.messages.isNotEmpty()) {
119+ derivedStateOf { state.messages.size > 10 && listState.firstVisibleItemIndex > 3 }
95− // Index of the trailing __generating__ item (it's last in the
96− // list, at position == messages.size). Falling back to the last
97− // message is safe even if the generating item is invisible.
98− listState.animateScrollToItem(view.messages.size)
99− }
100 }
120 }
101
121
102− // Auto-focus the input when the chat is empty so the user can start
122+ // Track how many messages the user has "seen" (i.e. was at the bottom for). While
103− // typing immediately without an extra tap. Only request focus once per
123+ // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
104− // session entry — keyed on the session id so switching sessions retriggers.
124+ var lastSeenCount by remember { mutableStateOf(0) }
105− val sessionId = view.currentSessionId
125+ LaunchedEffect(showScrollButton, state.messages.size) {
106− LaunchedEffect(sessionId, view.messages.isEmpty()) {
126+ if (!showScrollButton) {
107− if (sessionId != null && view.messages.isEmpty() && !view.loading && !view.generating) {
127+ lastSeenCount = state.messages.size
108− inputFocusRequester.requestFocus()
109 }
128 }
110 }
129 }
130+ val hasUnseenMessages = showScrollButton && state.messages.size > lastSeenCount
111
131
112− val errorHostState = ErrorHost(
132+ // Keep the newest content in view as it streams in, but only when the user is
113− core = core,
133+ // already near the bottom. If they've scrolled up to read history, leave it alone.
114− dismissLabel = stringResource(R.string.action_dismiss),
134+ val lastLen = state.messages.lastOrNull()?.text?.length ?: 0
115− retryLabel = stringResource(R.string.action_retry),
135+ LaunchedEffect(state.messages.size, lastLen, state.generating) {
116− )
136+ if (state.messages.isNotEmpty()) {
117− val infoHostState = InfoHost(
137+ val layoutInfo = listState.layoutInfo
118− core = core,
138+ val lastVisibleIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
119− successConnectedLabel = stringResource(R.string.connect_success),
139+ val totalItems = layoutInfo.totalItemsCount
120− successSessionCreatedLabel = stringResource(R.string.session_created),
140+ val nearBottom = totalItems == 0 || lastVisibleIndex >= totalItems - 3
121− )
141+ if (nearBottom) {
122−
142+ listState.animateScrollToItem(state.messages.size - 1)
123− val showSseBanner = sseState is SseState.Error ||
124− (sseState == SseState.Disconnected && view.currentSessionId != null && !view.loading)
125−
126− // Resolve nullable session fields into locals once per recomposition so we
127− // never smart-cast a delegate-backed collected property across calls.
128− val sessionTitle = view.currentSessionTitle
129− val chatFallback = stringResource(R.string.top_bar_chat_fallback)
130− val idShortTemplate = stringResource(R.string.chat_session_id_short)
131− val title = remember(sessionId, sessionTitle) {
132− when {
133− sessionTitle.isNotEmpty() -> sessionTitle
134− sessionId != null -> {
135− val prefix = sessionId.take(8)
136− if (sessionId.length > prefix.length) "$prefix…" else prefix
137 }
143 }
138− else -> chatFallback
139 }
144 }
140 }
145 }
141− val subtitle = remember(sessionId, sessionTitle) {
142− if (sessionTitle.isNotEmpty() && sessionId != null) {
143− idShortTemplate.format(sessionId.take(8))
144− } else null
145− }
146−
147− val refreshLabel = stringResource(R.string.chat_menu_refresh)
148− val overflowLabel = stringResource(R.string.chat_menu_overflow)
149− val chatEmptyHint = stringResource(R.string.chat_empty_hint)
150
146
151 Scaffold(
147 Scaffold(
152 topBar = {
148 topBar = {
153 TopAppBar(
149 TopAppBar(
154 title = {
150 title = {
155− Column {
151+ val title = state.currentSessionTitle.ifEmpty { "Chat" }
156− Text(
152+ Text(
157− text = title,
153+ text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
158− maxLines = 1,
154+ maxLines = 1,
159− overflow = TextOverflow.Ellipsis,
155+ overflow = TextOverflow.Ellipsis,
160− )
156+ modifier = Modifier.combinedClickable(
161− if (subtitle != null) {
157+ onClick = { dispatch(Event.NavigateToSessions) },
162− Text(
158+ onLongClick = {
163− text = subtitle,
159+ state.currentSessionId?.let { id ->
164− style = MaterialTheme.typography.labelSmall,
160+ copyToClipboard(context, id)
165− color = MaterialTheme.colorScheme.onSurfaceVariant,
161+ Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
166− maxLines = 1,
162+ }
167− )
163+ },
168− }
164+ ),
169− }
165+ )
170 },
166 },
171 navigationIcon = {
167 navigationIcon = {
172− IconButton(onClick = { core.update(Event.NavigateToSessions) }) {
168+ IconButton(onClick = { dispatch(Event.NavigateToSessions) }) {
173− Icon(
169+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to sessions")
174− Icons.AutoMirrored.Filled.ArrowBack,
175− contentDescription = stringResource(R.string.chat_cd_back),
176− )
177 }
170 }
178 },
171 },
179 actions = {
172 actions = {
180− // Overflow menu with a "Refresh messages" action. Gives
173+ if (state.generating) {
181− // a discoverable manual reload path (e.g. when the SSE
174+ CircularProgressIndicator(
182− // banner has been dismissed) and a home for future items.
175+ modifier = Modifier.padding(end = 16.dp).size(22.dp),
183− Box {
176+ strokeWidth = 2.dp,
184− IconButton(onClick = { menuExpanded = true }) {
177+ )
185− Icon(
186− Icons.Default.MoreVert,
187− contentDescription = overflowLabel,
188− )
189− }
190− DropdownMenu(
191− expanded = menuExpanded,
192− onDismissRequest = { menuExpanded = false },
193− ) {
194− DropdownMenuItem(
195− text = { Text(refreshLabel) },
196− leadingIcon = {
197− Icon(Icons.Default.Refresh, contentDescription = null)
198− },
199− onClick = {
200− menuExpanded = false
201− sessionId?.let { core.update(Event.LoadMessages(it)) }
202− },
203− )
204− }
205 }
178 }
206 },
179 },
207 )
180 )
208 },
181 },
209 bottomBar = {
182 bottomBar = {
210 ChatInputBar(
183 ChatInputBar(
211− text = inputText,
184+ draft = state.draft,
212− onTextChange = { inputText = it },
185+ generating = state.generating,
213− onSend = {
186+ loading = state.loading && state.messages.isEmpty(),
214− if (inputText.isNotBlank()) {
187+ onDraftChange = { dispatch(Event.DraftChanged(it)) },
215− core.update(Event.SendMessage(inputText))
188+ onSend = { dispatch(Event.SendMessage(state.draft)) },
216− inputText = ""
189+ onStop = { dispatch(Event.CancelGeneration) },
217− }
218− },
219− // Disable while loading OR while the assistant is generating,
220− // so users can't fire a second message mid-reply.
221− enabled = !view.loading && !view.generating,
222− placeholder = stringResource(R.string.chat_input_placeholder),
223− sendContentDescription = stringResource(R.string.chat_cd_send),
224− modifier = Modifier.focusRequester(inputFocusRequester),
225 )
190 )
226 },
191 },
227− snackbarHost = { DualSnackbarHost(errorHostState, infoHostState) },
228 ) { padding ->
192 ) { padding ->
229− Box(
193+ Column(Modifier.fillMaxSize().padding(padding)) {
230− modifier = Modifier
194+ if (!state.sseConnected && !state.generating) {
231− .fillMaxSize()
195+ ReconnectingBanner()
232− .padding(padding),
196+ }
233− ) {
197+ if (state.loading && state.messages.isEmpty()) {
234− Column(modifier = Modifier.fillMaxSize()) {
198+ LinearProgressIndicator(Modifier.fillMaxWidth())
235− if (showSseBanner) {
199+ }
236− val bannerMessage = (sseState as? SseState.Error)?.message
200+ if (state.error != null && state.messages.isNotEmpty()) {
237− ?: stringResource(R.string.sse_disconnected)
201+ ErrorBanner(
238− SseDisconnectedBanner(
202+ message = state.error,
239− message = bannerMessage,
203+ onDismiss = { dispatch(Event.DismissError) },
240− onReconnect = { core.reconnectSse() },
204+ )
241− reconnectLabel = stringResource(R.string.sse_reconnect),
205+ }
242− )
206+ Box(Modifier.fillMaxWidth().weight(1f)) {
243− }
207+ if (state.messages.isEmpty() && !state.loading) {
244−
208+ Column(
245− when {
209+ modifier = Modifier.align(Alignment.Center).padding(32.dp),
246− view.loading && view.messages.isEmpty() -> {
210+ horizontalAlignment = Alignment.CenterHorizontally,
247− LoadingPlaceholder()
211+ ) {
212+ Icon(
213+ Icons.Filled.ChatBubbleOutline,
214+ contentDescription = null,
215+ modifier = Modifier.size(48.dp),
216+ tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
217+ )
218+ Spacer(Modifier.size(16.dp))
219+ Text(
220+ text = "Send a message to start the conversation.",
221+ style = MaterialTheme.typography.bodyMedium,
222+ color = MaterialTheme.colorScheme.onSurfaceVariant,
223+ textAlign = TextAlign.Center,
224+ )
248 }
225 }
249− view.messages.isEmpty() -> {
226+ }
250− EmptyState(message = chatEmptyHint)
227+ LazyColumn(
228+ state = listState,
229+ modifier = Modifier.fillMaxSize(),
230+ contentPadding = PaddingValues(vertical = 8.dp),
231+ ) {
232+ itemsIndexed(state.messages, key = { _, message -> message.id }) { index, message ->
233+ // Insert a date separator whenever a message falls on a different
234+ // calendar day than the one before it (and above the first message).
235+ val previous = state.messages.getOrNull(index - 1)
236+ if (shouldShowDateSeparator(previous, message)) {
237+ DateSeparator(message.time)
238+ }
239+ val sameSenderAsPrevious = index > 0 && state.messages[index - 1].isUser == message.isUser
240+ MessageBubble(
241+ message,
242+ onRetry = { dispatch(Event.SendMessage(message.text)) },
243+ compactSpacing = sameSenderAsPrevious,
244+ )
251 }
245 }
252− else -> {
246+ // While the assistant is spinning up but hasn't emitted a streaming
253− // Pull-to-refresh lets the user manually reload
247+ // message yet (only the user's message is present), show a typing
254− // messages, e.g. when the SSE stream stalled and the
248+ // indicator so the wait doesn't look like a stall.
255− // banner was dismissed. Mirrors the Sessions screen.
249+ if (state.generating && state.messages.none { it.streaming }) {
256− androidx.compose.material3.pulltorefresh.PullToRefreshBox(
250+ item(key = "typing-indicator") {
257− isRefreshing = view.loading,
251+ TypingIndicator()
258− onRefresh = { sessionId?.let { core.update(Event.LoadMessages(it)) } },
259− modifier = Modifier.fillMaxSize(),
260− ) {
261− LazyColumn(
262− state = listState,
263− modifier = Modifier
264− .fillMaxSize()
265− .padding(horizontal = Dimens.listHorizontalPadding),
266− verticalArrangement = Arrangement.spacedBy(Dimens.listItemSpacing),
267− contentPadding = PaddingValues(vertical = Dimens.listVerticalPadding),
268− ) {
269− items(view.messages, key = { it.id }) { message ->
270− MessageBubble(message)
271− }
272− // "Thinking" indicator shown after the user sends, while
273− // the assistant reply hasn't arrived yet. The indicator
274− // itself animates (pulsing dots), so we don't wrap it in
275− // AnimatedVisibility — an outer ColumnScope receiver from
276− // the chat Column would shadow the LazyItemScope here and
277− // break AnimatedVisibility overload resolution.
278− if (view.generating) {
279− item(key = "__generating__") {
280− GeneratingIndicator()
281− }
282− }
283− }
284 }
252 }
285 }
253 }
286 }
254 }
255+ ScrollToBottomButton(
256+ visible = showScrollButton && !isImeVisible,
257+ showBadge = hasUnseenMessages,
258+ onClick = {
259+ coroutineScope.launch {
260+ if (state.messages.isNotEmpty()) {
261+ // When the typing indicator is showing it occupies the item
262+ // just past the last message, so scroll one further to reach it.
263+ val target = if (state.generating && state.messages.none { it.streaming })
264+ state.messages.size
265+ else
266+ state.messages.size - 1
267+ listState.animateScrollToItem(target)
268+ }
269+ }
270+ },
271+ )
272+ ScrollToTopButton(
273+ visible = showScrollTop,
274+ onClick = {
275+ coroutineScope.launch {
276+ listState.animateScrollToItem(0)
277+ }
278+ },
279+ )
287 }
280 }
281+ }
282+ }
283+}
288
284
289− // Scroll-to-bottom FAB: only when the user has scrolled up away
285+// Extracted into a BoxScope extension so the top-level AnimatedVisibility overload
290− // from the latest message and there's content to scroll to.
286+// resolves cleanly. Called inline inside a Column, the enclosing ColumnScope receiver
291− // Animated so it scales in/out rather than popping.
287+// would otherwise capture the ColumnScope.AnimatedVisibility overload and fail to compile.
292− AnimatedVisibility(
288+@Composable
293− visible = view.messages.isNotEmpty() && !isAtBottom,
289+private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean, onClick: () -> Unit) {
294− enter = scaleIn(),
290+ AnimatedVisibility(
295− exit = scaleOut(),
291+ visible = visible,
296− modifier = Modifier.align(Alignment.BottomEnd),
292+ modifier = Modifier.align(Alignment.BottomEnd),
293+ enter = scaleIn() + fadeIn(),
294+ exit = scaleOut() + fadeOut(),
295+ ) {
296+ Box(Modifier.padding(16.dp)) {
297+ FloatingActionButton(
298+ onClick = onClick,
299+ modifier = Modifier.size(44.dp),
297 ) {
300 ) {
298− ExtendedFloatingActionButton(
301+ Icon(
299− onClick = { scrollRequest++ },
302+ Icons.Filled.KeyboardArrowDown,
300− icon = {
303+ contentDescription = "Scroll to latest message",
301− Icon(
304+ )
302− Icons.Default.KeyboardArrowDown,
305+ }
303− contentDescription = stringResource(R.string.chat_cd_scroll_to_bottom),
306+ if (showBadge) {
304− )
307+ Box(
305− },
306− text = { Text(stringResource(R.string.chat_cd_scroll_to_bottom)) },
307− containerColor = MaterialTheme.colorScheme.primaryContainer,
308− contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
309 modifier = Modifier
308 modifier = Modifier
310− .padding(
309+ .align(Alignment.TopEnd)
311− end = Dimens.fabEndMargin,
310+ .size(8.dp)
312− bottom = Dimens.fabBottomMargin,
311+ .clip(CircleShape)
313− ),
312+ .background(MaterialTheme.colorScheme.error),
314 )
313 )
315 }
314 }
316 }
315 }
317 }
316 }
318}
317}
319
318
320−@OptIn(ExperimentalMaterial3Api::class)
319+// Mirror of ScrollToBottomButton, pinned to the top-start corner. Same BoxScope
321−@Preview(showBackground = true)
320+// extension trick so the top-level AnimatedVisibility overload resolves cleanly.
322−@Preview(showBackground = true, uiMode = android.content.res.Configuration.UI_MODE_NIGHT_YES)
323@Composable
321@Composable
324−private fun ChatScreenPreview() {
322+private fun BoxScope.ScrollToTopButton(visible: Boolean, onClick: () -> Unit) {
325− OpencodeTheme {
323+ AnimatedVisibility(
326− PreviewChatScreen(
324+ visible = visible,
327− title = "Refactor the parser",
325+ modifier = Modifier.align(Alignment.TopStart),
328− sessionId = "abc12345",
326+ enter = scaleIn() + fadeIn(),
329− messages = listOf(
327+ exit = scaleOut() + fadeOut(),
330− MessageView("u1", "user", "Can you clean up parse_messages?", 1_700_000_000uL),
328+ ) {
331− MessageView(
329+ Box(Modifier.padding(16.dp)) {
332− "a1",
330+ FloatingActionButton(
333− "assistant",
331+ onClick = onClick,
334− "Sure — here's a **plan**:\n\n1. Extract helpers\n2. Add tests",
332+ modifier = Modifier.size(44.dp),
335− 1_700_000_010uL,
333+ ) {
336− ),
334+ Icon(
337− ),
335+ Icons.Filled.KeyboardArrowUp,
338− generating = false,
336+ contentDescription = "Scroll to top",
339− )
337+ )
338+ }
339+ }
340+ }
341+}
342+
343+private fun copyToClipboard(context: Context, text: String) {
344+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
345+ clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
346+}
347+
348+private val dateSeparatorFormat = java.time.format.DateTimeFormatter.ofPattern("MMM d")
349+
350+/** Convert an epoch-millis timestamp to the local calendar day it falls on. */
351+private fun localDayOf(epochMillis: Long): java.time.LocalDate =
352+ java.time.Instant.ofEpochMilli(epochMillis)
353+ .atZone(java.time.ZoneId.systemDefault())
354+ .toLocalDate()
355+
356+/**
357+ * A separator is shown above a message when it starts a new calendar day — i.e. the
358+ * first timestamped message, or one whose day differs from the previous message's.
359+ * Messages without a valid time (time <= 0) never get one.
360+ */
361+private fun shouldShowDateSeparator(previous: soy.iko.opencode.core.MessageView?, current: soy.iko.opencode.core.MessageView): Boolean {
362+ if (current.time <= 0) return false
363+ if (previous == null || previous.time <= 0) return true
364+ return localDayOf(previous.time) != localDayOf(current.time)
365+}
366+
367+/** Human-friendly day label: "Today", "Yesterday", or "MMM d" (e.g. "Jul 8"). */
368+private fun dateSeparatorLabel(day: java.time.LocalDate): String {
369+ val today = java.time.LocalDate.now()
370+ return when (day) {
371+ today -> "Today"
372+ today.minusDays(1) -> "Yesterday"
373+ else -> day.format(dateSeparatorFormat)
340 }
374 }
341}
375}
342
376
343−@OptIn(ExperimentalMaterial3Api::class)
344−@Preview(showBackground = true)
345@Composable
377@Composable
346−private fun ChatScreenGeneratingPreview() {
378+private fun DateSeparator(epochMillis: Long) {
347− OpencodeTheme {
379+ Text(
348− PreviewChatScreen(
380+ text = dateSeparatorLabel(localDayOf(epochMillis)),
349− title = "New session",
381+ style = MaterialTheme.typography.labelSmall,
350− sessionId = "xyz12345",
382+ color = MaterialTheme.colorScheme.onSurfaceVariant,
351− messages = listOf(MessageView("u1", "user", "Hello!", 1_700_000_000uL)),
383+ textAlign = TextAlign.Center,
352− generating = true,
384+ modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
353− )
385+ )
386+}
387+
388+// Assistant-style bubble with three sequentially-pulsing dots, shown as a stand-in
389+// until the real streaming reply starts. Mirrors MessageBubble's left-aligned,
390+// surfaceVariant look so it reads as an incoming message.
391+@Composable
392+private fun TypingIndicator() {
393+ val shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp, bottomStart = 4.dp, bottomEnd = 16.dp)
394+ val transition = rememberInfiniteTransition(label = "typing")
395+ Row(
396+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
397+ horizontalArrangement = Arrangement.Start,
398+ ) {
399+ Row(
400+ modifier = Modifier
401+ .clip(shape)
402+ .background(MaterialTheme.colorScheme.surfaceVariant)
403+ .padding(horizontal = 14.dp, vertical = 12.dp),
404+ verticalAlignment = Alignment.CenterVertically,
405+ horizontalArrangement = Arrangement.spacedBy(6.dp),
406+ ) {
407+ Text(
408+ text = "Thinking",
409+ style = MaterialTheme.typography.bodyMedium.copy(fontStyle = FontStyle.Italic),
410+ color = MaterialTheme.colorScheme.onSurfaceVariant,
411+ )
412+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
413+ // Stagger the three dots so they fade in and out in sequence.
414+ listOf(0, 150, 300).forEach { staggerMs ->
415+ val alpha by transition.animateFloat(
416+ initialValue = 0.2f,
417+ targetValue = 1f,
418+ animationSpec = infiniteRepeatable(
419+ animation = tween(durationMillis = 600, delayMillis = staggerMs),
420+ repeatMode = RepeatMode.Reverse,
421+ ),
422+ label = "dot",
423+ )
424+ Box(
425+ modifier = Modifier
426+ .size(6.dp)
427+ .clip(CircleShape)
428+ .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)),
429+ )
430+ }
431+ }
432+ }
354 }
433 }
355}
434}
356
435
357−@OptIn(ExperimentalMaterial3Api::class)
358−@Preview(showBackground = true)
359@Composable
436@Composable
360−private fun ChatScreenEmptyPreview() {
437+private fun ReconnectingBanner() {
361− OpencodeTheme {
438+ Surface(
362− PreviewChatScreen(title = "", sessionId = null, messages = emptyList(), generating = false)
439+ modifier = Modifier.fillMaxWidth(),
440+ color = MaterialTheme.colorScheme.tertiaryContainer,
441+ ) {
442+ Row(
443+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
444+ verticalAlignment = Alignment.CenterVertically,
445+ horizontalArrangement = Arrangement.spacedBy(8.dp),
446+ ) {
447+ CircularProgressIndicator(
448+ modifier = Modifier.size(14.dp),
449+ strokeWidth = 2.dp,
450+ color = MaterialTheme.colorScheme.onTertiaryContainer,
451+ )
452+ Text(
453+ text = "Reconnecting…",
454+ style = MaterialTheme.typography.bodySmall,
455+ color = MaterialTheme.colorScheme.onTertiaryContainer,
456+ )
457+ }
363 }
458 }
364}
459}
365
460
366−@OptIn(ExperimentalMaterial3Api::class)
367@Composable
461@Composable
368−private fun PreviewChatScreen(
462+private fun ErrorBanner(message: String, onDismiss: () -> Unit) {
369− title: String,
463+ Surface(
370− sessionId: String?,
464+ modifier = Modifier.fillMaxWidth(),
371− messages: List<MessageView>,
465+ color = MaterialTheme.colorScheme.errorContainer,
372− generating: Boolean,
466+ ) {
373−) {
467+ Row(
374− val resolvedTitle = when {
468+ modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 6.dp, bottom = 6.dp, end = 4.dp),
375− title.isNotEmpty() -> title
469+ verticalAlignment = Alignment.CenterVertically,
376− sessionId != null -> {
470+ horizontalArrangement = Arrangement.spacedBy(8.dp),
377− val prefix = sessionId.take(8)
471+ ) {
378− if (sessionId.length > prefix.length) "$prefix…" else prefix
472+ Text(
473+ text = message,
474+ style = MaterialTheme.typography.bodySmall,
475+ color = MaterialTheme.colorScheme.onErrorContainer,
476+ modifier = Modifier.weight(1f),
477+ )
478+ IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
479+ Icon(
480+ Icons.Filled.Close,
481+ contentDescription = "Dismiss error",
482+ tint = MaterialTheme.colorScheme.onErrorContainer,
483+ modifier = Modifier.size(18.dp),
484+ )
485+ }
379 }
486 }
380− else -> "Chat"
381 }
487 }
382− Scaffold(
488+}
383− topBar = {
489+
384− TopAppBar(
490+@Composable
385− title = {
491+private fun ChatInputBar(
386− Text(
492+ draft: String,
387− text = resolvedTitle,
493+ generating: Boolean,
388− maxLines = 1,
494+ loading: Boolean,
389− overflow = TextOverflow.Ellipsis,
495+ onDraftChange: (String) -> Unit,
390− )
496+ onSend: () -> Unit,
497+ onStop: () -> Unit,
498+) {
499+ val haptic = LocalHapticFeedback.current
500+ val clipboardManager = LocalClipboardManager.current
501+ Surface(tonalElevation = 3.dp) {
502+ Column(
503+ modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504+ ) {
505+ Row(
506+ modifier = Modifier.fillMaxWidth(),
507+ verticalAlignment = Alignment.Bottom,
508+ horizontalArrangement = Arrangement.spacedBy(8.dp),
509+ ) {
510+ OutlinedTextField(
511+ value = draft,
512+ onValueChange = onDraftChange,
513+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
514+ enabled = !loading,
515+ placeholder = { Text("Message opencode…") },
516+ maxLines = 5,
517+ // Offer a quick way to wipe the draft once there's something to clear
518+ // and we're not mid-generation (where the field is a poor place to fuss).
519+ trailingIcon = if (draft.isNotEmpty() && !generating) {
520+ {
521+ IconButton(
522+ onClick = { onDraftChange("") },
523+ modifier = Modifier.size(20.dp),
524+ ) {
525+ Icon(
526+ Icons.Filled.Close,
527+ contentDescription = "Clear draft",
528+ modifier = Modifier.size(16.dp),
529+ )
530+ }
531+ }
532+ } else {
533+ null
391 },
534 },
392− navigationIcon = {
535+ // Surface a running count once the draft gets long, so the user has a
393− IconButton(onClick = {}) {
536+ // sense of scale before sending a wall of text.
394− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
537+ supportingText = if (draft.length > 500) {
538+ {
539+ Text(
540+ text = "${draft.length} characters",
541+ style = MaterialTheme.typography.labelSmall,
542+ color = MaterialTheme.colorScheme.onSurfaceVariant,
543+ textAlign = TextAlign.End,
544+ modifier = Modifier.fillMaxWidth(),
545+ )
395 }
546 }
547+ } else {
548+ null
396 },
549 },
550+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551+ keyboardActions = KeyboardActions(onSend = {
552+ if (!generating && !loading && draft.isNotBlank()) onSend()
553+ }),
397 )
554 )
398− },
555+ if (generating) {
399− bottomBar = {
556+ FilledTonalButton(onClick = onStop) {
400− ChatInputBar(text = "", onTextChange = {}, onSend = {}, enabled = true)
557+ Icon(
401− },
558+ Icons.Filled.Stop,
402− ) { padding ->
559+ contentDescription = null,
403− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
560+ modifier = Modifier.size(18.dp),
404− when {
561+ )
405− messages.isEmpty() -> EmptyState(message = "Send a message to start chatting")
562+ Spacer(Modifier.size(6.dp))
406− else -> {
563+ Text("Stop")
407− LazyColumn(
564+ }
408− modifier = Modifier.fillMaxSize().padding(horizontal = 12.dp),
565+ } else {
409− verticalArrangement = Arrangement.spacedBy(8.dp),
566+ FilledIconButton(
410− contentPadding = PaddingValues(vertical = 12.dp),
567+ onClick = {
411− ) {
568+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
412− items(messages, key = { it.id }) { MessageBubble(it) }
569+ onSend()
413− if (generating) {
570+ },
414− item(key = "__generating__") { GeneratingIndicator() }
571+ enabled = draft.isNotBlank() && !loading,
415− }
572+ ) {
416− }
573+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
417 }
574 }
418 }
575 }
419 }
576 }
577+ // With nothing typed yet, offer a one-tap way to drop in clipboard contents.
578+ if (draft.isEmpty() && !generating && !loading) {
579+ TextButton(
580+ onClick = {
581+ clipboardManager.getText()?.text?.let { onDraftChange(it) }
582+ },
583+ contentPadding = PaddingValues(0.dp),
584+ ) {
585+ Text("Paste")
586+ }
587+ }
588+ }
420 }
589 }
421}
590}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+155−264
@@ -1,13 +1,12 @@
1package soy.iko.opencode.ui.screens
1package soy.iko.opencode.ui.screens
2
2
3−import androidx.compose.animation.AnimatedVisibility
4import androidx.compose.foundation.layout.Arrangement
3import androidx.compose.foundation.layout.Arrangement
5import androidx.compose.foundation.layout.Column
4import androidx.compose.foundation.layout.Column
6−import androidx.compose.foundation.layout.Row
7import androidx.compose.foundation.layout.Spacer
5import androidx.compose.foundation.layout.Spacer
8import androidx.compose.foundation.layout.fillMaxSize
6import androidx.compose.foundation.layout.fillMaxSize
9import androidx.compose.foundation.layout.fillMaxWidth
7import androidx.compose.foundation.layout.fillMaxWidth
10import androidx.compose.foundation.layout.height
8import androidx.compose.foundation.layout.height
9+import androidx.compose.foundation.layout.imePadding
11import androidx.compose.foundation.layout.padding
10import androidx.compose.foundation.layout.padding
12import androidx.compose.foundation.layout.size
11import androidx.compose.foundation.layout.size
13import androidx.compose.foundation.rememberScrollState
12import androidx.compose.foundation.rememberScrollState
@@ -15,26 +14,20 @@ import androidx.compose.foundation.text.KeyboardActions
15import androidx.compose.foundation.text.KeyboardOptions
14import androidx.compose.foundation.text.KeyboardOptions
16import androidx.compose.foundation.verticalScroll
15import androidx.compose.foundation.verticalScroll
17import androidx.compose.material.icons.Icons
16import androidx.compose.material.icons.Icons
18−import androidx.compose.material.icons.filled.Dns
19import androidx.compose.material.icons.filled.Lock
17import androidx.compose.material.icons.filled.Lock
18+import androidx.compose.material.icons.filled.Person
19+import androidx.compose.material.icons.filled.Terminal
20import androidx.compose.material.icons.filled.Visibility
20import androidx.compose.material.icons.filled.Visibility
21import androidx.compose.material.icons.filled.VisibilityOff
21import androidx.compose.material.icons.filled.VisibilityOff
22−import androidx.compose.material.icons.filled.Warning
23import androidx.compose.material3.Button
22import androidx.compose.material3.Button
24import androidx.compose.material3.CircularProgressIndicator
23import androidx.compose.material3.CircularProgressIndicator
25−import androidx.compose.material3.ExperimentalMaterial3Api
26import androidx.compose.material3.Icon
24import androidx.compose.material3.Icon
27import androidx.compose.material3.IconButton
25import androidx.compose.material3.IconButton
28import androidx.compose.material3.MaterialTheme
26import androidx.compose.material3.MaterialTheme
29import androidx.compose.material3.OutlinedTextField
27import androidx.compose.material3.OutlinedTextField
30−import androidx.compose.material3.Scaffold
31−import androidx.compose.material3.SnackbarHostState
32import androidx.compose.material3.Text
28import androidx.compose.material3.Text
33−import androidx.compose.material3.TextButton
34−import androidx.compose.material3.TopAppBar
35import androidx.compose.runtime.Composable
29import androidx.compose.runtime.Composable
36import androidx.compose.runtime.LaunchedEffect
30import androidx.compose.runtime.LaunchedEffect
37−import androidx.compose.runtime.collectAsState
38import androidx.compose.runtime.getValue
31import androidx.compose.runtime.getValue
39import androidx.compose.runtime.mutableStateOf
32import androidx.compose.runtime.mutableStateOf
40import androidx.compose.runtime.remember
33import androidx.compose.runtime.remember
@@ -43,289 +36,187 @@ import androidx.compose.ui.Alignment
43import androidx.compose.ui.Modifier
36import androidx.compose.ui.Modifier
44import androidx.compose.ui.focus.FocusRequester
37import androidx.compose.ui.focus.FocusRequester
45import androidx.compose.ui.focus.focusRequester
38import androidx.compose.ui.focus.focusRequester
46−import androidx.compose.ui.res.pluralStringResource
47−import androidx.compose.ui.res.stringResource
48import androidx.compose.ui.text.input.ImeAction
39import androidx.compose.ui.text.input.ImeAction
49import androidx.compose.ui.text.input.KeyboardType
40import androidx.compose.ui.text.input.KeyboardType
50import androidx.compose.ui.text.input.PasswordVisualTransformation
41import androidx.compose.ui.text.input.PasswordVisualTransformation
51import androidx.compose.ui.text.input.VisualTransformation
42import androidx.compose.ui.text.input.VisualTransformation
52−import androidx.compose.ui.tooling.preview.Preview
43+import androidx.compose.ui.text.style.TextAlign
53import androidx.compose.ui.unit.dp
44import androidx.compose.ui.unit.dp
54−import soy.iko.opencode.CrashLogger
55−import soy.iko.opencode.R
56−import soy.iko.opencode.core.Core
57import soy.iko.opencode.core.Event
45import soy.iko.opencode.core.Event
58−import soy.iko.opencode.ui.components.CrashLogDialog
46+import soy.iko.opencode.core.UiState
59−import soy.iko.opencode.ui.components.DualSnackbarHost
60−import soy.iko.opencode.ui.components.ErrorHost
61−import soy.iko.opencode.ui.components.ErrorSnackbarHost
62−import soy.iko.opencode.ui.components.InfoHost
63−import soy.iko.opencode.ui.components.InfoSnackbarHost
64−import soy.iko.opencode.ui.theme.Dimens
65
47
66−@OptIn(ExperimentalMaterial3Api::class)
67@Composable
48@Composable
68−fun ConnectScreen(core: Core) {
49+fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
69− val view by core.view.collectAsState()
50+ val focusRequester = remember { FocusRequester() }
70− val crashCount by CrashLogger.reportCount.collectAsState()
71− var url by remember(view.serverUrl) { mutableStateOf(view.serverUrl) }
72− var username by remember(view.username) { mutableStateOf(view.username) }
73− var password by remember(view.password) { mutableStateOf(view.password) }
74 var passwordVisible by remember { mutableStateOf(false) }
51 var passwordVisible by remember { mutableStateOf(false) }
75− var showCrashLogs by remember { mutableStateOf(false) }
76− var urlError by remember { mutableStateOf(false) }
77− val errorHostState = ErrorHost(
78− core = core,
79− dismissLabel = stringResource(R.string.action_dismiss),
80− retryLabel = stringResource(R.string.action_retry),
81− )
82− val infoHostState = InfoHost(
83− core = core,
84− successConnectedLabel = stringResource(R.string.connect_success),
85− successSessionCreatedLabel = stringResource(R.string.session_created),
86− )
87
52
88− // Auto-focus the username field when the server reveals it requires
53+ // Focus the server URL field when the screen opens, but only when it's empty
89− // authentication, so the user doesn't have to tap into it manually.
54+ // so we don't steal focus (and pop the keyboard) on a return visit.
90− val usernameFocusRequester = remember { FocusRequester() }
55+ LaunchedEffect(Unit) {
91− LaunchedEffect(view.authRequired) {
56+ if (state.serverUrl.isEmpty()) focusRequester.requestFocus()
92− if (view.authRequired) {
93− usernameFocusRequester.requestFocus()
94− }
95 }
57 }
96
58
97− fun isValidUrl(value: String): Boolean {
59+ Column(
98− val trimmed = value.trim()
60+ modifier = Modifier
99− if (trimmed.isEmpty()) return false
61+ .fillMaxSize()
100− return trimmed.startsWith("http://", ignoreCase = true) ||
62+ .verticalScroll(rememberScrollState())
101− trimmed.startsWith("https://", ignoreCase = true)
63+ .imePadding()
102− }
64+ .padding(horizontal = 28.dp),
65+ verticalArrangement = Arrangement.Center,
66+ horizontalAlignment = Alignment.CenterHorizontally,
67+ ) {
68+ Icon(
69+ Icons.Filled.Terminal,
70+ contentDescription = null,
71+ tint = MaterialTheme.colorScheme.primary,
72+ modifier = Modifier.size(72.dp),
73+ )
74+ Spacer(Modifier.height(16.dp))
75+ Text(
76+ text = "opencode",
77+ style = MaterialTheme.typography.displaySmall,
78+ color = MaterialTheme.colorScheme.primary,
79+ )
80+ Text(
81+ text = "Connect to your opencode server",
82+ style = MaterialTheme.typography.bodyMedium,
83+ color = MaterialTheme.colorScheme.onSurfaceVariant,
84+ textAlign = TextAlign.Center,
85+ )
103
86
104− fun submit() {
87+ Spacer(Modifier.height(32.dp))
105− val trimmedUrl = url.trim()
106− if (!isValidUrl(trimmedUrl)) {
107− urlError = true
108− return
109− }
110− urlError = false
111− url = trimmedUrl
112− core.update(Event.ServerUrlChanged(trimmedUrl))
113− if (view.authRequired || username.isNotBlank() || password.isNotBlank()) {
114− core.update(Event.UsernameChanged(username.trim()))
115− core.update(Event.PasswordChanged(password))
116− }
117− core.update(Event.Connect)
118− }
119
88
120− Scaffold(
89+ OutlinedTextField(
121− topBar = {
90+ value = state.serverUrl,
122− TopAppBar(title = { Text(stringResource(R.string.top_bar_connect)) })
91+ onValueChange = { dispatch(Event.ServerUrlChanged(it)) },
123− },
92+ label = { Text("Server URL") },
124− snackbarHost = {
93+ placeholder = { Text("http://192.168.1.10:4096") },
125− DualSnackbarHost(errorHostState, infoHostState)
94+ singleLine = true,
126− },
95+ modifier = Modifier.fillMaxWidth().focusRequester(focusRequester),
127− ) { padding ->
96+ keyboardOptions = KeyboardOptions(
128− Column(
97+ keyboardType = KeyboardType.Uri,
129− horizontalAlignment = Alignment.CenterHorizontally,
98+ imeAction = if (state.authRequired) ImeAction.Next else ImeAction.Go,
130− verticalArrangement = Arrangement.Center,
99+ ),
131− modifier = Modifier
100+ keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
132− .fillMaxSize()
101+ enabled = !state.loading,
133− .padding(padding)
102+ )
134− .padding(Dimens.screenPadding)
103+
135− .verticalScroll(rememberScrollState()),
104+ // Point first-time users at the expected address format. Hidden once they
136− ) {
105+ // start typing so it doesn't compete with the field's own contents.
137− Icon(
106+ if (state.serverUrl.isEmpty()) {
138− imageVector = Icons.Default.Dns,
107+ Spacer(Modifier.height(6.dp))
139− contentDescription = stringResource(R.string.connect_cd_dns),
108+ Text(
140− modifier = Modifier.size(Dimens.iconHero),
109+ text = "Enter the URL of your opencode server (e.g. http://192.168.1.10:4096)",
141− tint = MaterialTheme.colorScheme.primary,
110+ style = MaterialTheme.typography.bodySmall,
111+ color = MaterialTheme.colorScheme.onSurfaceVariant,
112+ textAlign = TextAlign.Center,
142 )
113 )
143− Spacer(Modifier.height(Dimens.spaceLarge))
114+ }
115+
116+ // Nudge the user if the URL looks like it's missing a scheme — a bare host:port
117+ // won't connect. Informational (tertiary), not an error, since it's a heuristic.
118+ if (state.serverUrl.isNotBlank() && "://" !in state.serverUrl && !state.serverUrl.startsWith("http")) {
119+ Spacer(Modifier.height(6.dp))
144 Text(
120 Text(
145− text = stringResource(R.string.connect_heading),
121+ text = "Tip: Add http:// if connecting to a local server",
146− style = MaterialTheme.typography.headlineSmall,
122+ style = MaterialTheme.typography.bodySmall,
123+ color = MaterialTheme.colorScheme.tertiary,
124+ textAlign = TextAlign.Center,
147 )
125 )
148− Spacer(Modifier.height(Dimens.spaceXLarge))
126+ }
127+
128+ if (state.authRequired) {
129+ Spacer(Modifier.height(12.dp))
149 OutlinedTextField(
130 OutlinedTextField(
150− value = url,
131+ value = state.username,
151− onValueChange = {
132+ onValueChange = { dispatch(Event.UsernameChanged(it)) },
152− url = it
133+ label = { Text("Username") },
153− if (urlError) urlError = false
154− },
155− label = { Text(stringResource(R.string.connect_field_server_url)) },
156 singleLine = true,
134 singleLine = true,
157− isError = urlError,
135+ leadingIcon = { Icon(Icons.Filled.Person, contentDescription = null) },
158− supportingText = if (urlError) {
159− { Text(stringResource(R.string.connect_error_invalid_url)) }
160− } else null,
161− keyboardOptions = KeyboardOptions(
162− keyboardType = KeyboardType.Uri,
163− imeAction = ImeAction.Go,
164− ),
165− keyboardActions = KeyboardActions(onGo = { submit() }),
166 modifier = Modifier.fillMaxWidth(),
136 modifier = Modifier.fillMaxWidth(),
137+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
138+ enabled = !state.loading,
167 )
139 )
168−
140+ Spacer(Modifier.height(12.dp))
169− AnimatedVisibility(visible = view.authRequired) {
141+ OutlinedTextField(
170− Column(
142+ value = state.password,
171− horizontalAlignment = Alignment.CenterHorizontally,
143+ onValueChange = { dispatch(Event.PasswordChanged(it)) },
172− modifier = Modifier.fillMaxWidth().padding(top = Dimens.spaceSmall),
144+ label = { Text("Password") },
173− ) {
145+ singleLine = true,
174− Text(
146+ visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
175− text = stringResource(R.string.connect_auth_required),
147+ leadingIcon = { Icon(Icons.Filled.Lock, contentDescription = null) },
176− style = MaterialTheme.typography.bodyMedium,
148+ trailingIcon = {
177− color = MaterialTheme.colorScheme.error,
149+ IconButton(onClick = { passwordVisible = !passwordVisible }) {
178− )
150+ Icon(
179− Spacer(Modifier.height(Dimens.spaceSmall))
151+ imageVector = if (passwordVisible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
180− OutlinedTextField(
152+ contentDescription = if (passwordVisible) "Hide password" else "Show password",
181− value = username,
153+ )
182− onValueChange = { username = it },
183− label = { Text(stringResource(R.string.connect_field_username)) },
184− singleLine = true,
185− leadingIcon = {
186− Icon(
187− Icons.Default.Lock,
188− contentDescription = stringResource(R.string.connect_cd_lock),
189− )
190− },
191− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
192− modifier = Modifier
193− .fillMaxWidth()
194− .focusRequester(usernameFocusRequester),
195− )
196− Spacer(Modifier.height(Dimens.spaceSmall))
197− OutlinedTextField(
198− value = password,
199− onValueChange = { password = it },
200− label = { Text(stringResource(R.string.connect_field_password)) },
201− singleLine = true,
202− visualTransformation = if (passwordVisible) {
203− VisualTransformation.None
204− } else {
205− PasswordVisualTransformation()
206− },
207− trailingIcon = {
208− IconButton(onClick = { passwordVisible = !passwordVisible }) {
209− Icon(
210− if (passwordVisible) {
211− Icons.Default.VisibilityOff
212− } else {
213− Icons.Default.Visibility
214− },
215− contentDescription = if (passwordVisible) {
216− stringResource(R.string.connect_password_hide)
217− } else {
218− stringResource(R.string.connect_password_show)
219− },
220− )
221− }
222− },
223− keyboardOptions = KeyboardOptions(
224− keyboardType = KeyboardType.Password,
225− imeAction = ImeAction.Go,
226− ),
227− keyboardActions = KeyboardActions(onGo = { submit() }),
228− modifier = Modifier.fillMaxWidth(),
229− )
230− Spacer(Modifier.height(Dimens.spaceTiny))
231− TextButton(onClick = { core.update(Event.CancelAuth) }) {
232− Text(stringResource(R.string.connect_button_cancel))
233 }
154 }
234− }
155+ },
235− }
236−
237− Spacer(Modifier.height(Dimens.spaceLarge))
238− Button(
239− onClick = { submit() },
240− enabled = !view.loading,
241 modifier = Modifier.fillMaxWidth(),
156 modifier = Modifier.fillMaxWidth(),
242− ) {
157+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
243− if (view.loading) {
158+ keyboardActions = KeyboardActions(onGo = {
244− CircularProgressIndicator(
159+ // Mirror the connect button's enabled condition so the keyboard's
245− modifier = Modifier.size(Dimens.iconButtonSpinner),
160+ // Go action can't fire a request the form isn't ready for.
246− strokeWidth = Dimens.strokeThin,
161+ if (!state.loading && state.serverUrl.isNotBlank() &&
247− color = MaterialTheme.colorScheme.onPrimary,
162+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank())
248− )
163+ ) {
249− } else {
164+ dispatch(Event.Connect)
250− Text(stringResource(R.string.connect_button_connect))
251− }
252− }
253−
254− if (crashCount > 0) {
255− Spacer(Modifier.height(Dimens.spaceLarge))
256− Row(verticalAlignment = Alignment.CenterVertically) {
257− Icon(
258− Icons.Default.Warning,
259− contentDescription = stringResource(R.string.connect_cd_warning),
260− tint = MaterialTheme.colorScheme.error,
261− modifier = Modifier.size(Dimens.iconInputLeading),
262− )
263− Spacer(Modifier.size(Dimens.gapTiny))
264− TextButton(onClick = { showCrashLogs = true }) {
265− Text(
266− text = pluralStringResource(R.plurals.crash_reports_view, crashCount, crashCount),
267− style = MaterialTheme.typography.labelSmall,
268− )
269 }
165 }
270− }
166+ }),
271− }
167+ enabled = !state.loading,
168+ )
169+ Spacer(Modifier.height(4.dp))
170+ Text(
171+ text = "This server requires authentication.",
172+ style = MaterialTheme.typography.bodySmall,
173+ color = MaterialTheme.colorScheme.onSurfaceVariant,
174+ )
272 }
175 }
273− }
274
176
275− if (showCrashLogs) {
177+ Spacer(Modifier.height(24.dp))
276− CrashLogDialog(
277− reports = CrashLogger.getReports(),
278− onDismiss = { showCrashLogs = false },
279− onClear = {
280− CrashLogger.clearReports()
281− showCrashLogs = false
282− },
283− title = stringResource(R.string.crash_reports_title),
284− clearLabel = stringResource(R.string.crash_reports_clear),
285− closeLabel = stringResource(R.string.crash_reports_close),
286− clearConfirmLabel = stringResource(R.string.crash_reports_clear_confirm),
287− clearConfirmYesLabel = stringResource(R.string.crash_reports_clear_confirm_yes),
288− )
289− }
290−}
291
178
292−@OptIn(ExperimentalMaterial3Api::class)
179+ Button(
293−@Preview(showBackground = true)
180+ onClick = { dispatch(Event.Connect) },
294−@Preview(showBackground = true, uiMode = android.content.res.Configuration.UI_MODE_NIGHT_YES)
181+ // When auth is required, keep the button disabled until at least one
295−@Composable
182+ // credential is entered — otherwise it just triggers a validation error.
296−private fun ConnectScreenPreview() {
183+ enabled = !state.loading && state.serverUrl.isNotBlank() &&
297− soy.iko.opencode.ui.theme.OpencodeTheme {
184+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
298− Scaffold(topBar = { TopAppBar(title = { Text("Opencode") }) }) { padding ->
185+ modifier = Modifier.fillMaxWidth(),
299− Column(
186+ ) {
300− horizontalAlignment = Alignment.CenterHorizontally,
187+ if (state.loading) {
301− verticalArrangement = Arrangement.Center,
188+ CircularProgressIndicator(
302− modifier = Modifier
189+ modifier = Modifier.height(20.dp),
303− .fillMaxSize()
190+ strokeWidth = 2.dp,
304− .padding(padding)
191+ color = MaterialTheme.colorScheme.onPrimary,
305− .padding(24.dp)
306− .verticalScroll(rememberScrollState()),
307− ) {
308− Icon(
309− Icons.Default.Dns,
310− contentDescription = null,
311− modifier = Modifier.size(72.dp),
312− tint = MaterialTheme.colorScheme.primary,
313− )
314− Spacer(Modifier.height(16.dp))
315− Text("Connect to Opencode Server", style = MaterialTheme.typography.headlineSmall)
316− Spacer(Modifier.height(24.dp))
317− OutlinedTextField(
318− value = "http://localhost:4096",
319− onValueChange = {},
320− label = { Text("Server URL") },
321− singleLine = true,
322− modifier = Modifier.fillMaxWidth(),
323 )
192 )
324− Spacer(Modifier.height(16.dp))
193+ } else {
325− Button(onClick = {}, modifier = Modifier.fillMaxWidth()) {
194+ Text(if (state.authRequired) "Sign in" else "Connect")
326− Text("Connect")
327− }
328 }
195 }
329 }
196 }
197+
198+ // While connecting (including auto-connect on launch), echo the target URL
199+ // so the user knows what the spinner is waiting on.
200+ if (state.loading) {
201+ Spacer(Modifier.height(8.dp))
202+ Text(
203+ text = "Connecting to ${state.serverUrl}...",
204+ style = MaterialTheme.typography.bodySmall,
205+ color = MaterialTheme.colorScheme.onSurfaceVariant,
206+ textAlign = TextAlign.Center,
207+ )
208+ }
209+
210+ // Surface the error inline as well, so it stays visible while the user
211+ // corrects the form (the snackbar is transient).
212+ if (state.error != null && !state.loading) {
213+ Spacer(Modifier.height(8.dp))
214+ Text(
215+ text = state.error,
216+ style = MaterialTheme.typography.bodySmall,
217+ color = MaterialTheme.colorScheme.error,
218+ textAlign = TextAlign.Center,
219+ )
220+ }
330 }
221 }
331}
222}
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+333−135
@@ -1,114 +1,234 @@
1package soy.iko.opencode.ui.screens
1package soy.iko.opencode.ui.screens
2
2
3+import android.content.ClipData
4+import android.content.ClipboardManager
5+import android.content.Context
6+import android.widget.Toast
7+import androidx.compose.foundation.ExperimentalFoundationApi
8+import androidx.compose.foundation.background
3import androidx.compose.foundation.clickable
9import androidx.compose.foundation.clickable
10+import androidx.compose.foundation.combinedClickable
11+import androidx.compose.foundation.layout.Arrangement
4import androidx.compose.foundation.layout.Box
12import androidx.compose.foundation.layout.Box
13+import androidx.compose.foundation.layout.Column
14+import androidx.compose.foundation.layout.PaddingValues
15+import androidx.compose.foundation.layout.Row
16+import androidx.compose.foundation.layout.Spacer
5import androidx.compose.foundation.layout.fillMaxSize
17import androidx.compose.foundation.layout.fillMaxSize
18+import androidx.compose.foundation.layout.fillMaxWidth
19+import androidx.compose.foundation.layout.height
6import androidx.compose.foundation.layout.padding
20import androidx.compose.foundation.layout.padding
21+import androidx.compose.foundation.layout.size
7import androidx.compose.foundation.lazy.LazyColumn
22import androidx.compose.foundation.lazy.LazyColumn
8import androidx.compose.foundation.lazy.items
23import androidx.compose.foundation.lazy.items
24+import androidx.compose.foundation.lazy.rememberLazyListState
25+import androidx.compose.foundation.shape.CircleShape
9import androidx.compose.material.icons.Icons
26import androidx.compose.material.icons.Icons
10import androidx.compose.material.icons.automirrored.filled.ArrowBack
27import androidx.compose.material.icons.automirrored.filled.ArrowBack
11import androidx.compose.material.icons.filled.Add
28import androidx.compose.material.icons.filled.Add
12−import androidx.compose.material.icons.filled.ChatBubble
29+import androidx.compose.material.icons.filled.ChatBubbleOutline
30+import androidx.compose.material.icons.filled.ChevronRight
31+import androidx.compose.material.icons.filled.DeleteOutline
32+import androidx.compose.material.icons.filled.Refresh
33+import androidx.compose.material3.AlertDialog
34+import androidx.compose.material3.CircularProgressIndicator
13import androidx.compose.material3.ExperimentalMaterial3Api
35import androidx.compose.material3.ExperimentalMaterial3Api
36+import androidx.compose.material3.ExtendedFloatingActionButton
37+import androidx.compose.material3.HorizontalDivider
14import androidx.compose.material3.Icon
38import androidx.compose.material3.Icon
15import androidx.compose.material3.IconButton
39import androidx.compose.material3.IconButton
16−import androidx.compose.material3.ListItem
40+import androidx.compose.material3.LinearProgressIndicator
17import androidx.compose.material3.MaterialTheme
41import androidx.compose.material3.MaterialTheme
42+import androidx.compose.material3.OutlinedTextField
18import androidx.compose.material3.Scaffold
43import androidx.compose.material3.Scaffold
44+import androidx.compose.material3.Surface
45+import androidx.compose.material3.SwipeToDismissBox
46+import androidx.compose.material3.SwipeToDismissBoxValue
19import androidx.compose.material3.Text
47import androidx.compose.material3.Text
48+import androidx.compose.material3.TextButton
20import androidx.compose.material3.TopAppBar
49import androidx.compose.material3.TopAppBar
50+import androidx.compose.material3.rememberSwipeToDismissBoxState
21import androidx.compose.material3.pulltorefresh.PullToRefreshBox
51import androidx.compose.material3.pulltorefresh.PullToRefreshBox
52+import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
22import androidx.compose.runtime.Composable
53import androidx.compose.runtime.Composable
23−import androidx.compose.runtime.collectAsState
54+import androidx.compose.runtime.LaunchedEffect
24import androidx.compose.runtime.getValue
55import androidx.compose.runtime.getValue
56+import androidx.compose.runtime.mutableStateOf
57+import androidx.compose.runtime.remember
58+import androidx.compose.runtime.setValue
59+import androidx.compose.ui.Alignment
25import androidx.compose.ui.Modifier
60import androidx.compose.ui.Modifier
26−import androidx.compose.ui.res.stringResource
61+import androidx.compose.ui.draw.clip
27−import androidx.compose.ui.semantics.Role
62+import androidx.compose.ui.graphics.Color
28−import androidx.compose.ui.semantics.contentDescription
63+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
29−import androidx.compose.ui.semantics.role
64+import androidx.compose.ui.platform.LocalContext
30−import androidx.compose.ui.semantics.semantics
65+import androidx.compose.ui.platform.LocalHapticFeedback
31−import androidx.compose.ui.tooling.preview.Preview
66+import androidx.compose.ui.text.style.TextAlign
67+import androidx.compose.ui.text.style.TextOverflow
32import androidx.compose.ui.unit.dp
68import androidx.compose.ui.unit.dp
33−import soy.iko.opencode.R
34−import soy.iko.opencode.core.Core
35import soy.iko.opencode.core.Event
69import soy.iko.opencode.core.Event
36import soy.iko.opencode.core.SessionView
70import soy.iko.opencode.core.SessionView
37−import soy.iko.opencode.ui.components.DualSnackbarHost
71+import soy.iko.opencode.core.UiState
38−import soy.iko.opencode.ui.components.EmptyState
39−import soy.iko.opencode.ui.components.ErrorHost
40−import soy.iko.opencode.ui.components.InfoHost
41−import soy.iko.opencode.ui.components.LoadingPlaceholder
42−import soy.iko.opencode.ui.theme.Dimens
43−import soy.iko.opencode.ui.theme.OpencodeTheme
44
72
45@OptIn(ExperimentalMaterial3Api::class)
73@OptIn(ExperimentalMaterial3Api::class)
46@Composable
74@Composable
47−fun SessionsScreen(core: Core) {
75+fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
48− val view by core.view.collectAsState()
76+ val haptic = LocalHapticFeedback.current
49− val errorHostState = ErrorHost(
77+ var pendingDeleteId by remember { mutableStateOf<String?>(null) }
50− core = core,
78+ var isPullRefreshing by remember { mutableStateOf(false) }
51− dismissLabel = stringResource(R.string.action_dismiss),
79+ var searchQuery by remember { mutableStateOf("") }
52− retryLabel = stringResource(R.string.action_retry),
80+ val sessionsListState = rememberLazyListState()
53− )
81+
54− val infoHostState = InfoHost(
82+ // Bring a newly created session (which lands at the top of the list) into view.
55− core = core,
83+ // Only scroll when the list actually grows, not on every reload of the same sessions.
56− successConnectedLabel = stringResource(R.string.connect_success),
84+ var prevSize by remember { mutableStateOf(state.sessions.size) }
57− successSessionCreatedLabel = stringResource(R.string.session_created),
85+ LaunchedEffect(state.sessions.size) {
58− )
86+ if (state.sessions.size > prevSize) sessionsListState.animateScrollToItem(0)
59− val untitledLabel = stringResource(R.string.sessions_untitled)
87+ prevSize = state.sessions.size
60− val idShortTemplate = stringResource(R.string.sessions_id_short)
88+ }
89+
90+ // The pull-to-refresh spinner should only reflect a user-initiated pull, not
91+ // every loading operation. Clear it once the underlying load completes.
92+ LaunchedEffect(state.loading) {
93+ if (!state.loading) isPullRefreshing = false
94+ }
95+
96+ pendingDeleteId?.let { deleteId ->
97+ val pendingSession = state.sessions.firstOrNull { it.id == deleteId }
98+ AlertDialog(
99+ onDismissRequest = { pendingDeleteId = null },
100+ title = { Text("Delete session?") },
101+ text = { Text(pendingSession?.title ?: deleteId) },
102+ confirmButton = {
103+ TextButton(onClick = {
104+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
105+ dispatch(Event.DeleteSession(deleteId))
106+ pendingDeleteId = null
107+ }) {
108+ Text("Delete")
109+ }
110+ },
111+ dismissButton = {
112+ TextButton(onClick = { pendingDeleteId = null }) {
113+ Text("Cancel")
114+ }
115+ },
116+ )
117+ }
61
118
62 Scaffold(
119 Scaffold(
63 topBar = {
120 topBar = {
64 TopAppBar(
121 TopAppBar(
65− title = { Text(stringResource(R.string.top_bar_sessions)) },
122+ title = {
66− navigationIcon = {
123+ Row(verticalAlignment = Alignment.CenterVertically) {
67− IconButton(onClick = { core.update(Event.NavigateToConnect) }) {
124+ // A quick at-a-glance health dot for the SSE stream: green when
68− Icon(
125+ // connected, error-tinted when the stream is down (updates stall).
69− Icons.AutoMirrored.Filled.ArrowBack,
126+ Box(
70− contentDescription = stringResource(R.string.sessions_cd_back),
127+ modifier = Modifier
128+ .size(8.dp)
129+ .clip(CircleShape)
130+ .background(
131+ if (state.sseConnected) Color(0xFF4CAF50)
132+ else MaterialTheme.colorScheme.error,
133+ ),
71 )
134 )
135+ Spacer(Modifier.size(8.dp))
136+ Text(if (state.sessions.isNotEmpty()) "Sessions (${state.sessions.size})" else "Sessions")
137+ }
138+ },
139+ navigationIcon = {
140+ IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
141+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
72 }
142 }
73 },
143 },
74 actions = {
144 actions = {
75− IconButton(onClick = { core.update(Event.CreateSession) }) {
145+ IconButton(onClick = { dispatch(Event.LoadSessions) }) {
76− Icon(
146+ Icon(Icons.Filled.Refresh, contentDescription = "Refresh")
77− Icons.Default.Add,
78− contentDescription = stringResource(R.string.sessions_cd_new),
79− )
80 }
147 }
81 },
148 },
82 )
149 )
83 },
150 },
84− snackbarHost = { DualSnackbarHost(errorHostState, infoHostState) },
151+ floatingActionButton = {
152+ // Give the search results the full width while searching — the FAB would
153+ // otherwise cover the bottom rows and isn't relevant mid-search anyway.
154+ if (searchQuery.isEmpty()) {
155+ ExtendedFloatingActionButton(
156+ onClick = { dispatch(Event.CreateSession) },
157+ icon = { Icon(Icons.Filled.Add, contentDescription = null) },
158+ text = { Text("New session") },
159+ )
160+ }
161+ },
85 ) { padding ->
162 ) { padding ->
86− Box(
163+ Column(Modifier.fillMaxSize().padding(padding)) {
87− modifier = Modifier
164+ if (!state.sseConnected) {
88− .fillMaxSize()
165+ ReconnectingBanner()
89− .padding(padding),
166+ }
90− ) {
167+ if (state.loading && !isPullRefreshing) {
91− when {
168+ LinearProgressIndicator(Modifier.fillMaxWidth())
92− view.loading && view.sessions.isEmpty() -> {
169+ }
93− LoadingPlaceholder()
170+ if (state.sessions.isNotEmpty()) {
94− }
171+ OutlinedTextField(
95− view.sessions.isEmpty() -> {
172+ value = searchQuery,
96− EmptyState(message = stringResource(R.string.sessions_empty_hint))
173+ onValueChange = { searchQuery = it },
174+ placeholder = { Text("Search sessions") },
175+ singleLine = true,
176+ modifier = Modifier
177+ .fillMaxWidth()
178+ .padding(horizontal = 16.dp, vertical = 8.dp),
179+ )
180+ }
181+ val filteredSessions = if (searchQuery.isEmpty()) {
182+ state.sessions
183+ } else {
184+ state.sessions.filter {
185+ it.title.contains(searchQuery, ignoreCase = true) ||
186+ it.id.contains(searchQuery, ignoreCase = true)
97 }
187 }
98− else -> {
188+ }
99− PullToRefreshBox(
189+ when {
100− isRefreshing = view.loading,
190+ state.sessions.isEmpty() && !state.loading -> EmptySessions()
101− onRefresh = { core.update(Event.LoadSessions) },
191+ filteredSessions.isEmpty() && searchQuery.isNotEmpty() -> NoSearchResults(searchQuery)
192+ else -> PullToRefreshBox(
193+ isRefreshing = isPullRefreshing,
194+ onRefresh = {
195+ isPullRefreshing = true
196+ dispatch(Event.LoadSessions)
197+ },
198+ modifier = Modifier.fillMaxSize(),
199+ state = rememberPullToRefreshState(),
200+ ) {
201+ LazyColumn(
202+ state = sessionsListState,
102 modifier = Modifier.fillMaxSize(),
203 modifier = Modifier.fillMaxSize(),
204+ contentPadding = PaddingValues(bottom = 88.dp),
103 ) {
205 ) {
104− LazyColumn {
206+ items(filteredSessions, key = { it.id }) { session ->
105− items(view.sessions, key = { it.id }) { session ->
207+ // animateItem() slides the remaining rows into place when one is
106− SessionRow(
208+ // deleted (and fades new rows in) instead of snapping instantly.
107− session = session,
209+ Column(modifier = Modifier.animateItem()) {
108− untitledLabel = untitledLabel,
210+ val dismissState = rememberSwipeToDismissBoxState(
109− idShortLabel = idShortTemplate.format(session.id.take(8)),
211+ // Only a swipe from the end (right-to-left) triggers deletion;
110− onClick = { core.update(Event.SelectSession(session.id)) },
212+ // return false so the row snaps back and the confirm dialog decides.
213+ confirmValueChange = { value ->
214+ if (value == SwipeToDismissBoxValue.EndToStart) {
215+ pendingDeleteId = session.id
216+ }
217+ false
218+ },
111 )
219 )
220+ SwipeToDismissBox(
221+ state = dismissState,
222+ enableDismissFromStartToEnd = false,
223+ backgroundContent = { SwipeDeleteBackground() },
224+ ) {
225+ SessionRow(
226+ session = session,
227+ onOpen = { dispatch(Event.SelectSession(session.id)) },
228+ onDelete = { pendingDeleteId = session.id },
229+ )
230+ }
231+ HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
112 }
232 }
113 }
233 }
114 }
234 }
@@ -118,87 +238,165 @@ fun SessionsScreen(core: Core) {
118 }
238 }
119}
239}
120
240
241+@OptIn(ExperimentalFoundationApi::class)
121@Composable
242@Composable
122−private fun SessionRow(
243+private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
123− session: SessionView,
244+ val context = LocalContext.current
124− untitledLabel: String,
245+ Row(
125− idShortLabel: String,
246+ modifier = Modifier
126− onClick: () -> Unit,
247+ .fillMaxWidth()
127−) {
248+ .background(MaterialTheme.colorScheme.surface)
128− val title = session.title.ifEmpty { untitledLabel }
249+ .combinedClickable(
129− ListItem(
250+ onClick = onOpen,
130− headlineContent = { Text(title) },
251+ onLongClick = {
131− supportingContent = { Text(idShortLabel) },
252+ copyToClipboard(context, session.id)
132− leadingContent = {
253+ Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
254+ },
255+ )
256+ .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
257+ verticalAlignment = Alignment.CenterVertically,
258+ ) {
259+ Icon(
260+ Icons.Filled.ChatBubbleOutline,
261+ contentDescription = null,
262+ tint = MaterialTheme.colorScheme.primary,
263+ modifier = Modifier.padding(end = 16.dp),
264+ )
265+ Column(Modifier.weight(1f)) {
266+ Text(
267+ text = session.title,
268+ style = MaterialTheme.typography.bodyLarge,
269+ maxLines = 1,
270+ overflow = TextOverflow.Ellipsis,
271+ )
272+ Text(
273+ text = shortSessionId(session.id),
274+ style = MaterialTheme.typography.bodySmall,
275+ color = MaterialTheme.colorScheme.onSurfaceVariant,
276+ maxLines = 1,
277+ overflow = TextOverflow.Ellipsis,
278+ )
279+ }
280+ Icon(
281+ Icons.Filled.ChevronRight,
282+ contentDescription = null,
283+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
284+ modifier = Modifier.padding(horizontal = 4.dp),
285+ )
286+ IconButton(onClick = onDelete) {
133 Icon(
287 Icon(
134− Icons.Default.ChatBubble,
288+ Icons.Filled.DeleteOutline,
135− contentDescription = null,
289+ contentDescription = "Delete session",
136− tint = MaterialTheme.colorScheme.primary,
290+ tint = MaterialTheme.colorScheme.error,
137 )
291 )
138− },
292+ }
139− modifier = Modifier
293+ }
140− .clickable(onClick = onClick)
141− .semantics(mergeDescendants = true) {
142− // Merge the row into a single TalkBack utterance and announce
143− // it as a button so users know it's actionable.
144− role = Role.Button
145− contentDescription = title
146− },
147− )
148}
294}
149
295
150−@OptIn(ExperimentalMaterial3Api::class)
296+/** Red background with a trailing delete icon and label, revealed while swiping a session row away. */
151−@Preview(showBackground = true)
152−@Preview(showBackground = true, uiMode = android.content.res.Configuration.UI_MODE_NIGHT_YES)
153@Composable
297@Composable
154−private fun SessionsScreenPreview() {
298+private fun SwipeDeleteBackground() {
155− OpencodeTheme {
299+ Box(
156− Scaffold(topBar = {
300+ modifier = Modifier
157− TopAppBar(
301+ .fillMaxSize()
158− title = { Text("Sessions") },
302+ .background(MaterialTheme.colorScheme.error)
159− navigationIcon = {
303+ .padding(horizontal = 24.dp),
160− IconButton(onClick = {}) {
304+ contentAlignment = Alignment.CenterEnd,
161− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
305+ ) {
162− }
306+ Row(verticalAlignment = Alignment.CenterVertically) {
163− },
307+ Icon(
164− actions = {
308+ Icons.Filled.DeleteOutline,
165− IconButton(onClick = {}) {
309+ contentDescription = null,
166− Icon(Icons.Default.Add, contentDescription = "New session")
310+ tint = MaterialTheme.colorScheme.onError,
167− }
311+ )
168− },
312+ Text(
313+ text = "Delete",
314+ style = MaterialTheme.typography.labelLarge,
315+ color = MaterialTheme.colorScheme.onError,
316+ modifier = Modifier.padding(start = 4.dp),
169 )
317 )
170− }) { padding ->
171− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
172− LazyColumn {
173− items(
174− listOf(
175− SessionView("abc12345def", "Refactor the parser"),
176− SessionView("xyz12345abc", ""),
177− ),
178− key = { it.id },
179− ) { session ->
180− SessionRow(
181− session,
182− untitledLabel = "Untitled",
183− idShortLabel = "Session ${session.id.take(8)}",
184− onClick = {},
185− )
186− }
187− }
188− }
189 }
318 }
190 }
319 }
191}
320}
192
321
193−@OptIn(ExperimentalMaterial3Api::class)
322+/** Shown at the top of the list while the SSE stream is down, since session updates stall too. */
194−@Preview(showBackground = true)
195@Composable
323@Composable
196−private fun SessionsScreenEmptyPreview() {
324+private fun ReconnectingBanner() {
197− OpencodeTheme {
325+ Surface(
198− Scaffold(topBar = { TopAppBar(title = { Text("Sessions") }) }) { padding ->
326+ modifier = Modifier.fillMaxWidth(),
199− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
327+ color = MaterialTheme.colorScheme.tertiaryContainer,
200− EmptyState(message = "No sessions yet")
328+ ) {
201− }
329+ Row(
330+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
331+ verticalAlignment = Alignment.CenterVertically,
332+ horizontalArrangement = Arrangement.spacedBy(8.dp),
333+ ) {
334+ CircularProgressIndicator(
335+ modifier = Modifier.size(14.dp),
336+ strokeWidth = 2.dp,
337+ color = MaterialTheme.colorScheme.onTertiaryContainer,
338+ )
339+ Text(
340+ text = "Reconnecting…",
341+ style = MaterialTheme.typography.bodySmall,
342+ color = MaterialTheme.colorScheme.onTertiaryContainer,
343+ )
202 }
344 }
203 }
345 }
204}
346}
347+
348+private fun copyToClipboard(context: Context, text: String) {
349+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
350+ clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
351+}
352+
353+/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
354+private fun shortSessionId(id: String): String =
355+ if (id.length > 12) id.take(8) + "…" else id
356+
357+@Composable
358+private fun NoSearchResults(query: String) {
359+ Box(
360+ modifier = Modifier.fillMaxSize().padding(32.dp),
361+ contentAlignment = Alignment.Center,
362+ ) {
363+ Text(
364+ text = "No results for “$query”",
365+ style = MaterialTheme.typography.bodyMedium,
366+ color = MaterialTheme.colorScheme.onSurfaceVariant,
367+ )
368+ }
369+}
370+
371+@Composable
372+private fun EmptySessions() {
373+ Column(
374+ modifier = Modifier.fillMaxSize().padding(32.dp),
375+ verticalArrangement = Arrangement.Center,
376+ horizontalAlignment = Alignment.CenterHorizontally,
377+ ) {
378+ Icon(
379+ Icons.Filled.ChatBubbleOutline,
380+ contentDescription = null,
381+ modifier = Modifier.size(64.dp),
382+ tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
383+ )
384+ Spacer(Modifier.height(16.dp))
385+ Text(
386+ text = "No sessions yet",
387+ style = MaterialTheme.typography.titleMedium,
388+ )
389+ Text(
390+ text = "Tap “New session” to start chatting.",
391+ style = MaterialTheme.typography.bodyMedium,
392+ color = MaterialTheme.colorScheme.onSurfaceVariant,
393+ )
394+ Spacer(Modifier.height(8.dp))
395+ Text(
396+ text = "Sessions you create on this server will appear here.",
397+ style = MaterialTheme.typography.bodySmall,
398+ color = MaterialTheme.colorScheme.onSurfaceVariant,
399+ textAlign = TextAlign.Center,
400+ )
401+ }
402+}
app/src/main/java/soy/iko/opencode/ui/theme/Color.ktnew file+19
@@ -0,0 +1,19 @@
1+package soy.iko.opencode.ui.theme
2+
3+import androidx.compose.ui.graphics.Color
4+
5+// A calm, terminal-adjacent palette. Used when dynamic color isn't available.
6+val Emerald = Color(0xFF3DDC84)
7+val EmeraldDark = Color(0xFF1B8F52)
8+
9+val DarkBackground = Color(0xFF0F1115)
10+val DarkSurface = Color(0xFF171A21)
11+val DarkSurfaceVariant = Color(0xFF232833)
12+val DarkOnSurface = Color(0xFFE6E9EF)
13+val DarkOutline = Color(0xFF3A4150)
14+
15+val LightBackground = Color(0xFFF7F8FA)
16+val LightSurface = Color(0xFFFFFFFF)
17+val LightSurfaceVariant = Color(0xFFEBEDF2)
18+val LightOnSurface = Color(0xFF1A1C1F)
19+val LightOutline = Color(0xFFC4C9D4)
app/src/main/java/soy/iko/opencode/ui/theme/Dimens.ktdeleted−53
@@ -1,53 +0,0 @@
1−package soy.iko.opencode.ui.theme
2−
3−import androidx.compose.ui.unit.dp
4−
5−/**
6− * Centralized spacing/dimension tokens. Replaces the ~14 inline magic `dp`
7− * values that were scattered across the screen files. New UI should pull from
8− * here so spacing stays consistent and drift becomes visible.
9− */
10−object Dimens {
11− // Screen-edge padding
12− val screenPadding = 24.dp
13−
14− // List content padding (horizontal gutters + vertical breathing room)
15− val listHorizontalPadding = 12.dp
16− val listVerticalPadding = 12.dp
17− val listItemSpacing = 8.dp
18−
19− // Generic spacers
20− val spaceTiny = 4.dp
21− val spaceSmall = 8.dp
22− val spaceMedium = 12.dp
23− val spaceLarge = 16.dp
24− val spaceXLarge = 24.dp
25−
26− // Inline gaps (not large enough for a named "space" token but still shared)
27− val gapTiny = 6.dp
28−
29− // Bubble internals
30− val bubbleHorizontalPadding = 14.dp
31− val bubbleVerticalPadding = 10.dp
32− val bubbleTailCorner = 4.dp
33− val bubbleMaxWidthFraction = 0.82f
34−
35− // Input bar
36− val inputBarHorizontalPadding = 12.dp
37− val inputBarVerticalPadding = 8.dp
38− val inputBarTonalElevation = 3.dp
39−
40− // Icons
41− val iconHero = 72.dp
42− val iconInputLeading = 16.dp
43− val iconInlineSpinner = 14.dp
44− val iconButtonSpinner = 20.dp
45−
46− // Strokes
47− val strokeThin = 2.dp
48−
49− // Floating action button
50− val fabSize = 40.dp
51− val fabEndMargin = 16.dp
52− val fabBottomMargin = 12.dp
53−}
app/src/main/java/soy/iko/opencode/ui/theme/Shapes.ktdeleted−33
@@ -1,33 +0,0 @@
1−package soy.iko.opencode.ui.theme
2−
3−import androidx.compose.foundation.shape.RoundedCornerShape
4−import androidx.compose.material3.Shapes
5−import androidx.compose.ui.unit.dp
6−
7−/**
8− * Centralized shape tokens. The chat-bubble shapes are defined here so the
9− * user/assistant bubbles and the "generating" indicator all share one source
10− * of truth instead of being hand-duplicated at each call site.
11− */
12−val OpencodeShapes = Shapes(
13− extraSmall = RoundedCornerShape(4.dp),
14− small = RoundedCornerShape(8.dp),
15− medium = RoundedCornerShape(12.dp),
16− large = RoundedCornerShape(16.dp),
17− extraLarge = RoundedCornerShape(28.dp),
18−)
19−
20−/** Tail-at-corner shapes for chat bubbles. */
21−val UserBubbleShape = RoundedCornerShape(
22− topStart = 16.dp,
23− topEnd = 16.dp,
24− bottomStart = 16.dp,
25− bottomEnd = 4.dp,
26−)
27−
28−val AssistantBubbleShape = RoundedCornerShape(
29− topStart = 16.dp,
30− topEnd = 16.dp,
31− bottomStart = 4.dp,
32− bottomEnd = 16.dp,
33−)
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+46−30
@@ -11,50 +11,66 @@ import androidx.compose.runtime.Composable
11import androidx.compose.ui.graphics.Color
11import androidx.compose.ui.graphics.Color
12import androidx.compose.ui.platform.LocalContext
12import androidx.compose.ui.platform.LocalContext
13
13
14−private val DarkColorScheme = darkColorScheme(
14+private val DarkColors = darkColorScheme(
15− primary = Color(0xFF82B1FF),
15+ primary = Emerald,
16− secondary = Color(0xFF80CBC4),
16+ onPrimary = Color(0xFF0F1115),
17− tertiary = Color(0xFFFFB74D),
17+ primaryContainer = Color(0xFF1A3D2A),
18− background = Color(0xFF121212),
18+ onPrimaryContainer = Color(0xFFA8E6C1),
19− surface = Color(0xFF1E1E1E),
19+ secondary = EmeraldDark,
20− onPrimary = Color.Black,
20+ onSecondary = Color(0xFFE6E9EF),
21− onSecondary = Color.Black,
21+ secondaryContainer = Color(0xFF1A2A3D),
22− onTertiary = Color.Black,
22+ onSecondaryContainer = Color(0xFFA8C5E6),
23− onBackground = Color.White,
23+ tertiary = Color(0xFF6B7280),
24− onSurface = Color.White,
24+ onTertiary = Color(0xFFE6E9EF),
25+ tertiaryContainer = Color(0xFF2A2A3D),
26+ onTertiaryContainer = Color(0xFFC5C5E6),
27+ errorContainer = Color(0xFF4D2626),
28+ onErrorContainer = Color(0xFFFFB4B4),
29+ background = DarkBackground,
30+ surface = DarkSurface,
31+ surfaceVariant = DarkSurfaceVariant,
32+ onSurface = DarkOnSurface,
33+ outline = DarkOutline,
25)
34)
26
35
27−private val LightColorScheme = lightColorScheme(
36+private val LightColors = lightColorScheme(
28− primary = Color(0xFF1565C0),
37+ primary = EmeraldDark,
29− secondary = Color(0xFF00897B),
38+ primaryContainer = Color(0xFFD7F5E3),
30− tertiary = Color(0xFFF57C00),
39+ onPrimaryContainer = Color(0xFF0A3D22),
31− background = Color(0xFFF5F5F5),
40+ secondary = Emerald,
32− surface = Color.White,
41+ onSecondary = Color(0xFF1A1C1F),
33− onPrimary = Color.White,
42+ secondaryContainer = Color(0xFFD7E8F5),
34− onSecondary = Color.White,
43+ onSecondaryContainer = Color(0xFF0A2A4D),
35− onTertiary = Color.White,
44+ tertiary = Color(0xFF6B7280),
36− onBackground = Color.Black,
45+ onTertiary = Color(0xFFFFFFFF),
37− onSurface = Color.Black,
46+ tertiaryContainer = Color(0xFFE8E8F5),
47+ onTertiaryContainer = Color(0xFF2A2A4D),
48+ errorContainer = Color(0xFFFFE0E0),
49+ onErrorContainer = Color(0xFF660000),
50+ background = LightBackground,
51+ surface = LightSurface,
52+ surfaceVariant = LightSurfaceVariant,
53+ onSurface = LightOnSurface,
54+ outline = LightOutline,
38)
55)
39
56
40@Composable
57@Composable
41fun OpencodeTheme(
58fun OpencodeTheme(
42 darkTheme: Boolean = isSystemInDarkTheme(),
59 darkTheme: Boolean = isSystemInDarkTheme(),
43− dynamicColor: Boolean = true,
60+ dynamicColor: Boolean = false,
44 content: @Composable () -> Unit,
61 content: @Composable () -> Unit,
45) {
62) {
63+ val context = LocalContext.current
46 val colorScheme = when {
64 val colorScheme = when {
47− dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
65+ dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
48− val context = LocalContext.current
49 if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
66 if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
50− }
67+ darkTheme -> DarkColors
51− darkTheme -> DarkColorScheme
68+ else -> LightColors
52− else -> LightColorScheme
53 }
69 }
70+
54 MaterialTheme(
71 MaterialTheme(
55 colorScheme = colorScheme,
72 colorScheme = colorScheme,
56− typography = OpencodeTypography,
73+ typography = AppTypography,
57− shapes = OpencodeShapes,
58 content = content,
74 content = content,
59 )
75 )
60}
76}
app/src/main/java/soy/iko/opencode/ui/theme/Type.kt+7−62
@@ -3,68 +3,13 @@ package soy.iko.opencode.ui.theme
3import androidx.compose.material3.Typography
3import androidx.compose.material3.Typography
4import androidx.compose.ui.text.TextStyle
4import androidx.compose.ui.text.TextStyle
5import androidx.compose.ui.text.font.FontFamily
5import androidx.compose.ui.text.font.FontFamily
6−import androidx.compose.ui.text.font.FontWeight
7import androidx.compose.ui.unit.sp
6import androidx.compose.ui.unit.sp
8
7
9−/**
8+private val base = Typography()
10− * Typography scale. Stays close to the Material 3 baseline but pins the values
9+
11− * so that font sizes, weights, and letter spacing don't silently shift when
10+val AppTypography = base.copy(
12− * the Compose BOM updates. The screens reference these via
11+ bodyLarge = base.bodyLarge.copy(lineHeight = 22.sp),
13− * [androidx.compose.material3.MaterialTheme.typography].
12+ // Slightly monospaced feel for message bodies is applied inline where needed.
14− */
15−val OpencodeTypography = Typography(
16− headlineSmall = TextStyle(
17− fontFamily = FontFamily.Default,
18− fontWeight = FontWeight.SemiBold,
19− fontSize = 24.sp,
20− lineHeight = 32.sp,
21− letterSpacing = 0.sp,
22− ),
23− titleLarge = TextStyle(
24− fontFamily = FontFamily.Default,
25− fontWeight = FontWeight.SemiBold,
26− fontSize = 22.sp,
27− lineHeight = 28.sp,
28− ),
29− bodyLarge = TextStyle(
30− fontFamily = FontFamily.Default,
31− fontWeight = FontWeight.Normal,
32− fontSize = 16.sp,
33− lineHeight = 24.sp,
34− letterSpacing = 0.5.sp,
35− ),
36− bodyMedium = TextStyle(
37− fontFamily = FontFamily.Default,
38− fontWeight = FontWeight.Normal,
39− fontSize = 14.sp,
40− lineHeight = 20.sp,
41− letterSpacing = 0.25.sp,
42− ),
43− bodySmall = TextStyle(
44− fontFamily = FontFamily.Default,
45− fontWeight = FontWeight.Normal,
46− fontSize = 12.sp,
47− lineHeight = 16.sp,
48− ),
49− labelLarge = TextStyle(
50− fontFamily = FontFamily.Default,
51− fontWeight = FontWeight.Medium,
52− fontSize = 14.sp,
53− lineHeight = 20.sp,
54− letterSpacing = 0.1.sp,
55− ),
56− labelMedium = TextStyle(
57− fontFamily = FontFamily.Default,
58− fontWeight = FontWeight.Medium,
59− fontSize = 12.sp,
60− lineHeight = 16.sp,
61− letterSpacing = 0.5.sp,
62− ),
63− labelSmall = TextStyle(
64− fontFamily = FontFamily.Default,
65− fontWeight = FontWeight.Medium,
66− fontSize = 11.sp,
67− lineHeight = 16.sp,
68− letterSpacing = 0.5.sp,
69− ),
70)
13)
14+
15+val MonoStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp)
app/src/main/res/values-night-v31/themes.xmldeleted−7
@@ -1,7 +0,0 @@
1−<?xml version="1.0" encoding="utf-8"?>
2−<resources>
3− <style name="Theme.Opencode" parent="android:Theme.Material.NoActionBar">
4− <item name="android:windowSplashScreenBackground">@android:color/black</item>
5− <item name="android:windowSplashScreenAnimatedIcon">@android:drawable/ic_dialog_info</item>
6− </style>
7−</resources>
app/src/main/res/values-night/colors.xmlnew file+4
@@ -0,0 +1,4 @@
1+<?xml version="1.0" encoding="utf-8"?>
2+<resources>
3+ <color name="window_background">#0F1115</color>
4+</resources>
app/src/main/res/values-night/themes.xml+5−1
@@ -1,4 +1,8 @@
1<?xml version="1.0" encoding="utf-8"?>
1<?xml version="1.0" encoding="utf-8"?>
2<resources>
2<resources>
3− <style name="Theme.Opencode" parent="android:Theme.Material.NoActionBar" />
3+ <style name="Theme.OpencodeAndroid" parent="android:Theme.Material.NoActionBar">
4+ <item name="android:windowBackground">@color/window_background</item>
5+ <item name="android:statusBarColor">@android:color/transparent</item>
6+ <item name="android:navigationBarColor">@android:color/transparent</item>
7+ </style>
4</resources>
8</resources>
app/src/main/res/values-v31/themes.xmldeleted−11
@@ -1,11 +0,0 @@
1−<?xml version="1.0" encoding="utf-8"?>
2−<resources>
3− <style name="Theme.Opencode" parent="android:Theme.Material.Light.NoActionBar">
4− <!-- Android 12+ system splash screen: use the window background color
5− so the post-splash crossfade into the Compose UI is seamless. The
6− Compose UI paints its own background, so we only set the poster
7− color and a system icon here. -->
8− <item name="android:windowSplashScreenBackground">@android:color/white</item>
9− <item name="android:windowSplashScreenAnimatedIcon">@android:drawable/ic_dialog_info</item>
10− </style>
11−</resources>
app/src/main/res/values/colors.xmlnew file+4
@@ -0,0 +1,4 @@
1+<?xml version="1.0" encoding="utf-8"?>
2+<resources>
3+ <color name="window_background">#F7F8FA</color>
4+</resources>
app/src/main/res/values/strings.xml+2−63
@@ -1,65 +1,4 @@
1+<?xml version="1.0" encoding="utf-8"?>
1<resources>
2<resources>
2− <string name="app_name">Opencode</string>
3+ <string name="app_name">opencode</string>
3−
4− <!-- Top bar titles -->
5− <string name="top_bar_connect">Opencode</string>
6− <string name="top_bar_sessions">Sessions</string>
7− <string name="top_bar_chat_fallback">Chat</string>
8−
9− <!-- Connect screen -->
10− <string name="connect_heading">Connect to Opencode Server</string>
11− <string name="connect_field_server_url">Server URL</string>
12− <string name="connect_field_username">Username</string>
13− <string name="connect_field_password">Password</string>
14− <string name="connect_auth_required">Server requires authentication</string>
15− <string name="connect_password_hide">Hide password</string>
16− <string name="connect_password_show">Show password</string>
17− <string name="connect_button_cancel">Cancel</string>
18− <string name="connect_button_connect">Connect</string>
19− <string name="connect_success">Connected</string>
20− <string name="connect_cd_dns">Connection icon</string>
21− <string name="connect_cd_lock">Credentials icon</string>
22− <string name="connect_cd_warning">Warning icon</string>
23− <string name="connect_error_invalid_url">Enter a valid URL (http:// or https://)</string>
24−
25− <!-- Crash log -->
26− <string name="crash_reports_title">Crash Reports</string>
27− <plurals name="crash_reports_view">
28− <item quantity="one">%d crash report — view</item>
29− <item quantity="other">%d crash report(s) — view</item>
30− </plurals>
31− <string name="crash_reports_clear">Clear all</string>
32− <string name="crash_reports_close">Close</string>
33− <string name="crash_reports_clear_confirm">Clear all crash reports?</string>
34− <string name="crash_reports_clear_confirm_yes">Clear</string>
35−
36− <!-- Sessions screen -->
37− <string name="sessions_empty_hint">No sessions yet. Tap + to create one.</string>
38− <string name="sessions_cd_back">Change server</string>
39− <string name="sessions_cd_new">New session</string>
40− <string name="sessions_untitled">Untitled</string>
41− <string name="sessions_id_short">Session %s</string>
42− <string name="session_created">Session created</string>
43−
44− <!-- Chat screen -->
45− <string name="chat_empty_hint">Send a message below to start the conversation.</string>
46− <string name="chat_no_content">(no content)</string>
47− <string name="chat_input_placeholder">Message…</string>
48− <string name="chat_cd_back">Back</string>
49− <string name="chat_cd_send">Send</string>
50− <string name="chat_role_user">User</string>
51− <string name="chat_role_assistant">Assistant</string>
52− <string name="chat_cd_generating">Generating reply</string>
53− <string name="chat_cd_scroll_to_bottom">Scroll to latest message</string>
54− <string name="chat_session_id_short">Session %s</string>
55− <string name="chat_menu_overflow">More options</string>
56− <string name="chat_menu_refresh">Refresh messages</string>
57−
58− <!-- Error / snackbar -->
59− <string name="action_dismiss">Dismiss</string>
60− <string name="action_retry">Retry</string>
61−
62− <!-- SSE / connectivity -->
63− <string name="sse_disconnected">Live stream disconnected</string>
64− <string name="sse_reconnect">Reconnect</string>
65</resources>
4</resources>
app/src/main/res/values/themes.xml+10−1
@@ -1,4 +1,13 @@
1<?xml version="1.0" encoding="utf-8"?>
1<?xml version="1.0" encoding="utf-8"?>
2<resources>
2<resources>
3− <style name="Theme.Opencode" parent="android:Theme.Material.Light.NoActionBar" />
3+ <!--
4+ Minimal platform theme. All real theming is done in Compose (OpencodeTheme);
5+ this only removes the action bar and gives a neutral window background so
6+ there's no flash before the first frame.
7+ -->
8+ <style name="Theme.OpencodeAndroid" parent="android:Theme.Material.Light.NoActionBar">
9+ <item name="android:windowBackground">@color/window_background</item>
10+ <item name="android:statusBarColor">@android:color/transparent</item>
11+ <item name="android:navigationBarColor">@android:color/transparent</item>
12+ </style>
4</resources>
13</resources>
app/src/test/java/soy/iko/opencode/core/ConnectUrlTest.ktnew file+69
@@ -0,0 +1,69 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.coroutines.CoroutineScope
4+import kotlinx.coroutines.Dispatchers
5+import kotlinx.coroutines.test.runTest
6+import okhttp3.OkHttpClient
7+import okhttp3.Interceptor
8+import org.junit.Assert.assertEquals
9+import org.junit.Assert.assertTrue
10+import org.junit.Test
11+import java.io.IOException
12+
13+/**
14+ * Covers two related connect-screen bugs:
15+ * - the URL field must stay editable — normalizing per keystroke made it
16+ * "impossible to input" (it ate the "://" as you typed);
17+ * - a scheme-less URL must still be normalized to http:// on connect, and the
18+ * HTTP client must never crash on a malformed URL.
19+ */
20+class ConnectUrlTest {
21+ private fun core() = OpencodeCore(CoroutineScope(Dispatchers.Unconfined))
22+
23+ /** A client that never touches the network, so Connect's probe can't hang. */
24+ private fun offlineCore(): OpencodeCore {
25+ val offline = OkHttpClient.Builder()
26+ .addInterceptor(Interceptor { throw IOException("offline in test") })
27+ .build()
28+ return OpencodeCore(CoroutineScope(Dispatchers.Unconfined), HttpClient(offline))
29+ }
30+
31+ @Test
32+ fun `typing preserves raw input verbatim`() {
33+ val core = core()
34+ // Mid-scheme text the user is still typing must not be rewritten.
35+ core.dispatch(Event.ServerUrlChanged("http:/"))
36+ assertEquals("http:/", core.view.value.serverUrl)
37+ }
38+
39+ @Test
40+ fun `connect normalizes a scheme-less url to http`() {
41+ val core = offlineCore()
42+ core.dispatch(Event.ServerUrlChanged("192.168.1.10:4096"))
43+ assertEquals("192.168.1.10:4096", core.view.value.serverUrl) // raw while typing
44+ core.dispatch(Event.Connect)
45+ assertEquals("http://192.168.1.10:4096", core.view.value.serverUrl) // normalized on connect
46+ }
47+
48+ @Test
49+ fun `connect trims and keeps an explicit scheme`() {
50+ val core = offlineCore()
51+ core.dispatch(Event.ServerUrlChanged(" https://host:4096/ "))
52+ core.dispatch(Event.Connect)
53+ assertEquals("https://host:4096", core.view.value.serverUrl)
54+ }
55+
56+ @Test
57+ fun `connect on a blank url reports an error`() {
58+ val core = core()
59+ core.dispatch(Event.ServerUrlChanged(" "))
60+ core.dispatch(Event.Connect)
61+ assertEquals("Enter a server URL", core.view.value.error)
62+ }
63+
64+ @Test
65+ fun `http client returns failure rather than throwing on an unparseable url`() = runTest {
66+ val result = HttpClient().get("not a valid url", auth = null)
67+ assertTrue("expected a Result.failure, got $result", result.isFailure)
68+ }
69+}
app/src/test/java/soy/iko/opencode/core/PureCoreFfiTest.ktdeleted−201
@@ -1,201 +0,0 @@
1−package soy.iko.opencode.core
2−
3−import org.junit.Assert.assertEquals
4−import org.junit.Assert.assertFalse
5−import org.junit.Assert.assertNotNull
6−import org.junit.Assert.assertNull
7−import org.junit.Assert.assertTrue
8−import org.junit.Test
9−
10−class PureCoreFfiTest {
11−
12− private fun createCore(): PureCoreFfi = PureCoreFfi()
13−
14− private fun PureCoreFfi.currentView(): ViewModel =
15− ViewModel.bincodeDeserialize(view())
16−
17− private fun PureCoreFfi.processEvent(event: Event): Requests {
18− val effects = update(event.bincodeSerialize())
19− return Requests.bincodeDeserialize(effects)
20− }
21−
22− private fun PureCoreFfi.resolveHttp(
23− requestId: UInt,
24− status: Int = 200,
25− body: String = "{}",
26− ): Requests {
27− val response = HttpResponse(
28− status = status.toUShort(),
29− headers = emptyList(),
30− body = com.novi.serde.Bytes(body.toByteArray()),
31− )
32− val result = HttpResult.Ok(response)
33− val effects = resolve(requestId, result.bincodeSerialize())
34− return Requests.bincodeDeserialize(effects)
35− }
36−
37− @Test
38− fun `start event sets default server URL`() {
39− val core = createCore()
40− core.processEvent(Event.Start)
41− val view = core.currentView()
42− assertEquals("http://localhost:4096", view.serverUrl)
43− assertEquals(Screen.CONNECT, view.screen)
44− }
45−
46− @Test
47− fun `server URL change updates view`() {
48− val core = createCore()
49− core.processEvent(Event.Start)
50− core.processEvent(Event.ServerUrlChanged("http://10.0.0.1:4096"))
51− val view = core.currentView()
52− assertEquals("http://10.0.0.1:4096", view.serverUrl)
53− }
54−
55− @Test
56− fun `connect emits HTTP effect`() {
57− val core = createCore()
58− core.processEvent(Event.Start)
59− val requests = core.processEvent(Event.Connect)
60− assertEquals(1, requests.value.size)
61− assertTrue(requests.value[0].effect is Effect.Http)
62− val view = core.currentView()
63− assertTrue(view.loading)
64− }
65−
66− @Test
67− fun `successful connect transitions to sessions screen`() {
68− val core = createCore()
69− core.processEvent(Event.Start)
70− val requests = core.processEvent(Event.Connect)
71− val httpReq = requests.value[0]
72− assertEquals(Effect.Http::class, httpReq.effect::class)
73−
74− // Simulate health check success — triggers LoadSessions
75− val followUpRequests = core.resolveHttp(httpReq.id, body = """{"healthy":true}""")
76− assertEquals(1, followUpRequests.value.size)
77−
78− // Simulate sessions loaded
79− val sessionsBody = """[{"id":"s1","title":"My Session"}]"""
80− val finalRequests = core.resolveHttp(followUpRequests.value[0].id, body = sessionsBody)
81− assertEquals(0, finalRequests.value.size)
82−
83− val view = core.currentView()
84− assertTrue(view.connected)
85− assertEquals(Screen.SESSIONS, view.screen)
86− assertEquals(1, view.sessions.size)
87− assertEquals("s1", view.sessions[0].id)
88− assertEquals("My Session", view.sessions[0].title)
89− }
90−
91− @Test
92− fun `failed connect shows error`() {
93− val core = createCore()
94− core.processEvent(Event.Start)
95− val requests = core.processEvent(Event.Connect)
96−
97− val errorResult = HttpResult.Err(HttpError.Io("Connection refused"))
98− val effects = core.resolve(requests.value[0].id, errorResult.bincodeSerialize())
99− Requests.bincodeDeserialize(effects)
100−
101− val view = core.currentView()
102− assertNotNull(view.error)
103− assertFalse(view.loading)
104− }
105−
106− @Test
107− fun `dismiss error clears error`() {
108− val core = createCore()
109− core.processEvent(Event.Start)
110− val requests = core.processEvent(Event.Connect)
111−
112− val errorResult = HttpResult.Err(HttpError.Io("Connection refused"))
113− core.resolve(requests.value[0].id, errorResult.bincodeSerialize())
114−
115− core.processEvent(Event.DismissError)
116− val view = core.currentView()
117− assertNull(view.error)
118− }
119−
120− @Test
121− fun `select session loads messages and transitions to chat`() {
122− val core = createCore()
123− core.processEvent(Event.Start)
124− val connectReqs = core.processEvent(Event.Connect)
125− core.resolveHttp(connectReqs.value[0].id, body = """{"healthy":true}""")
126− core.resolveHttp(0u, body = "[]")
127−
128− val selectReqs = core.processEvent(Event.SelectSession("session-123"))
129− assertTrue(selectReqs.value.isNotEmpty())
130−
131− val view = core.currentView()
132− assertEquals("session-123", view.currentSessionId)
133− assertEquals(Screen.CHAT, view.screen)
134− }
135−
136− @Test
137− fun `401 response sets auth_required in view`() {
138− val core = createCore()
139− core.processEvent(Event.Start)
140− val requests = core.processEvent(Event.Connect)
141−
142− // Simulate 401 — server behind basic auth
143− core.resolveHttp(requests.value[0].id, status = 401, body = "Unauthorized")
144−
145− val view = core.currentView()
146− assertTrue(view.authRequired)
147− assertFalse(view.loading)
148− assertEquals(Screen.CONNECT, view.screen)
149− }
150−
151− @Test
152− fun `401 with credentials shows invalid credentials error`() {
153− val core = createCore()
154− core.processEvent(Event.Start)
155− core.processEvent(Event.UsernameChanged("opencode"))
156− core.processEvent(Event.PasswordChanged("wrong"))
157− val requests = core.processEvent(Event.Connect)
158−
159− // Simulate 401 despite credentials — invalid credentials
160− core.resolveHttp(requests.value[0].id, status = 401, body = "Unauthorized")
161−
162− val view = core.currentView()
163− assertNotNull(view.error)
164− assertTrue(view.error!!.contains("Invalid credentials"))
165− assertFalse(view.authRequired)
166− }
167−
168− @Test
169− fun `cancel auth clears auth_required and credentials`() {
170− val core = createCore()
171− core.processEvent(Event.Start)
172− val requests = core.processEvent(Event.Connect)
173− core.resolveHttp(requests.value[0].id, status = 401, body = "Unauthorized")
174−
175− core.processEvent(Event.CancelAuth)
176− val view = core.currentView()
177− assertFalse(view.authRequired)
178− assertEquals("", view.username)
179− assertEquals("", view.password)
180− }
181−
182− @Test
183− fun `successful connect with credentials marks authed`() {
184− val core = createCore()
185− core.processEvent(Event.Start)
186− core.processEvent(Event.UsernameChanged("opencode"))
187− core.processEvent(Event.PasswordChanged("secret"))
188− val requests = core.processEvent(Event.Connect)
189−
190− // Health check with credentials succeeds
191− val followUp = core.resolveHttp(requests.value[0].id, body = """{"healthy":true}""")
192− assertEquals(1, followUp.value.size)
193−
194− val sessionsBody = """[{"id":"s1","title":"Authed Session"}]"""
195− core.resolveHttp(followUp.value[0].id, body = sessionsBody)
196−
197− val view = core.currentView()
198− assertTrue(view.connected)
199− assertEquals(Screen.SESSIONS, view.screen)
200− }
201−}
build.gradle.kts−1
@@ -2,6 +2,5 @@ plugins {
2 alias(libs.plugins.android.application) apply false
2 alias(libs.plugins.android.application) apply false
3 alias(libs.plugins.kotlin.android) apply false
3 alias(libs.plugins.kotlin.android) apply false
4 alias(libs.plugins.kotlin.compose) apply false
4 alias(libs.plugins.kotlin.compose) apply false
5− alias(libs.plugins.android.library) apply false
6 alias(libs.plugins.kotlin.serialization) apply false
5 alias(libs.plugins.kotlin.serialization) apply false
7}
6}
flake.locknew file+61
@@ -0,0 +1,61 @@
1+{
2+ "nodes": {
3+ "flake-utils": {
4+ "inputs": {
5+ "systems": "systems"
6+ },
7+ "locked": {
8+ "lastModified": 1731533236,
9+ "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
10+ "owner": "numtide",
11+ "repo": "flake-utils",
12+ "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
13+ "type": "github"
14+ },
15+ "original": {
16+ "owner": "numtide",
17+ "repo": "flake-utils",
18+ "type": "github"
19+ }
20+ },
21+ "nixpkgs": {
22+ "locked": {
23+ "lastModified": 1783224372,
24+ "narHash": "sha256-8i/87eeoqiGE4yOTjwSA3Eh/ziJRQEmd/unYU+K27sk=",
25+ "owner": "NixOS",
26+ "repo": "nixpkgs",
27+ "rev": "d407951447dcd00442e97087bf374aad70c04cea",
28+ "type": "github"
29+ },
30+ "original": {
31+ "owner": "NixOS",
32+ "ref": "nixos-unstable",
33+ "repo": "nixpkgs",
34+ "type": "github"
35+ }
36+ },
37+ "root": {
38+ "inputs": {
39+ "flake-utils": "flake-utils",
40+ "nixpkgs": "nixpkgs"
41+ }
42+ },
43+ "systems": {
44+ "locked": {
45+ "lastModified": 1681028828,
46+ "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
47+ "owner": "nix-systems",
48+ "repo": "default",
49+ "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
50+ "type": "github"
51+ },
52+ "original": {
53+ "owner": "nix-systems",
54+ "repo": "default",
55+ "type": "github"
56+ }
57+ }
58+ },
59+ "root": "root",
60+ "version": 7
61+}
flake.nix+28−17
@@ -1,5 +1,5 @@
1{
1{
2− description = "Dev environment for opencode-android (Crux Rust core + Kotlin / Jetpack Compose shell)";
2+ description = "Dev environment for opencode-android — a Crux (Rust) core + Kotlin / Jetpack Compose shell";
3
3
4 inputs = {
4 inputs = {
5 nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
5 nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
@@ -9,14 +9,17 @@
9 outputs = { self, nixpkgs, flake-utils }:
9 outputs = { self, nixpkgs, flake-utils }:
10 flake-utils.lib.eachDefaultSystem (system:
10 flake-utils.lib.eachDefaultSystem (system:
11 let
11 let
12− # Versions kept in sync with the Gradle project (compileSdk / build-tools).
12+ # Kept in sync with the Gradle project (see gradle/libs.versions.toml and
13− platformVersion = "36";
13+ # app/build.gradle.kts). These are the versions actually provisioned below,
14− buildToolsVersion = "36.0.0";
14+ # so `compileSdk` / `buildToolsVersion` must match or Gradle will try to
15+ # download SDK components at build time.
16+ platformVersion = "35";
17+ buildToolsVersion = "35.0.0";
15
18
16 pkgs = import nixpkgs {
19 pkgs = import nixpkgs {
17 inherit system;
20 inherit system;
18 config = {
21 config = {
19− allowUnfree = true; # Android SDK is unfree
22+ allowUnfree = true; # the Android SDK is unfree
20 android_sdk.accept_license = true;
23 android_sdk.accept_license = true;
21 };
24 };
22 };
25 };
@@ -28,42 +31,50 @@
28
31
29 includeEmulator = false;
32 includeEmulator = false;
30 includeSystemImages = false;
33 includeSystemImages = false;
31− systemImageTypes = [ "google_apis" ];
32− abiVersions = [ "x86_64" ];
33
34
35+ # The Rust core is NOT cross-compiled to a JNI .so in this setup: nixpkgs'
36+ # `rustc` ships no Android std and no NDK is provisioned. The core is built
37+ # and unit-tested natively (`cargo test`), and the Android shell runs a
38+ # faithful Kotlin port of the reducer. Flip `includeNDK = true` and add
39+ # `cargo-ndk` below to build the real .so once a cross-toolchain is present.
34 includeNDK = false;
40 includeNDK = false;
35 };
41 };
36
42
37− sdk = android.androidsdk;
43+ sdk = android.androidsdk;
38− sdkRoot = "${sdk}/libexec/android-sdk";
44+ sdkRoot = "${sdk}/libexec/android-sdk";
39−
40 aapt2Path = "${sdkRoot}/build-tools/${buildToolsVersion}/aapt2";
45 aapt2Path = "${sdkRoot}/build-tools/${buildToolsVersion}/aapt2";
41 in {
46 in {
42 devShells.default = pkgs.mkShell {
47 devShells.default = pkgs.mkShell {
43 buildInputs = [
48 buildInputs = [
49+ # JVM / Android toolchain
44 pkgs.jdk17
50 pkgs.jdk17
45 pkgs.gradle
51 pkgs.gradle
52+ sdk
53+
54+ # Rust toolchain for the Crux core (build, test, typegen codegen)
46 pkgs.rustc
55 pkgs.rustc
47 pkgs.cargo
56 pkgs.cargo
48− sdk
49 ];
57 ];
50
58
51 ANDROID_HOME = sdkRoot;
59 ANDROID_HOME = sdkRoot;
52 ANDROID_SDK_ROOT = sdkRoot;
60 ANDROID_SDK_ROOT = sdkRoot;
53 JAVA_HOME = "${pkgs.jdk17}";
61 JAVA_HOME = "${pkgs.jdk17}";
54
62
63+ # AGP resolves aapt2 from a Maven artifact by default; point it at the
64+ # SDK-provided binary so the build works fully offline / hermetically.
55 GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${aapt2Path}";
65 GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${aapt2Path}";
56
66
57 shellHook = ''
67 shellHook = ''
58 echo "opencode-android dev shell"
68 echo "opencode-android dev shell"
59− echo " JDK: $(java -version 2>&1 | head -1)"
69+ echo " JDK: $(java -version 2>&1 | head -1)"
60− echo " ANDROID_HOME: $ANDROID_HOME"
61− echo " aapt2: ${aapt2Path}"
62 echo " Rust: $(rustc --version)"
70 echo " Rust: $(rustc --version)"
71+ echo " Gradle: $(gradle --version 2>/dev/null | awk '/^Gradle/{print $2}')"
72+ echo " ANDROID_HOME: $ANDROID_HOME"
63 echo ""
73 echo ""
64− echo "Build: ./gradlew assembleDebug"
74+ echo " Core: (cd shared && cargo test) # Crux core unit tests"
65− echo "Core: cd shared && cargo test"
75+ echo " Types: (cd shared && cargo run --bin codegen)"
66− echo "Device: adb devices"
76+ echo " App: ./gradlew assembleDebug # build debug APK"
77+ echo " Unit: ./gradlew testDebugUnitTest"
67 '';
78 '';
68 };
79 };
69 });
80 });
generated/build.gradle.ktsdeleted−21
@@ -1,21 +0,0 @@
1−plugins {
2− kotlin("jvm") version "2.2.0"
3− kotlin("plugin.serialization") version "2.2.0"
4− `java-library`
5−}
6−
7−group = "soy.iko.opencode.core"
8−version = "1.0.0"
9−
10−repositories {
11− mavenCentral()
12−}
13−
14−dependencies {}
15−
16−tasks.withType<Jar> {
17− manifest {
18− attributes["Implementation-Title"] = "soy.iko.opencode.core"
19− attributes["Implementation-Version"] = "1.0.0"
20− }
21−}
generated/com/novi/bincode/BincodeDeserializer.javanew file+38
@@ -0,0 +1,38 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.bincode;
5+
6+import com.novi.serde.DeserializationError;
7+import com.novi.serde.Slice;
8+import com.novi.serde.BinaryDeserializer;
9+
10+public class BincodeDeserializer extends BinaryDeserializer {
11+ public BincodeDeserializer(byte[] input) {
12+ super(input, Long.MAX_VALUE);
13+ }
14+
15+ public Float deserialize_f32() throws DeserializationError {
16+ return Float.valueOf(getFloat());
17+ }
18+
19+ public Double deserialize_f64() throws DeserializationError {
20+ return Double.valueOf(getDouble());
21+ }
22+
23+ public long deserialize_len() throws DeserializationError {
24+ long value = getLong();
25+ if (value < 0 || value > Integer.MAX_VALUE) {
26+ throw new DeserializationError("Incorrect length value");
27+ }
28+ return value;
29+ }
30+
31+ public int deserialize_variant_index() throws DeserializationError {
32+ return getInt();
33+ }
34+
35+ public void check_that_key_slices_are_increasing(Slice key1, Slice key2) throws DeserializationError {
36+ // Not required by the format.
37+ }
38+}
generated/com/novi/bincode/BincodeDeserializer.ktdeleted−39
@@ -1,39 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.bincode
5−
6−import com.novi.serde.BinaryDeserializer
7−import com.novi.serde.DeserializationError
8−import com.novi.serde.Slice
9−
10−class BincodeDeserializer(input: ByteArray) : BinaryDeserializer(input, Long.MAX_VALUE) {
11− @Throws(DeserializationError::class)
12− override fun deserialize_f32(): Float {
13− return Float.fromBits(getInt())
14− }
15−
16− @Throws(DeserializationError::class)
17− override fun deserialize_f64(): Double {
18− return Double.fromBits(getLong())
19− }
20−
21− @Throws(DeserializationError::class)
22− override fun deserialize_len(): Long {
23− val value = getLong()
24− if (value < 0 || value > Int.MAX_VALUE.toLong()) {
25− throw DeserializationError("Incorrect length value")
26− }
27− return value
28− }
29−
30− @Throws(DeserializationError::class)
31− override fun deserialize_variant_index(): Int {
32− return getInt()
33− }
34−
35− @Throws(DeserializationError::class)
36− override fun check_that_key_slices_are_increasing(key1: Slice, key2: Slice) {
37− // Not required by the format.
38− }
39−}
generated/com/novi/bincode/BincodeSerializer.javanew file+33
@@ -0,0 +1,33 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.bincode;
5+
6+import com.novi.serde.SerializationError;
7+import com.novi.serde.BinarySerializer;
8+
9+public class BincodeSerializer extends BinarySerializer {
10+ public BincodeSerializer() {
11+ super(Long.MAX_VALUE);
12+ }
13+
14+ public void serialize_f32(Float value) throws SerializationError {
15+ serialize_i32(Integer.valueOf(Float.floatToRawIntBits(value.floatValue())));
16+ }
17+
18+ public void serialize_f64(Double value) throws SerializationError {
19+ serialize_i64(Long.valueOf(Double.doubleToRawLongBits(value.doubleValue())));
20+ }
21+
22+ public void serialize_len(long value) throws SerializationError {
23+ serialize_u64(value);
24+ }
25+
26+ public void serialize_variant_index(int value) throws SerializationError {
27+ serialize_u32(value);
28+ }
29+
30+ public void sort_map_entries(int[] offsets) {
31+ // Not required by the format.
32+ }
33+}
generated/com/novi/bincode/BincodeSerializer.ktdeleted−33
@@ -1,33 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.bincode
5−
6−import com.novi.serde.BinarySerializer
7−import com.novi.serde.SerializationError
8−
9−class BincodeSerializer : BinarySerializer(Long.MAX_VALUE) {
10− @Throws(SerializationError::class)
11− override fun serialize_f32(value: Float) {
12− serialize_i32(value.toRawBits())
13− }
14−
15− @Throws(SerializationError::class)
16− override fun serialize_f64(value: Double) {
17− serialize_i64(value.toRawBits())
18− }
19−
20− @Throws(SerializationError::class)
21− override fun serialize_len(value: Long) {
22− serialize_u64(value.toULong())
23− }
24−
25− @Throws(SerializationError::class)
26− override fun serialize_variant_index(value: Int) {
27− serialize_u32(value.toUInt())
28− }
29−
30− override fun sort_map_entries(offsets: IntArray) {
31− // Not required by the format.
32− }
33−}
generated/com/novi/serde/ArrayLen.javanew file+12
@@ -0,0 +1,12 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.lang.annotation.ElementType;
7+import java.lang.annotation.Target;
8+
9+@Target({ElementType.TYPE_USE})
10+public @interface ArrayLen {
11+ int length();
12+}
generated/com/novi/serde/BinaryDeserializer.javanew file+195
@@ -0,0 +1,195 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.nio.ByteBuffer;
7+import java.nio.ByteOrder;
8+import java.nio.charset.CharsetDecoder;
9+import java.nio.charset.StandardCharsets;
10+import java.nio.charset.CharacterCodingException;
11+import java.math.BigInteger;
12+
13+public abstract class BinaryDeserializer implements Deserializer {
14+ protected ByteBuffer input;
15+ private long containerDepthBudget;
16+
17+ public BinaryDeserializer(byte[] input, long maxContainerDepth) {
18+ this.input = ByteBuffer.wrap(input);
19+ this.input.order(ByteOrder.LITTLE_ENDIAN);
20+ containerDepthBudget = maxContainerDepth;
21+ }
22+
23+ public void increase_container_depth() throws DeserializationError {
24+ if (containerDepthBudget == 0) {
25+ throw new DeserializationError("Exceeded maximum container depth");
26+ }
27+ containerDepthBudget -= 1;
28+ }
29+
30+ public void decrease_container_depth() {
31+ containerDepthBudget += 1;
32+ }
33+
34+ public String deserialize_str() throws DeserializationError {
35+ long len = deserialize_len();
36+ if (len < 0 || len > Integer.MAX_VALUE) {
37+ throw new DeserializationError("Incorrect length value for Java string");
38+ }
39+ byte[] content = new byte[(int) len];
40+ read(content);
41+ CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
42+ try {
43+ decoder.decode(ByteBuffer.wrap(content));
44+ } catch (CharacterCodingException ex) {
45+ throw new DeserializationError("Incorrect UTF8 string");
46+ }
47+ return new String(content);
48+ }
49+
50+ public Bytes deserialize_bytes() throws DeserializationError {
51+ long len = deserialize_len();
52+ if (len < 0 || len > Integer.MAX_VALUE) {
53+ throw new DeserializationError("Incorrect length value for Java array");
54+ }
55+ byte[] content = new byte[(int) len];
56+ read(content);
57+ return new Bytes(content);
58+ }
59+
60+ public Boolean deserialize_bool() throws DeserializationError {
61+ byte value = getByte();
62+ if (value == 0) {
63+ return Boolean.valueOf(false);
64+ }
65+ if (value == 1) {
66+ return Boolean.valueOf(true);
67+ }
68+ throw new DeserializationError("Incorrect boolean value");
69+ }
70+
71+ public Unit deserialize_unit() throws DeserializationError {
72+ return new Unit();
73+ }
74+
75+ public Character deserialize_char() throws DeserializationError {
76+ throw new DeserializationError("Not implemented: deserialize_char");
77+ }
78+
79+ public @Unsigned Byte deserialize_u8() throws DeserializationError {
80+ return Byte.valueOf(getByte());
81+ }
82+
83+ public @Unsigned Short deserialize_u16() throws DeserializationError {
84+ return Short.valueOf(getShort());
85+ }
86+
87+ public @Unsigned Integer deserialize_u32() throws DeserializationError {
88+ return Integer.valueOf(getInt());
89+ }
90+
91+ public @Unsigned Long deserialize_u64() throws DeserializationError {
92+ return Long.valueOf(getLong());
93+ }
94+
95+ public @Unsigned @Int128 BigInteger deserialize_u128() throws DeserializationError {
96+ BigInteger signed = deserialize_i128();
97+ if (signed.compareTo(BigInteger.ZERO) >= 0) {
98+ return signed;
99+ } else {
100+ return signed.add(BigInteger.ONE.shiftLeft(128));
101+ }
102+ }
103+
104+ public Byte deserialize_i8() throws DeserializationError {
105+ return Byte.valueOf(getByte());
106+ }
107+
108+ public Short deserialize_i16() throws DeserializationError {
109+ return Short.valueOf(getShort());
110+ }
111+
112+ public Integer deserialize_i32() throws DeserializationError {
113+ return Integer.valueOf(getInt());
114+ }
115+
116+ public Long deserialize_i64() throws DeserializationError {
117+ return Long.valueOf(getLong());
118+ }
119+
120+ public @Int128 BigInteger deserialize_i128() throws DeserializationError {
121+ byte[] content = new byte[16];
122+ read(content);
123+ byte[] reversed = new byte[16];
124+ for (int i = 0; i < 16; i++) {
125+ reversed[i] = content[15 - i];
126+ }
127+ return new BigInteger(reversed);
128+ }
129+
130+ public boolean deserialize_option_tag() throws DeserializationError {
131+ return deserialize_bool().booleanValue();
132+ }
133+
134+ public int get_buffer_offset() {
135+ return input.position();
136+ }
137+
138+ static final String INPUT_NOT_LARGE_ENOUGH = "Input is not large enough";
139+
140+ protected byte getByte() throws DeserializationError {
141+ try {
142+ return input.get();
143+ } catch (java.nio.BufferUnderflowException e) {
144+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
145+ }
146+ }
147+
148+ protected short getShort() throws DeserializationError {
149+ try {
150+ return input.getShort();
151+ } catch (java.nio.BufferUnderflowException e) {
152+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
153+ }
154+ }
155+
156+ protected int getInt() throws DeserializationError {
157+ try {
158+ return input.getInt();
159+ } catch (java.nio.BufferUnderflowException e) {
160+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
161+ }
162+ }
163+
164+ protected long getLong() throws DeserializationError {
165+ try {
166+ return input.getLong();
167+ } catch (java.nio.BufferUnderflowException e) {
168+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
169+ }
170+ }
171+
172+ protected float getFloat() throws DeserializationError {
173+ try {
174+ return input.getFloat();
175+ } catch (java.nio.BufferUnderflowException e) {
176+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
177+ }
178+ }
179+
180+ protected double getDouble() throws DeserializationError {
181+ try {
182+ return input.getDouble();
183+ } catch (java.nio.BufferUnderflowException e) {
184+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
185+ }
186+ }
187+
188+ protected void read(byte[] content) throws DeserializationError {
189+ try {
190+ input.get(content);
191+ } catch (java.nio.BufferUnderflowException e) {
192+ throw new DeserializationError(INPUT_NOT_LARGE_ENOUGH);
193+ }
194+ }
195+}
generated/com/novi/serde/BinaryDeserializer.ktdeleted−182
@@ -1,182 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−abstract class BinaryDeserializer(
7− protected val input: ByteArray,
8− maxContainerDepth: Long
9−) : Deserializer {
10− private var position: Int = 0
11− private var containerDepthBudget: Long = maxContainerDepth
12−
13− @Throws(DeserializationError::class)
14− override fun increase_container_depth() {
15− if (containerDepthBudget == 0L) {
16− throw DeserializationError("Exceeded maximum container depth")
17− }
18− containerDepthBudget -= 1
19− }
20−
21− override fun decrease_container_depth() {
22− containerDepthBudget += 1
23− }
24−
25− @Throws(DeserializationError::class)
26− override fun deserialize_str(): String {
27− val len = deserialize_len()
28− if (len < 0 || len > Int.MAX_VALUE.toLong()) {
29− throw DeserializationError("Incorrect length value for Kotlin string")
30− }
31− val content = readBytes(len.toInt())
32− return try {
33− content.decodeToString(throwOnInvalidSequence = true)
34− } catch (e: Throwable) {
35− throw DeserializationError("Incorrect UTF8 string")
36− }
37− }
38−
39− @Throws(DeserializationError::class)
40− override fun deserialize_bytes(): Bytes {
41− val len = deserialize_len()
42− if (len < 0 || len > Int.MAX_VALUE.toLong()) {
43− throw DeserializationError("Incorrect length value for Kotlin array")
44− }
45− return Bytes(readBytes(len.toInt()))
46− }
47−
48− @Throws(DeserializationError::class)
49− override fun deserialize_bool(): Boolean {
50− val value = getByte()
51− return when (value.toInt()) {
52− 0 -> false
53− 1 -> true
54− else -> throw DeserializationError("Incorrect boolean value")
55− }
56− }
57−
58− @Throws(DeserializationError::class)
59− override fun deserialize_unit(): Unit {
60− return Unit
61− }
62−
63− @Throws(DeserializationError::class)
64− override fun deserialize_char(): Char {
65− throw DeserializationError("Not implemented: deserialize_char")
66− }
67−
68− @Throws(DeserializationError::class)
69− override fun deserialize_u8(): UByte {
70− return getByte().toUByte()
71− }
72−
73− @Throws(DeserializationError::class)
74− override fun deserialize_u16(): UShort {
75− val b0 = getByte().toInt() and 0xff
76− val b1 = getByte().toInt() and 0xff
77− return (b0 or (b1 shl 8)).toUShort()
78− }
79−
80− @Throws(DeserializationError::class)
81− override fun deserialize_u32(): UInt {
82− val b0 = getByte().toInt() and 0xff
83− val b1 = getByte().toInt() and 0xff
84− val b2 = getByte().toInt() and 0xff
85− val b3 = getByte().toInt() and 0xff
86− return (b0 or (b1 shl 8) or (b2 shl 16) or (b3 shl 24)).toUInt()
87− }
88−
89− @Throws(DeserializationError::class)
90− override fun deserialize_u64(): ULong {
91− var value = 0uL
92− for (shift in 0 until 64 step 8) {
93− val byteValue = getByte().toULong() and 0xffuL
94− value = value or (byteValue shl shift)
95− }
96− return value
97− }
98−
99− @Throws(DeserializationError::class)
100− override fun deserialize_u128(): UInt128 {
101− val low = deserialize_u64()
102− val high = deserialize_u64()
103− return UInt128(high = high, low = low)
104− }
105−
106− @Throws(DeserializationError::class)
107− override fun deserialize_i8(): Byte {
108− return getByte()
109− }
110−
111− @Throws(DeserializationError::class)
112− override fun deserialize_i16(): Short {
113− return deserialize_u16().toShort()
114− }
115−
116− @Throws(DeserializationError::class)
117− override fun deserialize_i32(): Int {
118− return deserialize_u32().toInt()
119− }
120−
121− @Throws(DeserializationError::class)
122− override fun deserialize_i64(): Long {
123− return deserialize_u64().toLong()
124− }
125−
126− @Throws(DeserializationError::class)
127− override fun deserialize_i128(): Int128 {
128− val low = deserialize_u64()
129− val high = deserialize_i64()
130− return Int128(high = high, low = low)
131− }
132−
133− @Throws(DeserializationError::class)
134− override fun deserialize_option_tag(): Boolean {
135− return deserialize_bool()
136− }
137−
138− override fun get_buffer_offset(): Int {
139− return position
140− }
141−
142− protected fun getInt(): Int {
143− val b0 = getByte().toInt() and 0xff
144− val b1 = getByte().toInt() and 0xff
145− val b2 = getByte().toInt() and 0xff
146− val b3 = getByte().toInt() and 0xff
147− return b0 or (b1 shl 8) or (b2 shl 16) or (b3 shl 24)
148− }
149−
150− protected fun getLong(): Long {
151− var value = 0L
152− for (shift in 0 until 64 step 8) {
153− val byteValue = getByte().toLong() and 0xffL
154− value = value or (byteValue shl shift)
155− }
156− return value
157− }
158−
159− protected fun getByte(): Byte {
160− requireAvailable(1)
161− val value = input[position]
162− position += 1
163− return value
164− }
165−
166− private fun readBytes(count: Int): ByteArray {
167− requireAvailable(count)
168− val slice = input.copyOfRange(position, position + count)
169− position += count
170− return slice
171− }
172−
173− private fun requireAvailable(count: Int) {
174− if (position + count > input.size) {
175− throw DeserializationError(INPUT_NOT_LARGE_ENOUGH)
176− }
177− }
178−
179− companion object {
180− private const val INPUT_NOT_LARGE_ENOUGH = "Input is not large enough"
181− }
182−}
generated/com/novi/serde/BinarySerializer.javanew file+146
@@ -0,0 +1,146 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.math.BigInteger;
7+
8+public abstract class BinarySerializer implements Serializer {
9+ protected MyByteArrayOutputStream output;
10+ private long containerDepthBudget;
11+
12+ public BinarySerializer(long maxContainerDepth) {
13+ output = new BinarySerializer.MyByteArrayOutputStream();
14+ containerDepthBudget = maxContainerDepth;
15+ }
16+
17+ public void increase_container_depth() throws SerializationError {
18+ if (containerDepthBudget == 0) {
19+ throw new SerializationError("Exceeded maximum container depth");
20+ }
21+ containerDepthBudget -= 1;
22+ }
23+
24+ public void decrease_container_depth() {
25+ containerDepthBudget += 1;
26+ }
27+
28+ public void serialize_str(String value) throws SerializationError {
29+ serialize_bytes(new Bytes(value.getBytes()));
30+ }
31+
32+ public void serialize_bytes(Bytes value) throws SerializationError {
33+ byte[] content = value.content();
34+ serialize_len(content.length);
35+ output.write(content, 0, content.length);
36+ }
37+
38+ public void serialize_bool(Boolean value) throws SerializationError {
39+ output.write((value.booleanValue() ? 1 : 0));
40+ }
41+
42+ public void serialize_unit(Unit value) throws SerializationError {
43+ }
44+
45+ public void serialize_char(Character value) throws SerializationError {
46+ throw new SerializationError("Not implemented: serialize_char");
47+ }
48+
49+ public void serialize_u8(@Unsigned Byte value) throws SerializationError {
50+ output.write(value.byteValue());
51+ }
52+
53+ public void serialize_u16(@Unsigned Short value) throws SerializationError {
54+ short val = value.shortValue();
55+ output.write((byte) (val >>> 0));
56+ output.write((byte) (val >>> 8));
57+ }
58+
59+ public void serialize_u32(@Unsigned Integer value) throws SerializationError {
60+ int val = value.intValue();
61+ output.write((byte) (val >>> 0));
62+ output.write((byte) (val >>> 8));
63+ output.write((byte) (val >>> 16));
64+ output.write((byte) (val >>> 24));
65+ }
66+
67+ public void serialize_u64(@Unsigned Long value) throws SerializationError {
68+ long val = value.longValue();
69+ output.write((byte) (val >>> 0));
70+ output.write((byte) (val >>> 8));
71+ output.write((byte) (val >>> 16));
72+ output.write((byte) (val >>> 24));
73+ output.write((byte) (val >>> 32));
74+ output.write((byte) (val >>> 40));
75+ output.write((byte) (val >>> 48));
76+ output.write((byte) (val >>> 56));
77+ }
78+
79+ public void serialize_u128(@Unsigned @Int128 BigInteger value) throws SerializationError {
80+ if (value.compareTo(BigInteger.ZERO) < 0 || !value.shiftRight(128).equals(BigInteger.ZERO)) {
81+ throw new java.lang.IllegalArgumentException("Invalid value for an unsigned int128");
82+ }
83+ byte[] content = value.toByteArray();
84+ // BigInteger.toByteArray() may add a most-significant zero
85+ // byte for signing purpose: ignore it.
86+ assert content.length <= 16 || content[0] == 0;
87+ int len = Math.min(content.length, 16);
88+ // Write content in little-endian order.
89+ for (int i = 0; i < len; i++) {
90+ output.write(content[content.length - 1 - i]);
91+ }
92+ // Complete with zeros if needed.
93+ for (int i = len; i < 16; i++) {
94+ output.write(0);
95+ }
96+ }
97+
98+ public void serialize_i8(Byte value) throws SerializationError {
99+ serialize_u8(value);
100+ }
101+
102+ public void serialize_i16(Short value) throws SerializationError {
103+ serialize_u16(value);
104+ }
105+
106+ public void serialize_i32(Integer value) throws SerializationError {
107+ serialize_u32(value);
108+ }
109+
110+ public void serialize_i64(Long value) throws SerializationError {
111+ serialize_u64(value);
112+ }
113+
114+ public void serialize_i128(@Int128 BigInteger value) throws SerializationError {
115+ if (value.compareTo(BigInteger.ZERO) >= 0) {
116+ if (!value.shiftRight(127).equals(BigInteger.ZERO)) {
117+ throw new java.lang.IllegalArgumentException("Invalid value for a signed int128");
118+ }
119+ serialize_u128(value);
120+ } else {
121+ if (!value.add(BigInteger.ONE).negate().shiftRight(127).equals(BigInteger.ZERO)) {
122+ throw new java.lang.IllegalArgumentException("Invalid value for a signed int128");
123+ }
124+ serialize_u128(value.add(BigInteger.ONE.shiftLeft(128)));
125+ }
126+ }
127+
128+ public void serialize_option_tag(boolean value) throws SerializationError {
129+ output.write((value ? (byte) 1 : (byte) 0));
130+ }
131+
132+ public int get_buffer_offset() {
133+ return output.size();
134+ }
135+
136+ public byte[] get_bytes() {
137+ return output.toByteArray();
138+ }
139+
140+ // Local extension to provide access to the underlying buffer.
141+ static public class MyByteArrayOutputStream extends java.io.ByteArrayOutputStream {
142+ public byte[] getBuffer() {
143+ return buf;
144+ }
145+ }
146+}
generated/com/novi/serde/BinarySerializer.ktdeleted−122
@@ -1,122 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−abstract class BinarySerializer(maxContainerDepth: Long) : Serializer {
7− protected val output: SerdeByteArrayOutput = SerdeByteArrayOutput()
8− private var containerDepthBudget: Long = maxContainerDepth
9−
10− @Throws(SerializationError::class)
11− override fun increase_container_depth() {
12− if (containerDepthBudget == 0L) {
13− throw SerializationError("Exceeded maximum container depth")
14− }
15− containerDepthBudget -= 1
16− }
17−
18− override fun decrease_container_depth() {
19− containerDepthBudget += 1
20− }
21−
22− @Throws(SerializationError::class)
23− override fun serialize_str(value: String) {
24− serialize_bytes(Bytes(value.encodeToByteArray()))
25− }
26−
27− @Throws(SerializationError::class)
28− override fun serialize_bytes(value: Bytes) {
29− serialize_len(value.content.size.toLong())
30− output.writeBytes(value.content, 0, value.content.size)
31− }
32−
33− @Throws(SerializationError::class)
34− override fun serialize_bool(value: Boolean) {
35− output.writeByte(if (value) 1.toByte() else 0.toByte())
36− }
37−
38− @Throws(SerializationError::class)
39− override fun serialize_unit(value: Unit) {
40− // Nothing to serialize.
41− }
42−
43− @Throws(SerializationError::class)
44− override fun serialize_char(value: Char) {
45− throw SerializationError("Not implemented: serialize_char")
46− }
47−
48− @Throws(SerializationError::class)
49− override fun serialize_u8(value: UByte) {
50− output.writeByte(value.toByte())
51− }
52−
53− @Throws(SerializationError::class)
54− override fun serialize_u16(value: UShort) {
55− val v = value.toInt()
56− output.writeByte((v and 0xff).toByte())
57− output.writeByte(((v ushr 8) and 0xff).toByte())
58− }
59−
60− @Throws(SerializationError::class)
61− override fun serialize_u32(value: UInt) {
62− val v = value.toInt()
63− output.writeByte((v and 0xff).toByte())
64− output.writeByte(((v ushr 8) and 0xff).toByte())
65− output.writeByte(((v ushr 16) and 0xff).toByte())
66− output.writeByte(((v ushr 24) and 0xff).toByte())
67− }
68−
69− @Throws(SerializationError::class)
70− override fun serialize_u64(value: ULong) {
71− var v = value
72− for (i in 0 until 8) {
73− output.writeByte((v and 0xffuL).toByte())
74− v = v shr 8
75− }
76− }
77−
78− @Throws(SerializationError::class)
79− override fun serialize_u128(value: UInt128) {
80− serialize_u64(value.low)
81− serialize_u64(value.high)
82− }
83−
84− @Throws(SerializationError::class)
85− override fun serialize_i8(value: Byte) {
86− serialize_u8(value.toUByte())
87− }
88−
89− @Throws(SerializationError::class)
90− override fun serialize_i16(value: Short) {
91− serialize_u16(value.toUShort())
92− }
93−
94− @Throws(SerializationError::class)
95− override fun serialize_i32(value: Int) {
96− serialize_u32(value.toUInt())
97− }
98−
99− @Throws(SerializationError::class)
100− override fun serialize_i64(value: Long) {
101− serialize_u64(value.toULong())
102− }
103−
104− @Throws(SerializationError::class)
105− override fun serialize_i128(value: Int128) {
106− serialize_u64(value.low)
107− serialize_i64(value.high)
108− }
109−
110− @Throws(SerializationError::class)
111− override fun serialize_option_tag(value: Boolean) {
112− output.writeByte(if (value) 1.toByte() else 0.toByte())
113− }
114−
115− override fun get_buffer_offset(): Int {
116− return output.size()
117− }
118−
119− override fun get_bytes(): ByteArray {
120− return output.toByteArray()
121− }
122−}
generated/com/novi/serde/Bytes.javanew file+54
@@ -0,0 +1,54 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.util.Arrays;
7+import java.util.Objects;
8+
9+/**
10+ * Immutable wrapper class around byte[].
11+ *
12+ * Enforces value-semantice for `equals` and `hashCode`.
13+ */
14+public final class Bytes {
15+ private final byte[] content;
16+
17+ private static final Bytes EMPTY = new Bytes(new byte[0]);
18+
19+ /// Low-level constructor (use with care).
20+ public Bytes(byte[] content) {
21+ Objects.requireNonNull(content, "content must not be null");
22+ this.content = content;
23+ }
24+
25+ public static Bytes empty() {
26+ return EMPTY;
27+ }
28+
29+ public static Bytes valueOf(byte[] content) {
30+ Objects.requireNonNull(content, "content must not be null");
31+ if (content.length == 0) {
32+ return EMPTY;
33+ } else {
34+ return new Bytes(content.clone());
35+ }
36+ }
37+
38+ public byte[] content() {
39+ return this.content.clone();
40+ }
41+
42+ public boolean equals(Object obj) {
43+ if (this == obj) return true;
44+ if (obj == null) return false;
45+ if (getClass() != obj.getClass()) return false;
46+ Bytes other = (Bytes) obj;
47+ return Arrays.equals(this.content, other.content);
48+ }
49+
50+ public int hashCode() {
51+ return Arrays.hashCode(content);
52+ }
53+
54+}
generated/com/novi/serde/Bytes.ktdeleted−39
@@ -1,39 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−/**
7− * Inline value class wrapper around ByteArray.
8− *
9− * Provides proper value semantics for `equals` and `hashCode` using
10− * structural equality (contentEquals/contentHashCode) instead of
11− * referential equality.
12− *
13− * As a value class, this wrapper has zero runtime overhead - it's
14− * inlined at compile time and compiles down to ByteArray at runtime.
15− */
16−@JvmInline
17−value class Bytes(val content: ByteArray) {
18− override fun toString(): String = content.contentToString()
19−
20− companion object {
21− fun empty(): Bytes = Bytes(ByteArray(0))
22−
23− fun valueOf(content: ByteArray): Bytes = Bytes(content)
24− }
25−}
26−
27−/**
28− * Extension function for structural equality comparison.
29− * Required because value classes don't support overriding equals.
30− */
31−fun Bytes.contentEquals(other: Bytes): Boolean =
32− this.content.contentEquals(other.content)
33−
34−/**
35− * Extension function for structural hash code.
36− * Required because value classes don't support overriding hashCode.
37− */
38−fun Bytes.contentHashCode(): Int =
39− content.contentHashCode()
generated/com/novi/serde/DeserializationError.javanew file+11
@@ -0,0 +1,11 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+@SuppressWarnings("serial")
7+public final class DeserializationError extends Exception {
8+ public DeserializationError(String s) {
9+ super(s);
10+ }
11+}
generated/com/novi/serde/DeserializationError.ktdeleted−6
@@ -1,6 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−class DeserializationError(message: String) : Exception(message)
generated/com/novi/serde/Deserializer.javanew file+56
@@ -0,0 +1,56 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.math.BigInteger;
7+
8+public interface Deserializer {
9+ String deserialize_str() throws DeserializationError;
10+
11+ Bytes deserialize_bytes() throws DeserializationError;
12+
13+ Boolean deserialize_bool() throws DeserializationError;
14+
15+ Unit deserialize_unit() throws DeserializationError;
16+
17+ Character deserialize_char() throws DeserializationError;
18+
19+ Float deserialize_f32() throws DeserializationError;
20+
21+ Double deserialize_f64() throws DeserializationError;
22+
23+ @Unsigned Byte deserialize_u8() throws DeserializationError;
24+
25+ @Unsigned Short deserialize_u16() throws DeserializationError;
26+
27+ @Unsigned Integer deserialize_u32() throws DeserializationError;
28+
29+ @Unsigned Long deserialize_u64() throws DeserializationError;
30+
31+ @Unsigned @Int128 BigInteger deserialize_u128() throws DeserializationError;
32+
33+ Byte deserialize_i8() throws DeserializationError;
34+
35+ Short deserialize_i16() throws DeserializationError;
36+
37+ Integer deserialize_i32() throws DeserializationError;
38+
39+ Long deserialize_i64() throws DeserializationError;
40+
41+ @Int128 BigInteger deserialize_i128() throws DeserializationError;
42+
43+ long deserialize_len() throws DeserializationError;
44+
45+ int deserialize_variant_index() throws DeserializationError;
46+
47+ boolean deserialize_option_tag() throws DeserializationError;
48+
49+ void increase_container_depth() throws DeserializationError;
50+
51+ void decrease_container_depth();
52+
53+ int get_buffer_offset();
54+
55+ void check_that_key_slices_are_increasing(Slice key1, Slice key2) throws DeserializationError;
56+}
generated/com/novi/serde/Deserializer.ktdeleted−76
@@ -1,76 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−interface Deserializer {
7− @Throws(DeserializationError::class)
8− fun deserialize_str(): String
9−
10− @Throws(DeserializationError::class)
11− fun deserialize_bytes(): Bytes
12−
13− @Throws(DeserializationError::class)
14− fun deserialize_bool(): Boolean
15−
16− @Throws(DeserializationError::class)
17− fun deserialize_unit(): Unit
18−
19− @Throws(DeserializationError::class)
20− fun deserialize_char(): Char
21−
22− @Throws(DeserializationError::class)
23− fun deserialize_f32(): Float
24−
25− @Throws(DeserializationError::class)
26− fun deserialize_f64(): Double
27−
28− @Throws(DeserializationError::class)
29− fun deserialize_u8(): UByte
30−
31− @Throws(DeserializationError::class)
32− fun deserialize_u16(): UShort
33−
34− @Throws(DeserializationError::class)
35− fun deserialize_u32(): UInt
36−
37− @Throws(DeserializationError::class)
38− fun deserialize_u64(): ULong
39−
40− @Throws(DeserializationError::class)
41− fun deserialize_u128(): UInt128
42−
43− @Throws(DeserializationError::class)
44− fun deserialize_i8(): Byte
45−
46− @Throws(DeserializationError::class)
47− fun deserialize_i16(): Short
48−
49− @Throws(DeserializationError::class)
50− fun deserialize_i32(): Int
51−
52− @Throws(DeserializationError::class)
53− fun deserialize_i64(): Long
54−
55− @Throws(DeserializationError::class)
56− fun deserialize_i128(): Int128
57−
58− @Throws(DeserializationError::class)
59− fun deserialize_len(): Long
60−
61− @Throws(DeserializationError::class)
62− fun deserialize_variant_index(): Int
63−
64− @Throws(DeserializationError::class)
65− fun deserialize_option_tag(): Boolean
66−
67− @Throws(DeserializationError::class)
68− fun increase_container_depth()
69−
70− fun decrease_container_depth()
71−
72− fun get_buffer_offset(): Int
73−
74− @Throws(DeserializationError::class)
75− fun check_that_key_slices_are_increasing(key1: Slice, key2: Slice)
76−}
generated/com/novi/serde/Int128.javanew file+11
@@ -0,0 +1,11 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.lang.annotation.ElementType;
7+import java.lang.annotation.Target;
8+
9+@Target({ElementType.TYPE_USE})
10+public @interface Int128 {
11+}
generated/com/novi/serde/Int128.ktdeleted−6
@@ -1,6 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−data class Int128(val high: Long, val low: ULong)
generated/com/novi/serde/SerdeByteArrayOutput.ktdeleted−48
@@ -1,48 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−class SerdeByteArrayOutput(initialCapacity: Int = 32) {
7− private var buffer: ByteArray = ByteArray(initialCapacity)
8− private var length: Int = 0
9−
10− fun writeByte(value: Byte) {
11− ensureCapacity(1)
12− buffer[length] = value
13− length += 1
14− }
15−
16− fun writeBytes(value: ByteArray, offset: Int, count: Int) {
17− if (count == 0) {
18− return
19− }
20− ensureCapacity(count)
21− value.copyInto(buffer, destinationOffset = length, startIndex = offset, endIndex = offset + count)
22− length += count
23− }
24−
25− fun size(): Int {
26− return length
27− }
28−
29− fun toByteArray(): ByteArray {
30− return buffer.copyOf(length)
31− }
32−
33− fun getBuffer(): ByteArray {
34− return buffer
35− }
36−
37− private fun ensureCapacity(extra: Int) {
38− val required = length + extra
39− if (required <= buffer.size) {
40− return
41− }
42− var newSize = buffer.size
43− while (newSize < required) {
44− newSize = newSize * 2
45− }
46− buffer = buffer.copyOf(newSize)
47− }
48−}
generated/com/novi/serde/SerializationError.javanew file+11
@@ -0,0 +1,11 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+@SuppressWarnings("serial")
7+public final class SerializationError extends Exception {
8+ public SerializationError(String s) {
9+ super(s);
10+ }
11+}
generated/com/novi/serde/SerializationError.ktdeleted−6
@@ -1,6 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−class SerializationError(message: String) : Exception(message)
generated/com/novi/serde/Serializer.javanew file+58
@@ -0,0 +1,58 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.math.BigInteger;
7+
8+public interface Serializer {
9+ void serialize_str(String value) throws SerializationError;
10+
11+ void serialize_bytes(Bytes value) throws SerializationError;
12+
13+ void serialize_bool(Boolean value) throws SerializationError;
14+
15+ void serialize_unit(Unit value) throws SerializationError;
16+
17+ void serialize_char(Character value) throws SerializationError;
18+
19+ void serialize_f32(Float value) throws SerializationError;
20+
21+ void serialize_f64(Double value) throws SerializationError;
22+
23+ void serialize_u8(@Unsigned Byte value) throws SerializationError;
24+
25+ void serialize_u16(@Unsigned Short value) throws SerializationError;
26+
27+ void serialize_u32(@Unsigned Integer value) throws SerializationError;
28+
29+ void serialize_u64(@Unsigned Long value) throws SerializationError;
30+
31+ void serialize_u128(@Unsigned @Int128 BigInteger value) throws SerializationError;
32+
33+ void serialize_i8(Byte value) throws SerializationError;
34+
35+ void serialize_i16(Short value) throws SerializationError;
36+
37+ void serialize_i32(Integer value) throws SerializationError;
38+
39+ void serialize_i64(Long value) throws SerializationError;
40+
41+ void serialize_i128(@Int128 BigInteger value) throws SerializationError;
42+
43+ void serialize_len(long value) throws SerializationError;
44+
45+ void serialize_variant_index(int value) throws SerializationError;
46+
47+ void serialize_option_tag(boolean value) throws SerializationError;
48+
49+ void increase_container_depth() throws SerializationError;
50+
51+ void decrease_container_depth();
52+
53+ int get_buffer_offset();
54+
55+ void sort_map_entries(int[] offsets);
56+
57+ byte[] get_bytes();
58+}
generated/com/novi/serde/Serializer.ktdeleted−77
@@ -1,77 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−interface Serializer {
7− @Throws(SerializationError::class)
8− fun serialize_str(value: String)
9−
10− @Throws(SerializationError::class)
11− fun serialize_bytes(value: Bytes)
12−
13− @Throws(SerializationError::class)
14− fun serialize_bool(value: Boolean)
15−
16− @Throws(SerializationError::class)
17− fun serialize_unit(value: Unit)
18−
19− @Throws(SerializationError::class)
20− fun serialize_char(value: Char)
21−
22− @Throws(SerializationError::class)
23− fun serialize_f32(value: Float)
24−
25− @Throws(SerializationError::class)
26− fun serialize_f64(value: Double)
27−
28− @Throws(SerializationError::class)
29− fun serialize_u8(value: UByte)
30−
31− @Throws(SerializationError::class)
32− fun serialize_u16(value: UShort)
33−
34− @Throws(SerializationError::class)
35− fun serialize_u32(value: UInt)
36−
37− @Throws(SerializationError::class)
38− fun serialize_u64(value: ULong)
39−
40− @Throws(SerializationError::class)
41− fun serialize_u128(value: UInt128)
42−
43− @Throws(SerializationError::class)
44− fun serialize_i8(value: Byte)
45−
46− @Throws(SerializationError::class)
47− fun serialize_i16(value: Short)
48−
49− @Throws(SerializationError::class)
50− fun serialize_i32(value: Int)
51−
52− @Throws(SerializationError::class)
53− fun serialize_i64(value: Long)
54−
55− @Throws(SerializationError::class)
56− fun serialize_i128(value: Int128)
57−
58− @Throws(SerializationError::class)
59− fun serialize_len(value: Long)
60−
61− @Throws(SerializationError::class)
62− fun serialize_variant_index(value: Int)
63−
64− @Throws(SerializationError::class)
65− fun serialize_option_tag(value: Boolean)
66−
67− @Throws(SerializationError::class)
68− fun increase_container_depth()
69−
70− fun decrease_container_depth()
71−
72− fun get_buffer_offset(): Int
73−
74− fun sort_map_entries(offsets: IntArray)
75−
76− fun get_bytes(): ByteArray
77−}
generated/com/novi/serde/Slice.javanew file+40
@@ -0,0 +1,40 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+public final class Slice {
7+ public final int start;
8+ public final int end;
9+
10+ public Slice(int start, int end) {
11+ this.start = start;
12+ this.end = end;
13+ }
14+
15+ // Lexicographic comparison between the (unsigned!) bytes referenced by `slice1` and `slice2`
16+ // into `content`.
17+ public static int compare_bytes(byte[] content, Slice slice1, Slice slice2) {
18+ int start1 = slice1.start;
19+ int end1 = slice1.end;
20+ int start2 = slice2.start;
21+ int end2 = slice2.end;
22+ for (int i = 0; i < end1 - start1; i++) {
23+ int byte1 = content[start1 + i] & 0xFF;
24+ if (start2 + i >= end2) {
25+ return 1;
26+ }
27+ int byte2 = content[start2 + i] & 0xFF;
28+ if (byte1 > byte2) {
29+ return 1;
30+ }
31+ if (byte1 < byte2) {
32+ return -1;
33+ }
34+ }
35+ if (end2 - start2 > end1 - start1) {
36+ return -1;
37+ }
38+ return 0;
39+ }
40+}
generated/com/novi/serde/Slice.ktdeleted−36
@@ -1,36 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−data class Slice(val start: Int, val end: Int) {
7− companion object {
8− fun compare_bytes(content: ByteArray, slice1: Slice, slice2: Slice): Int {
9− val start1 = slice1.start
10− val end1 = slice1.end
11− val start2 = slice2.start
12− val end2 = slice2.end
13− var i = 0
14− while (i < end1 - start1) {
15− val index1 = start1 + i
16− val index2 = start2 + i
17− val byte1 = content[index1].toInt() and 0xff
18− if (index2 >= end2) {
19− return 1
20− }
21− val byte2 = content[index2].toInt() and 0xff
22− if (byte1 > byte2) {
23− return 1
24− }
25− if (byte1 < byte2) {
26− return -1
27− }
28− i += 1
29− }
30− if (end2 - start2 > end1 - start1) {
31− return -1
32− }
33− return 0
34− }
35− }
36−}
generated/com/novi/serde/Tuple2.javanew file+40
@@ -0,0 +1,40 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.util.Objects;
7+
8+public final class Tuple2<T0, T1> {
9+ public final T0 field0;
10+ public final T1 field1;
11+
12+ public Tuple2(T0 f0, T1 f1) {
13+ Objects.requireNonNull(f0, "f0 must not be null");
14+ Objects.requireNonNull(f1, "f1 must not be null");
15+ this.field0 = f0;
16+ this.field1 = f1;
17+ }
18+
19+ public boolean equals(Object obj) {
20+ if (this == obj) return true;
21+ if (obj == null) return false;
22+ if (getClass() != obj.getClass()) return false;
23+ Tuple2<?,?> other = (Tuple2) obj;
24+ if (!Objects.equals(this.field0, other.field0)) {
25+ return false;
26+ }
27+ if (!Objects.equals(this.field1, other.field1)) {
28+ return false;
29+ }
30+ return true;
31+ }
32+
33+ public int hashCode() {
34+ int value = 7;
35+ value = 31 * value + (this.field0 != null ? this.field0.hashCode() : 0);
36+ value = 31 * value + (this.field1 != null ? this.field1.hashCode() : 0);
37+ return value;
38+ }
39+
40+}
generated/com/novi/serde/Tuple3.javanew file+46
@@ -0,0 +1,46 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.util.Objects;
7+
8+public final class Tuple3<T0, T1, T2> {
9+ public final T0 field0;
10+ public final T1 field1;
11+ public final T2 field2;
12+
13+ public Tuple3(T0 f0, T1 f1, T2 f2) {
14+ Objects.requireNonNull(f0, "f0 must not be null");
15+ Objects.requireNonNull(f1, "f1 must not be null");
16+ Objects.requireNonNull(f2, "f2 must not be null");
17+ this.field0 = f0;
18+ this.field1 = f1;
19+ this.field2 = f2;
20+ }
21+
22+ public boolean equals(Object obj) {
23+ if (this == obj) return true;
24+ if (obj == null) return false;
25+ if (getClass() != obj.getClass()) return false;
26+ Tuple3<?,?,?> other = (Tuple3) obj;
27+ if (!Objects.equals(this.field0, other.field0)) {
28+ return false;
29+ }
30+ if (!Objects.equals(this.field1, other.field1)) {
31+ return false;
32+ }
33+ if (!Objects.equals(this.field2, other.field2)) {
34+ return false;
35+ }
36+ return true;
37+ }
38+
39+ public int hashCode() {
40+ int value = 7;
41+ value = 31 * value + (this.field0 != null ? this.field0.hashCode() : 0);
42+ value = 31 * value + (this.field1 != null ? this.field1.hashCode() : 0);
43+ value = 31 * value + (this.field2 != null ? this.field2.hashCode() : 0);
44+ return value;
45+ }
46+}
generated/com/novi/serde/Tuple4.javanew file+54
@@ -0,0 +1,54 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.util.Objects;
7+
8+public final class Tuple4<T0, T1, T2, T3> {
9+ public final T0 field0;
10+ public final T1 field1;
11+ public final T2 field2;
12+ public final T3 field3;
13+
14+ public Tuple4(T0 f0, T1 f1, T2 f2, T3 f3) {
15+ Objects.requireNonNull(f0, "f0 must not be null");
16+ Objects.requireNonNull(f1, "f1 must not be null");
17+ Objects.requireNonNull(f2, "f2 must not be null");
18+ Objects.requireNonNull(f3, "f3 must not be null");
19+ this.field0 = f0;
20+ this.field1 = f1;
21+ this.field2 = f2;
22+ this.field3 = f3;
23+ }
24+
25+ public boolean equals(Object obj) {
26+ if (this == obj) return true;
27+ if (obj == null) return false;
28+ if (getClass() != obj.getClass()) return false;
29+ Tuple4<?,?,?,?> other = (Tuple4) obj;
30+ if (!Objects.equals(this.field0, other.field0)) {
31+ return false;
32+ }
33+ if (!Objects.equals(this.field1, other.field1)) {
34+ return false;
35+ }
36+ if (!Objects.equals(this.field2, other.field2)) {
37+ return false;
38+ }
39+ if (!Objects.equals(this.field3, other.field3)) {
40+ return false;
41+ }
42+ return true;
43+ }
44+
45+ public int hashCode() {
46+ int value = 7;
47+ value = 31 * value + (this.field0 != null ? this.field0.hashCode() : 0);
48+ value = 31 * value + (this.field1 != null ? this.field1.hashCode() : 0);
49+ value = 31 * value + (this.field2 != null ? this.field2.hashCode() : 0);
50+ value = 31 * value + (this.field3 != null ? this.field3.hashCode() : 0);
51+ return value;
52+ }
53+
54+}
generated/com/novi/serde/Tuple4.ktdeleted−6
@@ -1,6 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−data class Tuple4<T0, T1, T2, T3>(val field0: T0, val field1: T1, val field2: T2, val field3: T3)
generated/com/novi/serde/Tuple5.javanew file+61
@@ -0,0 +1,61 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.util.Objects;
7+
8+public final class Tuple5<T0, T1, T2, T3, T4> {
9+ public final T0 field0;
10+ public final T1 field1;
11+ public final T2 field2;
12+ public final T3 field3;
13+ public final T4 field4;
14+
15+ public Tuple5(T0 f0, T1 f1, T2 f2, T3 f3, T4 f4) {
16+ Objects.requireNonNull(f0, "f0 must not be null");
17+ Objects.requireNonNull(f1, "f1 must not be null");
18+ Objects.requireNonNull(f2, "f2 must not be null");
19+ Objects.requireNonNull(f3, "f3 must not be null");
20+ Objects.requireNonNull(f4, "f4 must not be null");
21+ this.field0 = f0;
22+ this.field1 = f1;
23+ this.field2 = f2;
24+ this.field3 = f3;
25+ this.field4 = f4;
26+ }
27+
28+ public boolean equals(Object obj) {
29+ if (this == obj) return true;
30+ if (obj == null) return false;
31+ if (getClass() != obj.getClass()) return false;
32+ Tuple5<?,?,?,?,?> other = (Tuple5) obj;
33+ if (!Objects.equals(this.field0, other.field0)) {
34+ return false;
35+ }
36+ if (!Objects.equals(this.field1, other.field1)) {
37+ return false;
38+ }
39+ if (!Objects.equals(this.field2, other.field2)) {
40+ return false;
41+ }
42+ if (!Objects.equals(this.field3, other.field3)) {
43+ return false;
44+ }
45+ if (!Objects.equals(this.field4, other.field4)) {
46+ return false;
47+ }
48+ return true;
49+ }
50+
51+ public int hashCode() {
52+ int value = 7;
53+ value = 31 * value + (this.field0 != null ? this.field0.hashCode() : 0);
54+ value = 31 * value + (this.field1 != null ? this.field1.hashCode() : 0);
55+ value = 31 * value + (this.field2 != null ? this.field2.hashCode() : 0);
56+ value = 31 * value + (this.field3 != null ? this.field3.hashCode() : 0);
57+ value = 31 * value + (this.field4 != null ? this.field4.hashCode() : 0);
58+ return value;
59+ }
60+
61+}
generated/com/novi/serde/Tuple5.ktdeleted−12
@@ -1,12 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−data class Tuple5<T0, T1, T2, T3, T4>(
7− val field0: T0,
8− val field1: T1,
9− val field2: T2,
10− val field3: T3,
11− val field4: T4
12−)
generated/com/novi/serde/Tuple6.javanew file+67
@@ -0,0 +1,67 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.util.Objects;
7+
8+public final class Tuple6<T0, T1, T2, T3, T4, T5> {
9+ public final T0 field0;
10+ public final T1 field1;
11+ public final T2 field2;
12+ public final T3 field3;
13+ public final T4 field4;
14+ public final T5 field5;
15+
16+ public Tuple6(T0 f0, T1 f1, T2 f2, T3 f3, T4 f4, T5 f5) {
17+ Objects.requireNonNull(f0, "f0 must not be null");
18+ Objects.requireNonNull(f1, "f1 must not be null");
19+ Objects.requireNonNull(f2, "f2 must not be null");
20+ Objects.requireNonNull(f3, "f3 must not be null");
21+ Objects.requireNonNull(f4, "f4 must not be null");
22+ Objects.requireNonNull(f5, "f5 must not be null");
23+ this.field0 = f0;
24+ this.field1 = f1;
25+ this.field2 = f2;
26+ this.field3 = f3;
27+ this.field4 = f4;
28+ this.field5 = f5;
29+ }
30+
31+ public boolean equals(Object obj) {
32+ if (this == obj) return true;
33+ if (obj == null) return false;
34+ if (getClass() != obj.getClass()) return false;
35+ Tuple6<?,?,?,?,?,?> other = (Tuple6) obj;
36+ if (!Objects.equals(this.field0, other.field0)) {
37+ return false;
38+ }
39+ if (!Objects.equals(this.field1, other.field1)) {
40+ return false;
41+ }
42+ if (!Objects.equals(this.field2, other.field2)) {
43+ return false;
44+ }
45+ if (!Objects.equals(this.field3, other.field3)) {
46+ return false;
47+ }
48+ if (!Objects.equals(this.field4, other.field4)) {
49+ return false;
50+ }
51+ if (!Objects.equals(this.field5, other.field5)) {
52+ return false;
53+ }
54+ return true;
55+ }
56+
57+ public int hashCode() {
58+ int value = 7;
59+ value = 31 * value + (this.field0 != null ? this.field0.hashCode() : 0);
60+ value = 31 * value + (this.field1 != null ? this.field1.hashCode() : 0);
61+ value = 31 * value + (this.field2 != null ? this.field2.hashCode() : 0);
62+ value = 31 * value + (this.field3 != null ? this.field3.hashCode() : 0);
63+ value = 31 * value + (this.field4 != null ? this.field4.hashCode() : 0);
64+ value = 31 * value + (this.field5 != null ? this.field5.hashCode() : 0);
65+ return value;
66+ }
67+}
generated/com/novi/serde/Tuple6.ktdeleted−13
@@ -1,13 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−data class Tuple6<T0, T1, T2, T3, T4, T5>(
7− val field0: T0,
8− val field1: T1,
9− val field2: T2,
10− val field3: T3,
11− val field4: T4,
12− val field5: T5
13−)
generated/com/novi/serde/UInt128.ktdeleted−6
@@ -1,6 +0,0 @@
1−// Copyright (c) Zefchain Labs, Inc.
2−// SPDX-License-Identifier: MIT OR Apache-2.0
3−
4−package com.novi.serde
5−
6−data class UInt128(val high: ULong, val low: ULong)
generated/com/novi/serde/Unit.javanew file+20
@@ -0,0 +1,20 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+public final class Unit {
7+ public Unit() {}
8+
9+ public boolean equals(Object obj) {
10+ if (this == obj) return true;
11+ if (obj == null) return false;
12+ if (getClass() != obj.getClass()) return false;
13+ return true;
14+ }
15+
16+ public int hashCode() {
17+ return 7;
18+ }
19+
20+}
generated/com/novi/serde/Unsigned.javanew file+11
@@ -0,0 +1,11 @@
1+// Copyright (c) Facebook, Inc. and its affiliates
2+// SPDX-License-Identifier: MIT OR Apache-2.0
3+
4+package com.novi.serde;
5+
6+import java.lang.annotation.ElementType;
7+import java.lang.annotation.Target;
8+
9+@Target({ElementType.TYPE_USE})
10+public @interface Unsigned {
11+}
generated/soy/iko/opencode/core/Core.ktdeleted−1166
@@ -1,1166 +0,0 @@
1−package soy.iko.opencode.core
2−
3−import com.novi.bincode.BincodeDeserializer
4−import com.novi.bincode.BincodeSerializer
5−import com.novi.serde.Bytes
6−import com.novi.serde.DeserializationError
7−import com.novi.serde.Deserializer
8−import com.novi.serde.Serializer
9−
10−fun <T> List<T>.serialize(
11− serializer: Serializer,
12− serializeElement: Serializer.(T) -> Unit,
13−) {
14− serializer.serialize_len(size.toLong())
15− forEach { element ->
16− serializer.serializeElement(element)
17− }
18−}
19−
20−fun <T> Deserializer.deserializeListOf(deserializeElement: (Deserializer) -> T): List<T> {
21− val length = deserialize_len()
22− val list = mutableListOf<T>()
23− repeat(length.toInt()) {
24− list.add(deserializeElement(this))
25− }
26− return list
27−}
28−
29−fun <T> T?.serializeOptionOf(
30− serializer: Serializer,
31− serializeElement: Serializer.(T) -> Unit,
32−) {
33− if (this != null) {
34− serializer.serialize_option_tag(true)
35− serializer.serializeElement(this)
36− } else {
37− serializer.serialize_option_tag(false)
38− }
39−}
40−
41−fun <T> Deserializer.deserializeOptionOf(deserializeElement: (Deserializer) -> T): T? {
42− val tag = deserialize_option_tag()
43− return if (tag) {
44− deserializeElement(this)
45− } else {
46− null
47− }
48−}
49−
50−sealed interface Effect {
51− fun serialize(serializer: Serializer)
52−
53− fun bincodeSerialize(): ByteArray {
54− val serializer = BincodeSerializer()
55− serialize(serializer)
56− return serializer.get_bytes()
57− }
58−
59− data class Render(
60− val value: soy.iko.opencode.core.RenderOperation,
61− ) : Effect {
62− override fun serialize(serializer: Serializer) {
63− serializer.increase_container_depth()
64− serializer.serialize_variant_index(0)
65− value.serialize(serializer)
66− serializer.decrease_container_depth()
67− }
68−
69− companion object {
70− fun deserialize(deserializer: Deserializer): Render {
71− deserializer.increase_container_depth()
72− val value = soy.iko.opencode.core.RenderOperation.deserialize(deserializer)
73− deserializer.decrease_container_depth()
74− return Render(value)
75− }
76− }
77− }
78−
79− data class Http(
80− val value: soy.iko.opencode.core.HttpRequest,
81− ) : Effect {
82− override fun serialize(serializer: Serializer) {
83− serializer.increase_container_depth()
84− serializer.serialize_variant_index(1)
85− value.serialize(serializer)
86− serializer.decrease_container_depth()
87− }
88−
89− companion object {
90− fun deserialize(deserializer: Deserializer): Http {
91− deserializer.increase_container_depth()
92− val value = soy.iko.opencode.core.HttpRequest.deserialize(deserializer)
93− deserializer.decrease_container_depth()
94− return Http(value)
95− }
96− }
97− }
98−
99− companion object {
100− @Throws(DeserializationError::class)
101− fun deserialize(deserializer: Deserializer): Effect {
102− val index = deserializer.deserialize_variant_index()
103− return when (index) {
104− 0 -> Render.deserialize(deserializer)
105− 1 -> Http.deserialize(deserializer)
106− else -> throw DeserializationError("Unknown variant index for Effect: $index")
107− }
108− }
109−
110− @Throws(DeserializationError::class)
111− fun bincodeDeserialize(input: ByteArray?): Effect {
112− if (input == null) {
113− throw DeserializationError("Cannot deserialize null array")
114− }
115− val deserializer = BincodeDeserializer(input)
116− val value = deserialize(deserializer)
117− if (deserializer.get_buffer_offset() < input.size) {
118− throw DeserializationError("Some input bytes were not read")
119− }
120− return value
121− }
122− }
123−}
124−
125−sealed interface Event {
126− fun serialize(serializer: Serializer)
127−
128− fun bincodeSerialize(): ByteArray {
129− val serializer = BincodeSerializer()
130− serialize(serializer)
131− return serializer.get_bytes()
132− }
133−
134− data object Start: Event {
135− override fun serialize(serializer: Serializer) {
136− serializer.increase_container_depth()
137− serializer.serialize_variant_index(0)
138− serializer.decrease_container_depth()
139− }
140−
141− fun deserialize(deserializer: Deserializer): Start {
142− return Start
143− }
144− }
145−
146− data class ServerUrlChanged(
147− val value: String,
148− ) : Event {
149− override fun serialize(serializer: Serializer) {
150− serializer.increase_container_depth()
151− serializer.serialize_variant_index(1)
152− serializer.serialize_str(value)
153− serializer.decrease_container_depth()
154− }
155−
156− companion object {
157− fun deserialize(deserializer: Deserializer): ServerUrlChanged {
158− deserializer.increase_container_depth()
159− val value = deserializer.deserialize_str()
160− deserializer.decrease_container_depth()
161− return ServerUrlChanged(value)
162− }
163− }
164− }
165−
166− data class UsernameChanged(
167− val value: String,
168− ) : Event {
169− override fun serialize(serializer: Serializer) {
170− serializer.increase_container_depth()
171− serializer.serialize_variant_index(2)
172− serializer.serialize_str(value)
173− serializer.decrease_container_depth()
174− }
175−
176− companion object {
177− fun deserialize(deserializer: Deserializer): UsernameChanged {
178− deserializer.increase_container_depth()
179− val value = deserializer.deserialize_str()
180− deserializer.decrease_container_depth()
181− return UsernameChanged(value)
182− }
183− }
184− }
185−
186− data class PasswordChanged(
187− val value: String,
188− ) : Event {
189− override fun serialize(serializer: Serializer) {
190− serializer.increase_container_depth()
191− serializer.serialize_variant_index(3)
192− serializer.serialize_str(value)
193− serializer.decrease_container_depth()
194− }
195−
196− companion object {
197− fun deserialize(deserializer: Deserializer): PasswordChanged {
198− deserializer.increase_container_depth()
199− val value = deserializer.deserialize_str()
200− deserializer.decrease_container_depth()
201− return PasswordChanged(value)
202− }
203− }
204− }
205−
206− data object Connect: Event {
207− override fun serialize(serializer: Serializer) {
208− serializer.increase_container_depth()
209− serializer.serialize_variant_index(4)
210− serializer.decrease_container_depth()
211− }
212−
213− fun deserialize(deserializer: Deserializer): Connect {
214− return Connect
215− }
216− }
217−
218− data object CancelAuth: Event {
219− override fun serialize(serializer: Serializer) {
220− serializer.increase_container_depth()
221− serializer.serialize_variant_index(5)
222− serializer.decrease_container_depth()
223− }
224−
225− fun deserialize(deserializer: Deserializer): CancelAuth {
226− return CancelAuth
227− }
228− }
229−
230− data object LoadSessions: Event {
231− override fun serialize(serializer: Serializer) {
232− serializer.increase_container_depth()
233− serializer.serialize_variant_index(6)
234− serializer.decrease_container_depth()
235− }
236−
237− fun deserialize(deserializer: Deserializer): LoadSessions {
238− return LoadSessions
239− }
240− }
241−
242− data class SelectSession(
243− val value: String,
244− ) : Event {
245− override fun serialize(serializer: Serializer) {
246− serializer.increase_container_depth()
247− serializer.serialize_variant_index(7)
248− serializer.serialize_str(value)
249− serializer.decrease_container_depth()
250− }
251−
252− companion object {
253− fun deserialize(deserializer: Deserializer): SelectSession {
254− deserializer.increase_container_depth()
255− val value = deserializer.deserialize_str()
256− deserializer.decrease_container_depth()
257− return SelectSession(value)
258− }
259− }
260− }
261−
262− data object CreateSession: Event {
263− override fun serialize(serializer: Serializer) {
264− serializer.increase_container_depth()
265− serializer.serialize_variant_index(8)
266− serializer.decrease_container_depth()
267− }
268−
269− fun deserialize(deserializer: Deserializer): CreateSession {
270− return CreateSession
271− }
272− }
273−
274− data class LoadMessages(
275− val value: String,
276− ) : Event {
277− override fun serialize(serializer: Serializer) {
278− serializer.increase_container_depth()
279− serializer.serialize_variant_index(9)
280− serializer.serialize_str(value)
281− serializer.decrease_container_depth()
282− }
283−
284− companion object {
285− fun deserialize(deserializer: Deserializer): LoadMessages {
286− deserializer.increase_container_depth()
287− val value = deserializer.deserialize_str()
288− deserializer.decrease_container_depth()
289− return LoadMessages(value)
290− }
291− }
292− }
293−
294− data class SendMessage(
295− val value: String,
296− ) : Event {
297− override fun serialize(serializer: Serializer) {
298− serializer.increase_container_depth()
299− serializer.serialize_variant_index(10)
300− serializer.serialize_str(value)
301− serializer.decrease_container_depth()
302− }
303−
304− companion object {
305− fun deserialize(deserializer: Deserializer): SendMessage {
306− deserializer.increase_container_depth()
307− val value = deserializer.deserialize_str()
308− deserializer.decrease_container_depth()
309− return SendMessage(value)
310− }
311− }
312− }
313−
314− data class EventReceived(
315− val value: String,
316− ) : Event {
317− override fun serialize(serializer: Serializer) {
318− serializer.increase_container_depth()
319− serializer.serialize_variant_index(11)
320− serializer.serialize_str(value)
321− serializer.decrease_container_depth()
322− }
323−
324− companion object {
325− fun deserialize(deserializer: Deserializer): EventReceived {
326− deserializer.increase_container_depth()
327− val value = deserializer.deserialize_str()
328− deserializer.decrease_container_depth()
329− return EventReceived(value)
330− }
331− }
332− }
333−
334− data class NavigateToChat(
335− val value: String,
336− ) : Event {
337− override fun serialize(serializer: Serializer) {
338− serializer.increase_container_depth()
339− serializer.serialize_variant_index(12)
340− serializer.serialize_str(value)
341− serializer.decrease_container_depth()
342− }
343−
344− companion object {
345− fun deserialize(deserializer: Deserializer): NavigateToChat {
346− deserializer.increase_container_depth()
347− val value = deserializer.deserialize_str()
348− deserializer.decrease_container_depth()
349− return NavigateToChat(value)
350− }
351− }
352− }
353−
354− data object NavigateToSessions: Event {
355− override fun serialize(serializer: Serializer) {
356− serializer.increase_container_depth()
357− serializer.serialize_variant_index(13)
358− serializer.decrease_container_depth()
359− }
360−
361− fun deserialize(deserializer: Deserializer): NavigateToSessions {
362− return NavigateToSessions
363− }
364− }
365−
366− data object NavigateToConnect: Event {
367− override fun serialize(serializer: Serializer) {
368− serializer.increase_container_depth()
369− serializer.serialize_variant_index(14)
370− serializer.decrease_container_depth()
371− }
372−
373− fun deserialize(deserializer: Deserializer): NavigateToConnect {
374− return NavigateToConnect
375− }
376− }
377−
378− data object DismissError: Event {
379− override fun serialize(serializer: Serializer) {
380− serializer.increase_container_depth()
381− serializer.serialize_variant_index(15)
382− serializer.decrease_container_depth()
383− }
384−
385− fun deserialize(deserializer: Deserializer): DismissError {
386− return DismissError
387− }
388− }
389−
390− companion object {
391− @Throws(DeserializationError::class)
392− fun deserialize(deserializer: Deserializer): Event {
393− val index = deserializer.deserialize_variant_index()
394− return when (index) {
395− 0 -> Start.deserialize(deserializer)
396− 1 -> ServerUrlChanged.deserialize(deserializer)
397− 2 -> UsernameChanged.deserialize(deserializer)
398− 3 -> PasswordChanged.deserialize(deserializer)
399− 4 -> Connect.deserialize(deserializer)
400− 5 -> CancelAuth.deserialize(deserializer)
401− 6 -> LoadSessions.deserialize(deserializer)
402− 7 -> SelectSession.deserialize(deserializer)
403− 8 -> CreateSession.deserialize(deserializer)
404− 9 -> LoadMessages.deserialize(deserializer)
405− 10 -> SendMessage.deserialize(deserializer)
406− 11 -> EventReceived.deserialize(deserializer)
407− 12 -> NavigateToChat.deserialize(deserializer)
408− 13 -> NavigateToSessions.deserialize(deserializer)
409− 14 -> NavigateToConnect.deserialize(deserializer)
410− 15 -> DismissError.deserialize(deserializer)
411− else -> throw DeserializationError("Unknown variant index for Event: $index")
412− }
413− }
414−
415− @Throws(DeserializationError::class)
416− fun bincodeDeserialize(input: ByteArray?): Event {
417− if (input == null) {
418− throw DeserializationError("Cannot deserialize null array")
419− }
420− val deserializer = BincodeDeserializer(input)
421− val value = deserialize(deserializer)
422− if (deserializer.get_buffer_offset() < input.size) {
423− throw DeserializationError("Some input bytes were not read")
424− }
425− return value
426− }
427− }
428−}
429−
430−/// An error produced when an HTTP request fails.
431−///
432−/// Variants fall into two groups:
433−///
434−/// **Transport errors** — generated by the shell when it cannot complete the HTTP
435−/// exchange. These cross the FFI boundary and are serialized in the protocol:
436−/// [`Url`](HttpError::Url), [`Io`](HttpError::Io), [`Timeout`](HttpError::Timeout).
437−///
438−/// **Processing errors** — generated on the Rust side after a response arrives.
439−/// These are never serialized or visible to shells:
440−///
441−/// - [`Http`](HttpError::Http) — produced by `Response::new()` when the server returns
442−/// a 4xx or 5xx status. At the *protocol* level these arrive as
443−/// [`HttpResult::Ok`](crate::protocol::HttpResult::Ok); `Response::new()` converts
444−/// them here, so app code using `crux_http::Result<Response<T>>` will see them as
445−/// `Err(HttpError::Http { code, .. })`.
446−/// - [`Json`](HttpError::Json) — produced when response body deserialisation fails.
447−sealed interface HttpError {
448− fun serialize(serializer: Serializer)
449−
450− fun bincodeSerialize(): ByteArray {
451− val serializer = BincodeSerializer()
452− serialize(serializer)
453− return serializer.get_bytes()
454− }
455−
456− /// The request URL could not be parsed.
457− data class Url(
458− val value: String,
459− ) : HttpError {
460− override fun serialize(serializer: Serializer) {
461− serializer.increase_container_depth()
462− serializer.serialize_variant_index(0)
463− serializer.serialize_str(value)
464− serializer.decrease_container_depth()
465− }
466−
467− companion object {
468− fun deserialize(deserializer: Deserializer): Url {
469− deserializer.increase_container_depth()
470− val value = deserializer.deserialize_str()
471− deserializer.decrease_container_depth()
472− return Url(value)
473− }
474− }
475− }
476−
477− /// An IO error prevented the request from completing.
478− data class Io(
479− val value: String,
480− ) : HttpError {
481− override fun serialize(serializer: Serializer) {
482− serializer.increase_container_depth()
483− serializer.serialize_variant_index(1)
484− serializer.serialize_str(value)
485− serializer.decrease_container_depth()
486− }
487−
488− companion object {
489− fun deserialize(deserializer: Deserializer): Io {
490− deserializer.increase_container_depth()
491− val value = deserializer.deserialize_str()
492− deserializer.decrease_container_depth()
493− return Io(value)
494− }
495− }
496− }
497−
498− /// The request timed out before a response was received.
499− data object Timeout: HttpError {
500− override fun serialize(serializer: Serializer) {
501− serializer.increase_container_depth()
502− serializer.serialize_variant_index(2)
503− serializer.decrease_container_depth()
504− }
505−
506− fun deserialize(deserializer: Deserializer): Timeout {
507− return Timeout
508− }
509− }
510−
511− companion object {
512− @Throws(DeserializationError::class)
513− fun deserialize(deserializer: Deserializer): HttpError {
514− val index = deserializer.deserialize_variant_index()
515− return when (index) {
516− 0 -> Url.deserialize(deserializer)
517− 1 -> Io.deserialize(deserializer)
518− 2 -> Timeout.deserialize(deserializer)
519− else -> throw DeserializationError("Unknown variant index for HttpError: $index")
520− }
521− }
522−
523− @Throws(DeserializationError::class)
524− fun bincodeDeserialize(input: ByteArray?): HttpError {
525− if (input == null) {
526− throw DeserializationError("Cannot deserialize null array")
527− }
528− val deserializer = BincodeDeserializer(input)
529− val value = deserialize(deserializer)
530− if (deserializer.get_buffer_offset() < input.size) {
531− throw DeserializationError("Some input bytes were not read")
532− }
533− return value
534− }
535− }
536−}
537−
538−data class HttpHeader(
539− val name: String,
540− val value: String,
541−) {
542− fun serialize(serializer: Serializer) {
543− serializer.increase_container_depth()
544− serializer.serialize_str(name)
545− serializer.serialize_str(value)
546− serializer.decrease_container_depth()
547− }
548−
549− fun bincodeSerialize(): ByteArray {
550− val serializer = BincodeSerializer()
551− serialize(serializer)
552− return serializer.get_bytes()
553− }
554−
555− companion object {
556− fun deserialize(deserializer: Deserializer): HttpHeader {
557− deserializer.increase_container_depth()
558− val name = deserializer.deserialize_str()
559− val value = deserializer.deserialize_str()
560− deserializer.decrease_container_depth()
561− return HttpHeader(name, value)
562− }
563−
564− @Throws(DeserializationError::class)
565− fun bincodeDeserialize(input: ByteArray?): HttpHeader {
566− if (input == null) {
567− throw DeserializationError("Cannot deserialize null array")
568− }
569− val deserializer = BincodeDeserializer(input)
570− val value = deserialize(deserializer)
571− if (deserializer.get_buffer_offset() < input.size) {
572− throw DeserializationError("Some input bytes were not read")
573− }
574− return value
575− }
576− }
577−}
578−
579−/// A raw HTTP request, as sent to the shell over the protocol boundary.
580−///
581−/// # No header validation
582−///
583−/// All fields are plain strings. Header names and values are carried as-is with no
584−/// validation against the HTTP specification. This is intentional: `HttpRequest` is a
585−/// cross-language data carrier deserialised by Swift, Kotlin, and TypeScript shells;
586−/// Rust's `http`-crate validation rules cannot be enforced on the other side of that
587−/// boundary.
588−///
589−/// **Shell authors must not assume that header names or values are well-formed.**
590−/// Pass them to your underlying HTTP client as-is — it will apply its own rules.
591−///
592−/// For the ergonomic Rust-side builder that *does* validate header values (and panics
593−/// on invalid input), see [`crate::command::RequestBuilder`].
594−data class HttpRequest(
595− val method: String,
596− val url: String,
597− val headers: List<soy.iko.opencode.core.HttpHeader>,
598− val body: Bytes,
599−) {
600− fun serialize(serializer: Serializer) {
601− serializer.increase_container_depth()
602− serializer.serialize_str(method)
603− serializer.serialize_str(url)
604− headers.serialize(serializer) {
605− it.serialize(serializer)
606− }
607− serializer.serialize_bytes(body)
608− serializer.decrease_container_depth()
609− }
610−
611− fun bincodeSerialize(): ByteArray {
612− val serializer = BincodeSerializer()
613− serialize(serializer)
614− return serializer.get_bytes()
615− }
616−
617− companion object {
618− fun deserialize(deserializer: Deserializer): HttpRequest {
619− deserializer.increase_container_depth()
620− val method = deserializer.deserialize_str()
621− val url = deserializer.deserialize_str()
622− val headers =
623− deserializer.deserializeListOf {
624− soy.iko.opencode.core.HttpHeader.deserialize(deserializer)
625− }
626− val body = deserializer.deserialize_bytes()
627− deserializer.decrease_container_depth()
628− return HttpRequest(method, url, headers, body)
629− }
630−
631− @Throws(DeserializationError::class)
632− fun bincodeDeserialize(input: ByteArray?): HttpRequest {
633− if (input == null) {
634− throw DeserializationError("Cannot deserialize null array")
635− }
636− val deserializer = BincodeDeserializer(input)
637− val value = deserialize(deserializer)
638− if (deserializer.get_buffer_offset() < input.size) {
639− throw DeserializationError("Some input bytes were not read")
640− }
641− return value
642− }
643− }
644−}
645−
646−data class HttpResponse(
647− val status: UShort,
648− val headers: List<soy.iko.opencode.core.HttpHeader>,
649− val body: Bytes,
650−) {
651− fun serialize(serializer: Serializer) {
652− serializer.increase_container_depth()
653− serializer.serialize_u16(status)
654− headers.serialize(serializer) {
655− it.serialize(serializer)
656− }
657− serializer.serialize_bytes(body)
658− serializer.decrease_container_depth()
659− }
660−
661− fun bincodeSerialize(): ByteArray {
662− val serializer = BincodeSerializer()
663− serialize(serializer)
664− return serializer.get_bytes()
665− }
666−
667− companion object {
668− fun deserialize(deserializer: Deserializer): HttpResponse {
669− deserializer.increase_container_depth()
670− val status = deserializer.deserialize_u16()
671− val headers =
672− deserializer.deserializeListOf {
673− soy.iko.opencode.core.HttpHeader.deserialize(deserializer)
674− }
675− val body = deserializer.deserialize_bytes()
676− deserializer.decrease_container_depth()
677− return HttpResponse(status, headers, body)
678− }
679−
680− @Throws(DeserializationError::class)
681− fun bincodeDeserialize(input: ByteArray?): HttpResponse {
682− if (input == null) {
683− throw DeserializationError("Cannot deserialize null array")
684− }
685− val deserializer = BincodeDeserializer(input)
686− val value = deserialize(deserializer)
687− if (deserializer.get_buffer_offset() < input.size) {
688− throw DeserializationError("Some input bytes were not read")
689− }
690− return value
691− }
692− }
693−}
694−
695−/// The result of an HTTP request, as returned by the shell over the protocol boundary.
696−///
697−/// # Status codes are not errors
698−///
699−/// Any completed HTTP exchange — including responses with 4xx or 5xx status codes — is
700−/// returned as [`HttpResult::Ok`]. Only *transport-level* failures (the shell could not
701−/// reach the server at all) produce [`HttpResult::Err`].
702−///
703−/// To act on an error status, inspect [`HttpResponse::status`]:
704−///
705−/// ```
706−/// # use crux_http::protocol::{HttpResult, HttpResponse};
707−/// # use crux_http::HttpError;
708−/// # fn handle(result: HttpResult) {
709−/// match result {
710−/// HttpResult::Ok(response) if response.status == 200 => { /* success */ }
711−/// HttpResult::Ok(response) if response.status == 404 => { /* not found */ }
712−/// HttpResult::Ok(response) if response.status >= 500 => { /* server error */ }
713−/// HttpResult::Ok(_) => { /* other status */ }
714−/// HttpResult::Err(e) => { /* transport failure: bad URL, IO error, or timeout */ }
715−/// }
716−/// # }
717−/// ```
718−sealed interface HttpResult {
719− fun serialize(serializer: Serializer)
720−
721− fun bincodeSerialize(): ByteArray {
722− val serializer = BincodeSerializer()
723− serialize(serializer)
724− return serializer.get_bytes()
725− }
726−
727− /// The shell completed the HTTP exchange. The response may carry any status code,
728− /// including 4xx and 5xx — inspect [`HttpResponse::status`] to distinguish them.
729− data class Ok(
730− val value: soy.iko.opencode.core.HttpResponse,
731− ) : HttpResult {
732− override fun serialize(serializer: Serializer) {
733− serializer.increase_container_depth()
734− serializer.serialize_variant_index(0)
735− value.serialize(serializer)
736− serializer.decrease_container_depth()
737− }
738−
739− companion object {
740− fun deserialize(deserializer: Deserializer): Ok {
741− deserializer.increase_container_depth()
742− val value = soy.iko.opencode.core.HttpResponse.deserialize(deserializer)
743− deserializer.decrease_container_depth()
744− return Ok(value)
745− }
746− }
747− }
748−
749− /// The shell could not complete the HTTP exchange due to a transport-level failure.
750− /// See [`HttpError`] for the possible causes.
751− data class Err(
752− val value: soy.iko.opencode.core.HttpError,
753− ) : HttpResult {
754− override fun serialize(serializer: Serializer) {
755− serializer.increase_container_depth()
756− serializer.serialize_variant_index(1)
757− value.serialize(serializer)
758− serializer.decrease_container_depth()
759− }
760−
761− companion object {
762− fun deserialize(deserializer: Deserializer): Err {
763− deserializer.increase_container_depth()
764− val value = soy.iko.opencode.core.HttpError.deserialize(deserializer)
765− deserializer.decrease_container_depth()
766− return Err(value)
767− }
768− }
769− }
770−
771− companion object {
772− @Throws(DeserializationError::class)
773− fun deserialize(deserializer: Deserializer): HttpResult {
774− val index = deserializer.deserialize_variant_index()
775− return when (index) {
776− 0 -> Ok.deserialize(deserializer)
777− 1 -> Err.deserialize(deserializer)
778− else -> throw DeserializationError("Unknown variant index for HttpResult: $index")
779− }
780− }
781−
782− @Throws(DeserializationError::class)
783− fun bincodeDeserialize(input: ByteArray?): HttpResult {
784− if (input == null) {
785− throw DeserializationError("Cannot deserialize null array")
786− }
787− val deserializer = BincodeDeserializer(input)
788− val value = deserialize(deserializer)
789− if (deserializer.get_buffer_offset() < input.size) {
790− throw DeserializationError("Some input bytes were not read")
791− }
792− return value
793− }
794− }
795−}
796−
797−data class MessageView(
798− val id: String,
799− val role: String,
800− val text: String,
801− val time: ULong,
802−) {
803− fun serialize(serializer: Serializer) {
804− serializer.increase_container_depth()
805− serializer.serialize_str(id)
806− serializer.serialize_str(role)
807− serializer.serialize_str(text)
808− serializer.serialize_u64(time)
809− serializer.decrease_container_depth()
810− }
811−
812− fun bincodeSerialize(): ByteArray {
813− val serializer = BincodeSerializer()
814− serialize(serializer)
815− return serializer.get_bytes()
816− }
817−
818− companion object {
819− fun deserialize(deserializer: Deserializer): MessageView {
820− deserializer.increase_container_depth()
821− val id = deserializer.deserialize_str()
822− val role = deserializer.deserialize_str()
823− val text = deserializer.deserialize_str()
824− val time = deserializer.deserialize_u64()
825− deserializer.decrease_container_depth()
826− return MessageView(id, role, text, time)
827− }
828−
829− @Throws(DeserializationError::class)
830− fun bincodeDeserialize(input: ByteArray?): MessageView {
831− if (input == null) {
832− throw DeserializationError("Cannot deserialize null array")
833− }
834− val deserializer = BincodeDeserializer(input)
835− val value = deserialize(deserializer)
836− if (deserializer.get_buffer_offset() < input.size) {
837− throw DeserializationError("Some input bytes were not read")
838− }
839− return value
840− }
841− }
842−}
843−
844−/// The single operation `Render` implements.
845−data object RenderOperation {
846− fun serialize(serializer: Serializer) {}
847−
848− fun bincodeSerialize(): ByteArray {
849− val serializer = BincodeSerializer()
850− serialize(serializer)
851− return serializer.get_bytes()
852− }
853−
854− fun deserialize(deserializer: Deserializer): RenderOperation {
855− return RenderOperation
856− }
857−
858− @Throws(DeserializationError::class)
859− fun bincodeDeserialize(input: ByteArray?): RenderOperation {
860− if (input == null) {
861− throw DeserializationError("Cannot deserialize null array")
862− }
863− val deserializer = BincodeDeserializer(input)
864− val value = deserialize(deserializer)
865− if (deserializer.get_buffer_offset() < input.size) {
866− throw DeserializationError("Some input bytes were not read")
867− }
868− return value
869− }
870−}
871−
872−/// Request for a side-effect passed from the Core to the Shell.
873−///
874−/// The `EffectId` links the `Request` with the corresponding call to [`Core::resolve`] to pass the data back
875−/// to the [`App::update`] function (wrapped in the event provided to the capability originating the effect).
876−data class Request(
877− val id: UInt,
878− val effect: soy.iko.opencode.core.Effect,
879−) {
880− fun serialize(serializer: Serializer) {
881− serializer.increase_container_depth()
882− serializer.serialize_u32(id)
883− effect.serialize(serializer)
884− serializer.decrease_container_depth()
885− }
886−
887− fun bincodeSerialize(): ByteArray {
888− val serializer = BincodeSerializer()
889− serialize(serializer)
890− return serializer.get_bytes()
891− }
892−
893− companion object {
894− fun deserialize(deserializer: Deserializer): Request {
895− deserializer.increase_container_depth()
896− val id = deserializer.deserialize_u32()
897− val effect = soy.iko.opencode.core.Effect.deserialize(deserializer)
898− deserializer.decrease_container_depth()
899− return Request(id, effect)
900− }
901−
902− @Throws(DeserializationError::class)
903− fun bincodeDeserialize(input: ByteArray?): Request {
904− if (input == null) {
905− throw DeserializationError("Cannot deserialize null array")
906− }
907− val deserializer = BincodeDeserializer(input)
908− val value = deserialize(deserializer)
909− if (deserializer.get_buffer_offset() < input.size) {
910− throw DeserializationError("Some input bytes were not read")
911− }
912− return value
913− }
914− }
915−}
916−
917−/// A batch of effect requests from the Core to the Shell, as serialised by
918−/// [`Bridge::update`] and [`Bridge::resolve`].
919−///
920−/// The wire format is identical to `Vec<Request<Eff>>` (the newtype is
921−/// `serde(transparent)`), so existing shell code that already deserialises
922−/// a `Vec<Request>` remains binary-compatible.
923−///
924−/// Registering this type with the type-generation system causes the code
925−/// generators to emit a `Requests` type (with a `value` field containing the
926−/// list) together with a top-level `bincodeDeserialize` / `BincodeDeserialize`
927−/// helper, replacing the hand-written extension files that were previously
928−/// appended by `add_extensions()`.
929−data class Requests(
930− val value: List<soy.iko.opencode.core.Request>,
931−) {
932− fun serialize(serializer: Serializer) {
933− serializer.increase_container_depth()
934− value.serialize(serializer) {
935− it.serialize(serializer)
936− }
937− serializer.decrease_container_depth()
938− }
939−
940− fun bincodeSerialize(): ByteArray {
941− val serializer = BincodeSerializer()
942− serialize(serializer)
943− return serializer.get_bytes()
944− }
945−
946− companion object {
947− fun deserialize(deserializer: Deserializer): Requests {
948− deserializer.increase_container_depth()
949− val value =
950− deserializer.deserializeListOf {
951− soy.iko.opencode.core.Request.deserialize(deserializer)
952− }
953− deserializer.decrease_container_depth()
954− return Requests(value)
955− }
956−
957− @Throws(DeserializationError::class)
958− fun bincodeDeserialize(input: ByteArray?): Requests {
959− if (input == null) {
960− throw DeserializationError("Cannot deserialize null array")
961− }
962− val deserializer = BincodeDeserializer(input)
963− val value = deserialize(deserializer)
964− if (deserializer.get_buffer_offset() < input.size) {
965− throw DeserializationError("Some input bytes were not read")
966− }
967− return value
968− }
969− }
970−}
971−
972−enum class Screen {
973− CONNECT,
974− SESSIONS,
975− CHAT;
976−
977− fun serialize(serializer: Serializer) {
978− serializer.increase_container_depth()
979− serializer.serialize_variant_index(ordinal)
980− serializer.decrease_container_depth()
981− }
982−
983− fun bincodeSerialize(): ByteArray {
984− val serializer = BincodeSerializer()
985− serialize(serializer)
986− return serializer.get_bytes()
987− }
988−
989− companion object {
990− @Throws(DeserializationError::class)
991− fun deserialize(deserializer: Deserializer): Screen {
992− deserializer.increase_container_depth()
993− val index = deserializer.deserialize_variant_index()
994− deserializer.decrease_container_depth()
995− return when (index) {
996− 0 -> CONNECT
997− 1 -> SESSIONS
998− 2 -> CHAT
999− else -> throw DeserializationError("Unknown variant index for Screen: $index")
1000− }
1001− }
1002−
1003− @Throws(DeserializationError::class)
1004− fun bincodeDeserialize(input: ByteArray?): Screen {
1005− if (input == null) {
1006− throw DeserializationError("Cannot deserialize null array")
1007− }
1008− val deserializer = BincodeDeserializer(input)
1009− val value = deserialize(deserializer)
1010− if (deserializer.get_buffer_offset() < input.size) {
1011− throw DeserializationError("Some input bytes were not read")
1012− }
1013− return value
1014− }
1015− }
1016−}
1017−
1018−data class SessionView(
1019− val id: String,
1020− val title: String,
1021−) {
1022− fun serialize(serializer: Serializer) {
1023− serializer.increase_container_depth()
1024− serializer.serialize_str(id)
1025− serializer.serialize_str(title)
1026− serializer.decrease_container_depth()
1027− }
1028−
1029− fun bincodeSerialize(): ByteArray {
1030− val serializer = BincodeSerializer()
1031− serialize(serializer)
1032− return serializer.get_bytes()
1033− }
1034−
1035− companion object {
1036− fun deserialize(deserializer: Deserializer): SessionView {
1037− deserializer.increase_container_depth()
1038− val id = deserializer.deserialize_str()
1039− val title = deserializer.deserialize_str()
1040− deserializer.decrease_container_depth()
1041− return SessionView(id, title)
1042− }
1043−
1044− @Throws(DeserializationError::class)
1045− fun bincodeDeserialize(input: ByteArray?): SessionView {
1046− if (input == null) {
1047− throw DeserializationError("Cannot deserialize null array")
1048− }
1049− val deserializer = BincodeDeserializer(input)
1050− val value = deserialize(deserializer)
1051− if (deserializer.get_buffer_offset() < input.size) {
1052− throw DeserializationError("Some input bytes were not read")
1053− }
1054− return value
1055− }
1056− }
1057−}
1058−
1059−data class ViewModel(
1060− val screen: soy.iko.opencode.core.Screen,
1061− val serverUrl: String,
1062− val username: String,
1063− val password: String,
1064− val authRequired: Boolean,
1065− val connected: Boolean,
1066− val loading: Boolean,
1067− val error: String? = null,
1068− val sessions: List<soy.iko.opencode.core.SessionView>,
1069− val currentSessionId: String? = null,
1070− val currentSessionTitle: String,
1071− val messages: List<soy.iko.opencode.core.MessageView>,
1072− val draftMessage: String,
1073− /// True while waiting for the assistant to reply after the user sends.
1074− val generating: Boolean,
1075− val crashLogCount: UInt,
1076− val latestCrashLog: String? = null,
1077−) {
1078− fun serialize(serializer: Serializer) {
1079− serializer.increase_container_depth()
1080− screen.serialize(serializer)
1081− serializer.serialize_str(serverUrl)
1082− serializer.serialize_str(username)
1083− serializer.serialize_str(password)
1084− serializer.serialize_bool(authRequired)
1085− serializer.serialize_bool(connected)
1086− serializer.serialize_bool(loading)
1087− error.serializeOptionOf(serializer) {
1088− serializer.serialize_str(it)
1089− }
1090− sessions.serialize(serializer) {
1091− it.serialize(serializer)
1092− }
1093− currentSessionId.serializeOptionOf(serializer) {
1094− serializer.serialize_str(it)
1095− }
1096− serializer.serialize_str(currentSessionTitle)
1097− messages.serialize(serializer) {
1098− it.serialize(serializer)
1099− }
1100− serializer.serialize_str(draftMessage)
1101− serializer.serialize_bool(generating)
1102− serializer.serialize_u32(crashLogCount)
1103− latestCrashLog.serializeOptionOf(serializer) {
1104− serializer.serialize_str(it)
1105− }
1106− serializer.decrease_container_depth()
1107− }
1108−
1109− fun bincodeSerialize(): ByteArray {
1110− val serializer = BincodeSerializer()
1111− serialize(serializer)
1112− return serializer.get_bytes()
1113− }
1114−
1115− companion object {
1116− fun deserialize(deserializer: Deserializer): ViewModel {
1117− deserializer.increase_container_depth()
1118− val screen = soy.iko.opencode.core.Screen.deserialize(deserializer)
1119− val serverUrl = deserializer.deserialize_str()
1120− val username = deserializer.deserialize_str()
1121− val password = deserializer.deserialize_str()
1122− val authRequired = deserializer.deserialize_bool()
1123− val connected = deserializer.deserialize_bool()
1124− val loading = deserializer.deserialize_bool()
1125− val error =
1126− deserializer.deserializeOptionOf {
1127− deserializer.deserialize_str()
1128− }
1129− val sessions =
1130− deserializer.deserializeListOf {
1131− soy.iko.opencode.core.SessionView.deserialize(deserializer)
1132− }
1133− val currentSessionId =
1134− deserializer.deserializeOptionOf {
1135− deserializer.deserialize_str()
1136− }
1137− val currentSessionTitle = deserializer.deserialize_str()
1138− val messages =
1139− deserializer.deserializeListOf {
1140− soy.iko.opencode.core.MessageView.deserialize(deserializer)
1141− }
1142− val draftMessage = deserializer.deserialize_str()
1143− val generating = deserializer.deserialize_bool()
1144− val crashLogCount = deserializer.deserialize_u32()
1145− val latestCrashLog =
1146− deserializer.deserializeOptionOf {
1147− deserializer.deserialize_str()
1148− }
1149− deserializer.decrease_container_depth()
1150− return ViewModel(screen, serverUrl, username, password, authRequired, connected, loading, error, sessions, currentSessionId, currentSessionTitle, messages, draftMessage, generating, crashLogCount, latestCrashLog)
1151− }
1152−
1153− @Throws(DeserializationError::class)
1154− fun bincodeDeserialize(input: ByteArray?): ViewModel {
1155− if (input == null) {
1156− throw DeserializationError("Cannot deserialize null array")
1157− }
1158− val deserializer = BincodeDeserializer(input)
1159− val value = deserialize(deserializer)
1160− if (deserializer.get_buffer_offset() < input.size) {
1161− throw DeserializationError("Some input bytes were not read")
1162− }
1163− return value
1164− }
1165− }
1166−}
generated/soy/iko/opencode/shared/MessageStatus.javanew file+150
@@ -0,0 +1,150 @@
1+package soy.iko.opencode.shared;
2+
3+
4+public abstract class MessageStatus {
5+
6+ abstract public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError;
7+
8+ public static MessageStatus deserialize(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
9+ int index = deserializer.deserialize_variant_index();
10+ switch (index) {
11+ case 0: return Sent.load(deserializer);
12+ case 1: return Pending.load(deserializer);
13+ case 2: return Failed.load(deserializer);
14+ default: throw new com.novi.serde.DeserializationError("Unknown variant index for MessageStatus: " + index);
15+ }
16+ }
17+
18+ public byte[] bincodeSerialize() throws com.novi.serde.SerializationError {
19+ com.novi.serde.Serializer serializer = new com.novi.bincode.BincodeSerializer();
20+ serialize(serializer);
21+ return serializer.get_bytes();
22+ }
23+
24+ public static MessageStatus bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
25+ if (input == null) {
26+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
27+ }
28+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
29+ MessageStatus value = deserialize(deserializer);
30+ if (deserializer.get_buffer_offset() < input.length) {
31+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
32+ }
33+ return value;
34+ }
35+
36+ public static final class Sent extends MessageStatus {
37+ public Sent() {
38+ }
39+
40+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
41+ serializer.increase_container_depth();
42+ serializer.serialize_variant_index(0);
43+ serializer.decrease_container_depth();
44+ }
45+
46+ static Sent load(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
47+ deserializer.increase_container_depth();
48+ Builder builder = new Builder();
49+ deserializer.decrease_container_depth();
50+ return builder.build();
51+ }
52+
53+ public boolean equals(Object obj) {
54+ if (this == obj) return true;
55+ if (obj == null) return false;
56+ if (getClass() != obj.getClass()) return false;
57+ Sent other = (Sent) obj;
58+ return true;
59+ }
60+
61+ public int hashCode() {
62+ int value = 7;
63+ return value;
64+ }
65+
66+ public static final class Builder {
67+ public Sent build() {
68+ return new Sent(
69+ );
70+ }
71+ }
72+ }
73+
74+ public static final class Pending extends MessageStatus {
75+ public Pending() {
76+ }
77+
78+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
79+ serializer.increase_container_depth();
80+ serializer.serialize_variant_index(1);
81+ serializer.decrease_container_depth();
82+ }
83+
84+ static Pending load(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
85+ deserializer.increase_container_depth();
86+ Builder builder = new Builder();
87+ deserializer.decrease_container_depth();
88+ return builder.build();
89+ }
90+
91+ public boolean equals(Object obj) {
92+ if (this == obj) return true;
93+ if (obj == null) return false;
94+ if (getClass() != obj.getClass()) return false;
95+ Pending other = (Pending) obj;
96+ return true;
97+ }
98+
99+ public int hashCode() {
100+ int value = 7;
101+ return value;
102+ }
103+
104+ public static final class Builder {
105+ public Pending build() {
106+ return new Pending(
107+ );
108+ }
109+ }
110+ }
111+
112+ public static final class Failed extends MessageStatus {
113+ public Failed() {
114+ }
115+
116+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
117+ serializer.increase_container_depth();
118+ serializer.serialize_variant_index(2);
119+ serializer.decrease_container_depth();
120+ }
121+
122+ static Failed load(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
123+ deserializer.increase_container_depth();
124+ Builder builder = new Builder();
125+ deserializer.decrease_container_depth();
126+ return builder.build();
127+ }
128+
129+ public boolean equals(Object obj) {
130+ if (this == obj) return true;
131+ if (obj == null) return false;
132+ if (getClass() != obj.getClass()) return false;
133+ Failed other = (Failed) obj;
134+ return true;
135+ }
136+
137+ public int hashCode() {
138+ int value = 7;
139+ return value;
140+ }
141+
142+ public static final class Builder {
143+ public Failed build() {
144+ return new Failed(
145+ );
146+ }
147+ }
148+ }
149+}
150+
generated/soy/iko/opencode/shared/MessageView.javanew file+131
@@ -0,0 +1,131 @@
1+package soy.iko.opencode.shared;
2+
3+
4+public final class MessageView {
5+ public final String id;
6+ public final String role;
7+ public final String text;
8+ public final java.util.Optional<String> reasoning;
9+ public final java.util.List<ToolView> tools;
10+ public final @com.novi.serde.Unsigned Long time;
11+ public final MessageStatus status;
12+ public final Boolean streaming;
13+
14+ public MessageView(String id, String role, String text, java.util.Optional<String> reasoning, java.util.List<ToolView> tools, @com.novi.serde.Unsigned Long time, MessageStatus status, Boolean streaming) {
15+ java.util.Objects.requireNonNull(id, "id must not be null");
16+ java.util.Objects.requireNonNull(role, "role must not be null");
17+ java.util.Objects.requireNonNull(text, "text must not be null");
18+ java.util.Objects.requireNonNull(reasoning, "reasoning must not be null");
19+ java.util.Objects.requireNonNull(tools, "tools must not be null");
20+ java.util.Objects.requireNonNull(time, "time must not be null");
21+ java.util.Objects.requireNonNull(status, "status must not be null");
22+ java.util.Objects.requireNonNull(streaming, "streaming must not be null");
23+ this.id = id;
24+ this.role = role;
25+ this.text = text;
26+ this.reasoning = reasoning;
27+ this.tools = tools;
28+ this.time = time;
29+ this.status = status;
30+ this.streaming = streaming;
31+ }
32+
33+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
34+ serializer.increase_container_depth();
35+ serializer.serialize_str(id);
36+ serializer.serialize_str(role);
37+ serializer.serialize_str(text);
38+ TraitHelpers.serialize_option_str(reasoning, serializer);
39+ TraitHelpers.serialize_vector_ToolView(tools, serializer);
40+ serializer.serialize_u64(time);
41+ status.serialize(serializer);
42+ serializer.serialize_bool(streaming);
43+ serializer.decrease_container_depth();
44+ }
45+
46+ public byte[] bincodeSerialize() throws com.novi.serde.SerializationError {
47+ com.novi.serde.Serializer serializer = new com.novi.bincode.BincodeSerializer();
48+ serialize(serializer);
49+ return serializer.get_bytes();
50+ }
51+
52+ public static MessageView deserialize(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
53+ deserializer.increase_container_depth();
54+ Builder builder = new Builder();
55+ builder.id = deserializer.deserialize_str();
56+ builder.role = deserializer.deserialize_str();
57+ builder.text = deserializer.deserialize_str();
58+ builder.reasoning = TraitHelpers.deserialize_option_str(deserializer);
59+ builder.tools = TraitHelpers.deserialize_vector_ToolView(deserializer);
60+ builder.time = deserializer.deserialize_u64();
61+ builder.status = MessageStatus.deserialize(deserializer);
62+ builder.streaming = deserializer.deserialize_bool();
63+ deserializer.decrease_container_depth();
64+ return builder.build();
65+ }
66+
67+ public static MessageView bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
68+ if (input == null) {
69+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
70+ }
71+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
72+ MessageView value = deserialize(deserializer);
73+ if (deserializer.get_buffer_offset() < input.length) {
74+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
75+ }
76+ return value;
77+ }
78+
79+ public boolean equals(Object obj) {
80+ if (this == obj) return true;
81+ if (obj == null) return false;
82+ if (getClass() != obj.getClass()) return false;
83+ MessageView other = (MessageView) obj;
84+ if (!java.util.Objects.equals(this.id, other.id)) { return false; }
85+ if (!java.util.Objects.equals(this.role, other.role)) { return false; }
86+ if (!java.util.Objects.equals(this.text, other.text)) { return false; }
87+ if (!java.util.Objects.equals(this.reasoning, other.reasoning)) { return false; }
88+ if (!java.util.Objects.equals(this.tools, other.tools)) { return false; }
89+ if (!java.util.Objects.equals(this.time, other.time)) { return false; }
90+ if (!java.util.Objects.equals(this.status, other.status)) { return false; }
91+ if (!java.util.Objects.equals(this.streaming, other.streaming)) { return false; }
92+ return true;
93+ }
94+
95+ public int hashCode() {
96+ int value = 7;
97+ value = 31 * value + (this.id != null ? this.id.hashCode() : 0);
98+ value = 31 * value + (this.role != null ? this.role.hashCode() : 0);
99+ value = 31 * value + (this.text != null ? this.text.hashCode() : 0);
100+ value = 31 * value + (this.reasoning != null ? this.reasoning.hashCode() : 0);
101+ value = 31 * value + (this.tools != null ? this.tools.hashCode() : 0);
102+ value = 31 * value + (this.time != null ? this.time.hashCode() : 0);
103+ value = 31 * value + (this.status != null ? this.status.hashCode() : 0);
104+ value = 31 * value + (this.streaming != null ? this.streaming.hashCode() : 0);
105+ return value;
106+ }
107+
108+ public static final class Builder {
109+ public String id;
110+ public String role;
111+ public String text;
112+ public java.util.Optional<String> reasoning;
113+ public java.util.List<ToolView> tools;
114+ public @com.novi.serde.Unsigned Long time;
115+ public MessageStatus status;
116+ public Boolean streaming;
117+
118+ public MessageView build() {
119+ return new MessageView(
120+ id,
121+ role,
122+ text,
123+ reasoning,
124+ tools,
125+ time,
126+ status,
127+ streaming
128+ );
129+ }
130+ }
131+}
generated/soy/iko/opencode/shared/Requests.javanew file+27
@@ -0,0 +1,27 @@
1+package soy.iko.opencode.shared;
2+
3+public final class Requests {
4+
5+ public static java.util.List<Request> bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
6+ if (input == null) {
7+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
8+ }
9+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
10+ deserializer.increase_container_depth();
11+
12+ long length = deserializer.deserialize_len();
13+
14+ java.util.List<Request> value = new java.util.ArrayList<>();
15+
16+ for (int i = 0; i < length; i++) {
17+ value.add(Request.deserialize(deserializer));
18+ }
19+
20+ deserializer.decrease_container_depth();
21+
22+ if (deserializer.get_buffer_offset() < input.length) {
23+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
24+ }
25+ return value;
26+ }
27+}
generated/soy/iko/opencode/shared/Screen.javanew file+150
@@ -0,0 +1,150 @@
1+package soy.iko.opencode.shared;
2+
3+
4+public abstract class Screen {
5+
6+ abstract public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError;
7+
8+ public static Screen deserialize(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
9+ int index = deserializer.deserialize_variant_index();
10+ switch (index) {
11+ case 0: return Connect.load(deserializer);
12+ case 1: return Sessions.load(deserializer);
13+ case 2: return Chat.load(deserializer);
14+ default: throw new com.novi.serde.DeserializationError("Unknown variant index for Screen: " + index);
15+ }
16+ }
17+
18+ public byte[] bincodeSerialize() throws com.novi.serde.SerializationError {
19+ com.novi.serde.Serializer serializer = new com.novi.bincode.BincodeSerializer();
20+ serialize(serializer);
21+ return serializer.get_bytes();
22+ }
23+
24+ public static Screen bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
25+ if (input == null) {
26+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
27+ }
28+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
29+ Screen value = deserialize(deserializer);
30+ if (deserializer.get_buffer_offset() < input.length) {
31+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
32+ }
33+ return value;
34+ }
35+
36+ public static final class Connect extends Screen {
37+ public Connect() {
38+ }
39+
40+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
41+ serializer.increase_container_depth();
42+ serializer.serialize_variant_index(0);
43+ serializer.decrease_container_depth();
44+ }
45+
46+ static Connect load(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
47+ deserializer.increase_container_depth();
48+ Builder builder = new Builder();
49+ deserializer.decrease_container_depth();
50+ return builder.build();
51+ }
52+
53+ public boolean equals(Object obj) {
54+ if (this == obj) return true;
55+ if (obj == null) return false;
56+ if (getClass() != obj.getClass()) return false;
57+ Connect other = (Connect) obj;
58+ return true;
59+ }
60+
61+ public int hashCode() {
62+ int value = 7;
63+ return value;
64+ }
65+
66+ public static final class Builder {
67+ public Connect build() {
68+ return new Connect(
69+ );
70+ }
71+ }
72+ }
73+
74+ public static final class Sessions extends Screen {
75+ public Sessions() {
76+ }
77+
78+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
79+ serializer.increase_container_depth();
80+ serializer.serialize_variant_index(1);
81+ serializer.decrease_container_depth();
82+ }
83+
84+ static Sessions load(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
85+ deserializer.increase_container_depth();
86+ Builder builder = new Builder();
87+ deserializer.decrease_container_depth();
88+ return builder.build();
89+ }
90+
91+ public boolean equals(Object obj) {
92+ if (this == obj) return true;
93+ if (obj == null) return false;
94+ if (getClass() != obj.getClass()) return false;
95+ Sessions other = (Sessions) obj;
96+ return true;
97+ }
98+
99+ public int hashCode() {
100+ int value = 7;
101+ return value;
102+ }
103+
104+ public static final class Builder {
105+ public Sessions build() {
106+ return new Sessions(
107+ );
108+ }
109+ }
110+ }
111+
112+ public static final class Chat extends Screen {
113+ public Chat() {
114+ }
115+
116+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
117+ serializer.increase_container_depth();
118+ serializer.serialize_variant_index(2);
119+ serializer.decrease_container_depth();
120+ }
121+
122+ static Chat load(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
123+ deserializer.increase_container_depth();
124+ Builder builder = new Builder();
125+ deserializer.decrease_container_depth();
126+ return builder.build();
127+ }
128+
129+ public boolean equals(Object obj) {
130+ if (this == obj) return true;
131+ if (obj == null) return false;
132+ if (getClass() != obj.getClass()) return false;
133+ Chat other = (Chat) obj;
134+ return true;
135+ }
136+
137+ public int hashCode() {
138+ int value = 7;
139+ return value;
140+ }
141+
142+ public static final class Builder {
143+ public Chat build() {
144+ return new Chat(
145+ );
146+ }
147+ }
148+ }
149+}
150+
generated/soy/iko/opencode/shared/SessionView.javanew file+77
@@ -0,0 +1,77 @@
1+package soy.iko.opencode.shared;
2+
3+
4+public final class SessionView {
5+ public final String id;
6+ public final String title;
7+
8+ public SessionView(String id, String title) {
9+ java.util.Objects.requireNonNull(id, "id must not be null");
10+ java.util.Objects.requireNonNull(title, "title must not be null");
11+ this.id = id;
12+ this.title = title;
13+ }
14+
15+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
16+ serializer.increase_container_depth();
17+ serializer.serialize_str(id);
18+ serializer.serialize_str(title);
19+ serializer.decrease_container_depth();
20+ }
21+
22+ public byte[] bincodeSerialize() throws com.novi.serde.SerializationError {
23+ com.novi.serde.Serializer serializer = new com.novi.bincode.BincodeSerializer();
24+ serialize(serializer);
25+ return serializer.get_bytes();
26+ }
27+
28+ public static SessionView deserialize(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
29+ deserializer.increase_container_depth();
30+ Builder builder = new Builder();
31+ builder.id = deserializer.deserialize_str();
32+ builder.title = deserializer.deserialize_str();
33+ deserializer.decrease_container_depth();
34+ return builder.build();
35+ }
36+
37+ public static SessionView bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
38+ if (input == null) {
39+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
40+ }
41+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
42+ SessionView value = deserialize(deserializer);
43+ if (deserializer.get_buffer_offset() < input.length) {
44+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
45+ }
46+ return value;
47+ }
48+
49+ public boolean equals(Object obj) {
50+ if (this == obj) return true;
51+ if (obj == null) return false;
52+ if (getClass() != obj.getClass()) return false;
53+ SessionView other = (SessionView) obj;
54+ if (!java.util.Objects.equals(this.id, other.id)) { return false; }
55+ if (!java.util.Objects.equals(this.title, other.title)) { return false; }
56+ return true;
57+ }
58+
59+ public int hashCode() {
60+ int value = 7;
61+ value = 31 * value + (this.id != null ? this.id.hashCode() : 0);
62+ value = 31 * value + (this.title != null ? this.title.hashCode() : 0);
63+ return value;
64+ }
65+
66+ public static final class Builder {
67+ public String id;
68+ public String title;
69+
70+ public SessionView build() {
71+ return new SessionView(
72+ id,
73+ title
74+ );
75+ }
76+ }
77+}
generated/soy/iko/opencode/shared/ToolView.javanew file+86
@@ -0,0 +1,86 @@
1+package soy.iko.opencode.shared;
2+
3+
4+public final class ToolView {
5+ public final String name;
6+ public final String status;
7+ public final java.util.Optional<String> title;
8+
9+ public ToolView(String name, String status, java.util.Optional<String> title) {
10+ java.util.Objects.requireNonNull(name, "name must not be null");
11+ java.util.Objects.requireNonNull(status, "status must not be null");
12+ java.util.Objects.requireNonNull(title, "title must not be null");
13+ this.name = name;
14+ this.status = status;
15+ this.title = title;
16+ }
17+
18+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
19+ serializer.increase_container_depth();
20+ serializer.serialize_str(name);
21+ serializer.serialize_str(status);
22+ TraitHelpers.serialize_option_str(title, serializer);
23+ serializer.decrease_container_depth();
24+ }
25+
26+ public byte[] bincodeSerialize() throws com.novi.serde.SerializationError {
27+ com.novi.serde.Serializer serializer = new com.novi.bincode.BincodeSerializer();
28+ serialize(serializer);
29+ return serializer.get_bytes();
30+ }
31+
32+ public static ToolView deserialize(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
33+ deserializer.increase_container_depth();
34+ Builder builder = new Builder();
35+ builder.name = deserializer.deserialize_str();
36+ builder.status = deserializer.deserialize_str();
37+ builder.title = TraitHelpers.deserialize_option_str(deserializer);
38+ deserializer.decrease_container_depth();
39+ return builder.build();
40+ }
41+
42+ public static ToolView bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
43+ if (input == null) {
44+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
45+ }
46+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
47+ ToolView value = deserialize(deserializer);
48+ if (deserializer.get_buffer_offset() < input.length) {
49+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
50+ }
51+ return value;
52+ }
53+
54+ public boolean equals(Object obj) {
55+ if (this == obj) return true;
56+ if (obj == null) return false;
57+ if (getClass() != obj.getClass()) return false;
58+ ToolView other = (ToolView) obj;
59+ if (!java.util.Objects.equals(this.name, other.name)) { return false; }
60+ if (!java.util.Objects.equals(this.status, other.status)) { return false; }
61+ if (!java.util.Objects.equals(this.title, other.title)) { return false; }
62+ return true;
63+ }
64+
65+ public int hashCode() {
66+ int value = 7;
67+ value = 31 * value + (this.name != null ? this.name.hashCode() : 0);
68+ value = 31 * value + (this.status != null ? this.status.hashCode() : 0);
69+ value = 31 * value + (this.title != null ? this.title.hashCode() : 0);
70+ return value;
71+ }
72+
73+ public static final class Builder {
74+ public String name;
75+ public String status;
76+ public java.util.Optional<String> title;
77+
78+ public ToolView build() {
79+ return new ToolView(
80+ name,
81+ status,
82+ title
83+ );
84+ }
85+ }
86+}
generated/soy/iko/opencode/shared/TraitHelpers.javanew file+71
@@ -0,0 +1,71 @@
1+package soy.iko.opencode.shared;
2+
3+final class TraitHelpers {
4+ static void serialize_option_str(java.util.Optional<String> value, com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
5+ if (value.isPresent()) {
6+ serializer.serialize_option_tag(true);
7+ serializer.serialize_str(value.get());
8+ } else {
9+ serializer.serialize_option_tag(false);
10+ }
11+ }
12+
13+ static java.util.Optional<String> deserialize_option_str(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
14+ boolean tag = deserializer.deserialize_option_tag();
15+ if (!tag) {
16+ return java.util.Optional.empty();
17+ } else {
18+ return java.util.Optional.of(deserializer.deserialize_str());
19+ }
20+ }
21+
22+ static void serialize_vector_MessageView(java.util.List<MessageView> value, com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
23+ serializer.serialize_len(value.size());
24+ for (MessageView item : value) {
25+ item.serialize(serializer);
26+ }
27+ }
28+
29+ static java.util.List<MessageView> deserialize_vector_MessageView(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
30+ long length = deserializer.deserialize_len();
31+ java.util.List<MessageView> obj = new java.util.ArrayList<MessageView>((int) length);
32+ for (long i = 0; i < length; i++) {
33+ obj.add(MessageView.deserialize(deserializer));
34+ }
35+ return obj;
36+ }
37+
38+ static void serialize_vector_SessionView(java.util.List<SessionView> value, com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
39+ serializer.serialize_len(value.size());
40+ for (SessionView item : value) {
41+ item.serialize(serializer);
42+ }
43+ }
44+
45+ static java.util.List<SessionView> deserialize_vector_SessionView(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
46+ long length = deserializer.deserialize_len();
47+ java.util.List<SessionView> obj = new java.util.ArrayList<SessionView>((int) length);
48+ for (long i = 0; i < length; i++) {
49+ obj.add(SessionView.deserialize(deserializer));
50+ }
51+ return obj;
52+ }
53+
54+ static void serialize_vector_ToolView(java.util.List<ToolView> value, com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
55+ serializer.serialize_len(value.size());
56+ for (ToolView item : value) {
57+ item.serialize(serializer);
58+ }
59+ }
60+
61+ static java.util.List<ToolView> deserialize_vector_ToolView(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
62+ long length = deserializer.deserialize_len();
63+ java.util.List<ToolView> obj = new java.util.ArrayList<ToolView>((int) length);
64+ for (long i = 0; i < length; i++) {
65+ obj.add(ToolView.deserialize(deserializer));
66+ }
67+ return obj;
68+ }
69+
70+}
71+
generated/soy/iko/opencode/shared/ViewModel.javanew file+185
@@ -0,0 +1,185 @@
1+package soy.iko.opencode.shared;
2+
3+
4+public final class ViewModel {
5+ public final Screen screen;
6+ public final String server_url;
7+ public final String username;
8+ public final String password;
9+ public final Boolean auth_required;
10+ public final Boolean connected;
11+ public final Boolean loading;
12+ public final java.util.Optional<String> error;
13+ public final java.util.List<SessionView> sessions;
14+ public final java.util.Optional<String> current_session_id;
15+ public final String current_session_title;
16+ public final java.util.List<MessageView> messages;
17+ public final String draft;
18+ public final Boolean generating;
19+
20+ public ViewModel(Screen screen, String server_url, String username, String password, Boolean auth_required, Boolean connected, Boolean loading, java.util.Optional<String> error, java.util.List<SessionView> sessions, java.util.Optional<String> current_session_id, String current_session_title, java.util.List<MessageView> messages, String draft, Boolean generating) {
21+ java.util.Objects.requireNonNull(screen, "screen must not be null");
22+ java.util.Objects.requireNonNull(server_url, "server_url must not be null");
23+ java.util.Objects.requireNonNull(username, "username must not be null");
24+ java.util.Objects.requireNonNull(password, "password must not be null");
25+ java.util.Objects.requireNonNull(auth_required, "auth_required must not be null");
26+ java.util.Objects.requireNonNull(connected, "connected must not be null");
27+ java.util.Objects.requireNonNull(loading, "loading must not be null");
28+ java.util.Objects.requireNonNull(error, "error must not be null");
29+ java.util.Objects.requireNonNull(sessions, "sessions must not be null");
30+ java.util.Objects.requireNonNull(current_session_id, "current_session_id must not be null");
31+ java.util.Objects.requireNonNull(current_session_title, "current_session_title must not be null");
32+ java.util.Objects.requireNonNull(messages, "messages must not be null");
33+ java.util.Objects.requireNonNull(draft, "draft must not be null");
34+ java.util.Objects.requireNonNull(generating, "generating must not be null");
35+ this.screen = screen;
36+ this.server_url = server_url;
37+ this.username = username;
38+ this.password = password;
39+ this.auth_required = auth_required;
40+ this.connected = connected;
41+ this.loading = loading;
42+ this.error = error;
43+ this.sessions = sessions;
44+ this.current_session_id = current_session_id;
45+ this.current_session_title = current_session_title;
46+ this.messages = messages;
47+ this.draft = draft;
48+ this.generating = generating;
49+ }
50+
51+ public void serialize(com.novi.serde.Serializer serializer) throws com.novi.serde.SerializationError {
52+ serializer.increase_container_depth();
53+ screen.serialize(serializer);
54+ serializer.serialize_str(server_url);
55+ serializer.serialize_str(username);
56+ serializer.serialize_str(password);
57+ serializer.serialize_bool(auth_required);
58+ serializer.serialize_bool(connected);
59+ serializer.serialize_bool(loading);
60+ TraitHelpers.serialize_option_str(error, serializer);
61+ TraitHelpers.serialize_vector_SessionView(sessions, serializer);
62+ TraitHelpers.serialize_option_str(current_session_id, serializer);
63+ serializer.serialize_str(current_session_title);
64+ TraitHelpers.serialize_vector_MessageView(messages, serializer);
65+ serializer.serialize_str(draft);
66+ serializer.serialize_bool(generating);
67+ serializer.decrease_container_depth();
68+ }
69+
70+ public byte[] bincodeSerialize() throws com.novi.serde.SerializationError {
71+ com.novi.serde.Serializer serializer = new com.novi.bincode.BincodeSerializer();
72+ serialize(serializer);
73+ return serializer.get_bytes();
74+ }
75+
76+ public static ViewModel deserialize(com.novi.serde.Deserializer deserializer) throws com.novi.serde.DeserializationError {
77+ deserializer.increase_container_depth();
78+ Builder builder = new Builder();
79+ builder.screen = Screen.deserialize(deserializer);
80+ builder.server_url = deserializer.deserialize_str();
81+ builder.username = deserializer.deserialize_str();
82+ builder.password = deserializer.deserialize_str();
83+ builder.auth_required = deserializer.deserialize_bool();
84+ builder.connected = deserializer.deserialize_bool();
85+ builder.loading = deserializer.deserialize_bool();
86+ builder.error = TraitHelpers.deserialize_option_str(deserializer);
87+ builder.sessions = TraitHelpers.deserialize_vector_SessionView(deserializer);
88+ builder.current_session_id = TraitHelpers.deserialize_option_str(deserializer);
89+ builder.current_session_title = deserializer.deserialize_str();
90+ builder.messages = TraitHelpers.deserialize_vector_MessageView(deserializer);
91+ builder.draft = deserializer.deserialize_str();
92+ builder.generating = deserializer.deserialize_bool();
93+ deserializer.decrease_container_depth();
94+ return builder.build();
95+ }
96+
97+ public static ViewModel bincodeDeserialize(byte[] input) throws com.novi.serde.DeserializationError {
98+ if (input == null) {
99+ throw new com.novi.serde.DeserializationError("Cannot deserialize null array");
100+ }
101+ com.novi.serde.Deserializer deserializer = new com.novi.bincode.BincodeDeserializer(input);
102+ ViewModel value = deserialize(deserializer);
103+ if (deserializer.get_buffer_offset() < input.length) {
104+ throw new com.novi.serde.DeserializationError("Some input bytes were not read");
105+ }
106+ return value;
107+ }
108+
109+ public boolean equals(Object obj) {
110+ if (this == obj) return true;
111+ if (obj == null) return false;
112+ if (getClass() != obj.getClass()) return false;
113+ ViewModel other = (ViewModel) obj;
114+ if (!java.util.Objects.equals(this.screen, other.screen)) { return false; }
115+ if (!java.util.Objects.equals(this.server_url, other.server_url)) { return false; }
116+ if (!java.util.Objects.equals(this.username, other.username)) { return false; }
117+ if (!java.util.Objects.equals(this.password, other.password)) { return false; }
118+ if (!java.util.Objects.equals(this.auth_required, other.auth_required)) { return false; }
119+ if (!java.util.Objects.equals(this.connected, other.connected)) { return false; }
120+ if (!java.util.Objects.equals(this.loading, other.loading)) { return false; }
121+ if (!java.util.Objects.equals(this.error, other.error)) { return false; }
122+ if (!java.util.Objects.equals(this.sessions, other.sessions)) { return false; }
123+ if (!java.util.Objects.equals(this.current_session_id, other.current_session_id)) { return false; }
124+ if (!java.util.Objects.equals(this.current_session_title, other.current_session_title)) { return false; }
125+ if (!java.util.Objects.equals(this.messages, other.messages)) { return false; }
126+ if (!java.util.Objects.equals(this.draft, other.draft)) { return false; }
127+ if (!java.util.Objects.equals(this.generating, other.generating)) { return false; }
128+ return true;
129+ }
130+
131+ public int hashCode() {
132+ int value = 7;
133+ value = 31 * value + (this.screen != null ? this.screen.hashCode() : 0);
134+ value = 31 * value + (this.server_url != null ? this.server_url.hashCode() : 0);
135+ value = 31 * value + (this.username != null ? this.username.hashCode() : 0);
136+ value = 31 * value + (this.password != null ? this.password.hashCode() : 0);
137+ value = 31 * value + (this.auth_required != null ? this.auth_required.hashCode() : 0);
138+ value = 31 * value + (this.connected != null ? this.connected.hashCode() : 0);
139+ value = 31 * value + (this.loading != null ? this.loading.hashCode() : 0);
140+ value = 31 * value + (this.error != null ? this.error.hashCode() : 0);
141+ value = 31 * value + (this.sessions != null ? this.sessions.hashCode() : 0);
142+ value = 31 * value + (this.current_session_id != null ? this.current_session_id.hashCode() : 0);
143+ value = 31 * value + (this.current_session_title != null ? this.current_session_title.hashCode() : 0);
144+ value = 31 * value + (this.messages != null ? this.messages.hashCode() : 0);
145+ value = 31 * value + (this.draft != null ? this.draft.hashCode() : 0);
146+ value = 31 * value + (this.generating != null ? this.generating.hashCode() : 0);
147+ return value;
148+ }
149+
150+ public static final class Builder {
151+ public Screen screen;
152+ public String server_url;
153+ public String username;
154+ public String password;
155+ public Boolean auth_required;
156+ public Boolean connected;
157+ public Boolean loading;
158+ public java.util.Optional<String> error;
159+ public java.util.List<SessionView> sessions;
160+ public java.util.Optional<String> current_session_id;
161+ public String current_session_title;
162+ public java.util.List<MessageView> messages;
163+ public String draft;
164+ public Boolean generating;
165+
166+ public ViewModel build() {
167+ return new ViewModel(
168+ screen,
169+ server_url,
170+ username,
171+ password,
172+ auth_required,
173+ connected,
174+ loading,
175+ error,
176+ sessions,
177+ current_session_id,
178+ current_session_title,
179+ messages,
180+ draft,
181+ generating
182+ );
183+ }
184+ }
185+}
gradle.properties+7−2
@@ -1,5 +1,10 @@
1org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
1org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
2+org.gradle.caching=true
3+org.gradle.configuration-cache=true
4+
5+# AndroidX
2android.useAndroidX=true
6android.useAndroidX=true
3−kotlin.code.style=official
4android.nonTransitiveRClass=true
7android.nonTransitiveRClass=true
5−android.suppressUnsupportedCompileSdk=37.0
8+
9+# Kotlin
10+kotlin.code.style=official
gradle/libs.versions.toml+23−30
@@ -1,51 +1,44 @@
1[versions]
1[versions]
2−agp = "8.13.2"
2+agp = "8.7.3"
3−kotlin = "2.3.0"
3+kotlin = "2.0.21"
4−coreKtx = "1.17.0"
4+coreKtx = "1.15.0"
5+lifecycle = "2.8.7"
6+activityCompose = "1.9.3"
7+composeBom = "2024.10.01"
8+coroutines = "1.9.0"
9+serialization = "1.7.3"
10+okhttp = "4.12.0"
5junit = "4.13.2"
11junit = "4.13.2"
6−junitVersion = "1.3.0"
12+androidxJunit = "1.2.1"
7−espressoCore = "3.7.0"
13+
8−lifecycleRuntimeKtx = "2.10.0"
9−activityCompose = "1.12.3"
10−composeBom = "2026.01.01"
11−lifecycle = "2.10.0"
12−ktor = "3.1.3"
13−kotlinxCoroutines = "1.10.2"
14−markdownRenderer = "0.43.0"
15[libraries]
14[libraries]
16androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
15androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
17−junit = { group = "junit", name = "junit", version.ref = "junit" }
16+androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
18−androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
17+androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
19−androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
18+androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" }
20−androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
19+androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
21androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
20androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
21+
22androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
22androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
23androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
23androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
24androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
24androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
25androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
25androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
26androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
26androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
27−androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
28−androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
29androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
27androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
30androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
28androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
31−lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
32
29
33−markdown-renderer-m3 = { group = "com.mikepenz", name = "multiplatform-markdown-renderer-m3-android", version.ref = "markdownRenderer" }
30+kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
34−markdown-renderer-core = { group = "com.mikepenz", name = "multiplatform-markdown-renderer-android", version.ref = "markdownRenderer" }
31+kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
35
32
36−ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }
33+okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
37−ktor-client-okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.ref = "ktor" }
34+okhttp-sse = { group = "com.squareup.okhttp3", name = "okhttp-sse", version.ref = "okhttp" }
38−ktor-client-content-negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" }
39−ktor-serialization-kotlinx-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" }
40−ktor-client-logging = { group = "io.ktor", name = "ktor-client-logging", version.ref = "ktor" }
41−ktor-client-auth = { group = "io.ktor", name = "ktor-client-auth", version.ref = "ktor" }
42
35
43−kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }
36+junit = { group = "junit", name = "junit", version.ref = "junit" }
44−kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" }
37+kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }
38+androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidxJunit" }
45
39
46[plugins]
40[plugins]
47android-application = { id = "com.android.application", version.ref = "agp" }
41android-application = { id = "com.android.application", version.ref = "agp" }
48−android-library = { id = "com.android.library", version.ref = "agp" }
49kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
42kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
50kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
43kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
51kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
44kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
settings.gradle.kts+3−1
@@ -21,5 +21,7 @@ dependencyResolutionManagement {
21}
21}
22
22
23rootProject.name = "opencode-android"
23rootProject.name = "opencode-android"
24+
25+// The Crux core lives in `shared/` and is a pure Rust crate (built and tested with
26+// cargo, not Gradle), so the only Gradle module is the Android app shell.
24include(":app")
27include(":app")
25−include(":shared")
shared/Cargo.lock+4−362
@@ -2,71 +2,12 @@
2# It is not intended for manual editing.
2# It is not intended for manual editing.
3version = 4
3version = 4
4
4
5−[[package]]
6−name = "aho-corasick"
7−version = "1.1.4"
8−source = "registry+https://github.com/rust-lang/crates.io-index"
9−checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
10−dependencies = [
11− "memchr",
12−]
13−
14[[package]]
5[[package]]
15name = "allocator-api2"
6name = "allocator-api2"
16version = "0.2.21"
7version = "0.2.21"
17source = "registry+https://github.com/rust-lang/crates.io-index"
8source = "registry+https://github.com/rust-lang/crates.io-index"
18checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
9checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
19
10
20−[[package]]
21−name = "anstream"
22−version = "1.0.0"
23−source = "registry+https://github.com/rust-lang/crates.io-index"
24−checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
25−dependencies = [
26− "anstyle",
27− "anstyle-parse",
28− "anstyle-query",
29− "anstyle-wincon",
30− "colorchoice",
31− "is_terminal_polyfill",
32− "utf8parse",
33−]
34−
35−[[package]]
36−name = "anstyle"
37−version = "1.0.14"
38−source = "registry+https://github.com/rust-lang/crates.io-index"
39−checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
40−
41−[[package]]
42−name = "anstyle-parse"
43−version = "1.0.0"
44−source = "registry+https://github.com/rust-lang/crates.io-index"
45−checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
46−dependencies = [
47− "utf8parse",
48−]
49−
50−[[package]]
51−name = "anstyle-query"
52−version = "1.1.5"
53−source = "registry+https://github.com/rust-lang/crates.io-index"
54−checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
55−dependencies = [
56− "windows-sys",
57−]
58−
59−[[package]]
60−name = "anstyle-wincon"
61−version = "3.0.11"
62−source = "registry+https://github.com/rust-lang/crates.io-index"
63−checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
64−dependencies = [
65− "anstyle",
66− "once_cell_polyfill",
67− "windows-sys",
68−]
69−
70[[package]]
11[[package]]
71name = "anyhow"
12name = "anyhow"
72version = "1.0.103"
13version = "1.0.103"
@@ -105,89 +46,6 @@ dependencies = [
105 "serde",
46 "serde",
106]
47]
107
48
108−[[package]]
109−name = "boltffi"
110−version = "0.27.3"
111−source = "registry+https://github.com/rust-lang/crates.io-index"
112−checksum = "a52185e3efe73ae1e37d4a12ecfc51b03392b3bd6fa677b49bf4e6f4eb30d033"
113−dependencies = [
114− "boltffi_core",
115− "boltffi_macros",
116−]
117−
118−[[package]]
119−name = "boltffi_ast"
120−version = "0.27.3"
121−source = "registry+https://github.com/rust-lang/crates.io-index"
122−checksum = "447bff7f815366882b6c7152284cf60b35bda4ee4920c20f9ca702b3de5d517e"
123−dependencies = [
124− "serde",
125−]
126−
127−[[package]]
128−name = "boltffi_binding"
129−version = "0.27.3"
130−source = "registry+https://github.com/rust-lang/crates.io-index"
131−checksum = "f162e2813a4168530ee144a411921c89b2148e2aedda2327b7f9c46cd57e50d0"
132−dependencies = [
133− "boltffi_ast",
134− "serde",
135− "serde_json",
136−]
137−
138−[[package]]
139−name = "boltffi_core"
140−version = "0.27.3"
141−source = "registry+https://github.com/rust-lang/crates.io-index"
142−checksum = "f6df0e010773b88cf3888511de299425dce2ed0458c9f9d02f454e23590ac1e8"
143−dependencies = [
144− "boltffi_macros",
145− "url",
146− "uuid",
147−]
148−
149−[[package]]
150−name = "boltffi_ffi_rules"
151−version = "0.27.3"
152−source = "registry+https://github.com/rust-lang/crates.io-index"
153−checksum = "8d72f6392c860c87c069c1b11c890d208cae4db143f72230d73ce53155ab2370"
154−dependencies = [
155− "serde",
156− "serde_json",
157− "syn 2.0.118",
158− "walkdir",
159−]
160−
161−[[package]]
162−name = "boltffi_macros"
163−version = "0.27.3"
164−source = "registry+https://github.com/rust-lang/crates.io-index"
165−checksum = "8b2f35b6e1b94218d5178916bdd59f0c358214c146f3ce189fc96ddaa019d435"
166−dependencies = [
167− "boltffi_ast",
168− "boltffi_binding",
169− "boltffi_ffi_rules",
170− "boltffi_scan",
171− "proc-macro2",
172− "quote",
173− "syn 2.0.118",
174−]
175−
176−[[package]]
177−name = "boltffi_scan"
178−version = "0.27.3"
179−source = "registry+https://github.com/rust-lang/crates.io-index"
180−checksum = "4476cba632b69b8736ea499a463a8eddc6fd311f320f98601e338ddc0c9476a0"
181−dependencies = [
182− "boltffi_ast",
183− "proc-macro2",
184− "quote",
185− "serde",
186− "serde_json",
187− "syn 2.0.118",
188− "walkdir",
189−]
190−
191[[package]]
49[[package]]
192name = "bumpalo"
50name = "bumpalo"
193version = "3.20.3"
51version = "3.20.3"
@@ -196,9 +54,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
196
54
197[[package]]
55[[package]]
198name = "bytes"
56name = "bytes"
199−version = "1.12.0"
57+version = "1.12.1"
200source = "registry+https://github.com/rust-lang/crates.io-index"
58source = "registry+https://github.com/rust-lang/crates.io-index"
201−checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
59+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
202
60
203[[package]]
61[[package]]
204name = "cfg-if"
62name = "cfg-if"
@@ -206,52 +64,6 @@ version = "1.0.4"
206source = "registry+https://github.com/rust-lang/crates.io-index"
64source = "registry+https://github.com/rust-lang/crates.io-index"
207checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
65checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
208
66
209−[[package]]
210−name = "clap"
211−version = "4.6.1"
212−source = "registry+https://github.com/rust-lang/crates.io-index"
213−checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
214−dependencies = [
215− "clap_builder",
216− "clap_derive",
217−]
218−
219−[[package]]
220−name = "clap_builder"
221−version = "4.6.0"
222−source = "registry+https://github.com/rust-lang/crates.io-index"
223−checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
224−dependencies = [
225− "anstream",
226− "anstyle",
227− "clap_lex",
228− "strsim",
229−]
230−
231−[[package]]
232−name = "clap_derive"
233−version = "4.6.1"
234−source = "registry+https://github.com/rust-lang/crates.io-index"
235−checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
236−dependencies = [
237− "heck 0.5.0",
238− "proc-macro2",
239− "quote",
240− "syn 2.0.118",
241−]
242−
243−[[package]]
244−name = "clap_lex"
245−version = "1.1.0"
246−source = "registry+https://github.com/rust-lang/crates.io-index"
247−checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
248−
249−[[package]]
250−name = "colorchoice"
251−version = "1.0.5"
252−source = "registry+https://github.com/rust-lang/crates.io-index"
253−checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
254−
255[[package]]
67[[package]]
256name = "const-fnv1a-hash"
68name = "const-fnv1a-hash"
257version = "1.1.0"
69version = "1.1.0"
@@ -284,10 +96,8 @@ dependencies = [
284 "crossbeam-channel",
96 "crossbeam-channel",
285 "crux_macros",
97 "crux_macros",
286 "facet",
98 "facet",
287− "facet_generate",
288 "futures",
99 "futures",
289 "include_dir 0.7.4",
100 "include_dir 0.7.4",
290− "log",
291 "serde",
101 "serde",
292 "serde-generate",
102 "serde-generate",
293 "serde-reflection",
103 "serde-reflection",
@@ -539,26 +349,6 @@ dependencies = [
539 "unsynn",
349 "unsynn",
540]
350]
541
351
542−[[package]]
543−name = "facet_generate"
544−version = "0.17.2"
545−source = "registry+https://github.com/rust-lang/crates.io-index"
546−checksum = "4bab57b923bae6e204f5e47643054a9c5ad9c3bd9aadec66df741790de8a859f"
547−dependencies = [
548− "derive_builder",
549− "facet",
550− "facet-generate-attrs",
551− "heck 0.5.0",
552− "include_dir 0.7.4",
553− "indent",
554− "indoc",
555− "regex",
556− "serde",
557− "serde_json",
558− "textwrap 0.16.2",
559− "thiserror 2.0.18",
560−]
561−
562[[package]]
352[[package]]
563name = "fnv"
353name = "fnv"
564version = "1.0.7"
354version = "1.0.7"
@@ -890,27 +680,6 @@ dependencies = [
890 "quote",
680 "quote",
891]
681]
892
682
893−[[package]]
894−name = "indent"
895−version = "0.1.1"
896−source = "registry+https://github.com/rust-lang/crates.io-index"
897−checksum = "d9f1a0777d972970f204fdf8ef319f1f4f8459131636d7e3c96c5d59570d0fa6"
898−
899−[[package]]
900−name = "indoc"
901−version = "2.0.7"
902−source = "registry+https://github.com/rust-lang/crates.io-index"
903−checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
904−dependencies = [
905− "rustversion",
906−]
907−
908−[[package]]
909−name = "is_terminal_polyfill"
910−version = "1.70.2"
911−source = "registry+https://github.com/rust-lang/crates.io-index"
912−checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
913−
914[[package]]
683[[package]]
915name = "itoa"
684name = "itoa"
916version = "1.0.18"
685version = "1.0.18"
@@ -940,12 +709,6 @@ version = "0.8.2"
940source = "registry+https://github.com/rust-lang/crates.io-index"
709source = "registry+https://github.com/rust-lang/crates.io-index"
941checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
710checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
942
711
943−[[package]]
944−name = "log"
945−version = "0.4.33"
946−source = "registry+https://github.com/rust-lang/crates.io-index"
947−checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
948−
949[[package]]
712[[package]]
950name = "memchr"
713name = "memchr"
951version = "2.8.3"
714version = "2.8.3"
@@ -970,12 +733,6 @@ version = "1.21.4"
970source = "registry+https://github.com/rust-lang/crates.io-index"
733source = "registry+https://github.com/rust-lang/crates.io-index"
971checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
734checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
972
735
973−[[package]]
974−name = "once_cell_polyfill"
975−version = "1.70.2"
976−source = "registry+https://github.com/rust-lang/crates.io-index"
977−checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
978−
979[[package]]
736[[package]]
980name = "percent-encoding"
737name = "percent-encoding"
981version = "2.3.2"
738version = "2.3.2"
@@ -1128,35 +885,6 @@ dependencies = [
1128 "getrandom",
885 "getrandom",
1129]
886]
1130
887
1131−[[package]]
1132−name = "regex"
1133−version = "1.12.4"
1134−source = "registry+https://github.com/rust-lang/crates.io-index"
1135−checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"
1136−dependencies = [
1137− "aho-corasick",
1138− "memchr",
1139− "regex-automata",
1140− "regex-syntax",
1141−]
1142−
1143−[[package]]
1144−name = "regex-automata"
1145−version = "0.4.14"
1146−source = "registry+https://github.com/rust-lang/crates.io-index"
1147−checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
1148−dependencies = [
1149− "aho-corasick",
1150− "memchr",
1151− "regex-syntax",
1152−]
1153−
1154−[[package]]
1155−name = "regex-syntax"
1156−version = "0.8.11"
1157−source = "registry+https://github.com/rust-lang/crates.io-index"
1158−checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
1159−
1160[[package]]
888[[package]]
1161name = "rustc-hash"
889name = "rustc-hash"
1162version = "2.1.3"
890version = "2.1.3"
@@ -1175,15 +903,6 @@ version = "1.0.23"
1175source = "registry+https://github.com/rust-lang/crates.io-index"
903source = "registry+https://github.com/rust-lang/crates.io-index"
1176checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
904checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
1177
905
1178−[[package]]
1179−name = "same-file"
1180−version = "1.0.6"
1181−source = "registry+https://github.com/rust-lang/crates.io-index"
1182−checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
1183−dependencies = [
1184− "winapi-util",
1185−]
1186−
1187[[package]]
906[[package]]
1188name = "serde"
907name = "serde"
1189version = "1.0.228"
908version = "1.0.228"
@@ -1205,7 +924,7 @@ dependencies = [
1205 "phf",
924 "phf",
1206 "serde",
925 "serde",
1207 "serde-reflection",
926 "serde-reflection",
1208− "textwrap 0.13.4",
927+ "textwrap",
1209]
928]
1210
929
1211[[package]]
930[[package]]
@@ -1280,12 +999,8 @@ version = "0.1.0"
1280dependencies = [
999dependencies = [
1281 "anyhow",
1000 "anyhow",
1282 "base64",
1001 "base64",
1283− "bincode",
1284− "boltffi",
1285− "clap",
1286 "crux_core",
1002 "crux_core",
1287 "crux_http",
1003 "crux_http",
1288− "facet",
1289 "serde",
1004 "serde",
1290 "serde_json",
1005 "serde_json",
1291]
1006]
@@ -1366,18 +1081,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1366checksum = "cd05616119e612a8041ef58f2b578906cc2531a6069047ae092cfb86a325d835"
1081checksum = "cd05616119e612a8041ef58f2b578906cc2531a6069047ae092cfb86a325d835"
1367dependencies = [
1082dependencies = [
1368 "smawk",
1083 "smawk",
1369− "unicode-width 0.1.14",
1084+ "unicode-width",
1370−]
1371−
1372−[[package]]
1373−name = "textwrap"
1374−version = "0.16.2"
1375−source = "registry+https://github.com/rust-lang/crates.io-index"
1376−checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"
1377−dependencies = [
1378− "smawk",
1379− "unicode-linebreak",
1380− "unicode-width 0.2.2",
1381]
1085]
1382
1086
1383[[package]]
1087[[package]]
@@ -1436,12 +1140,6 @@ version = "1.0.24"
1436source = "registry+https://github.com/rust-lang/crates.io-index"
1140source = "registry+https://github.com/rust-lang/crates.io-index"
1437checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
1141checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
1438
1142
1439−[[package]]
1440−name = "unicode-linebreak"
1441−version = "0.1.5"
1442−source = "registry+https://github.com/rust-lang/crates.io-index"
1443−checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
1444−
1445[[package]]
1143[[package]]
1446name = "unicode-segmentation"
1144name = "unicode-segmentation"
1447version = "1.13.3"
1145version = "1.13.3"
@@ -1454,12 +1152,6 @@ version = "0.1.14"
1454source = "registry+https://github.com/rust-lang/crates.io-index"
1152source = "registry+https://github.com/rust-lang/crates.io-index"
1455checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
1153checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
1456
1154
1457−[[package]]
1458−name = "unicode-width"
1459−version = "0.2.2"
1460−source = "registry+https://github.com/rust-lang/crates.io-index"
1461−checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
1462−
1463[[package]]
1155[[package]]
1464name = "unsynn"
1156name = "unsynn"
1465version = "0.3.0"
1157version = "0.3.0"
@@ -1489,38 +1181,12 @@ version = "1.0.4"
1489source = "registry+https://github.com/rust-lang/crates.io-index"
1181source = "registry+https://github.com/rust-lang/crates.io-index"
1490checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
1182checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
1491
1183
1492−[[package]]
1493−name = "utf8parse"
1494−version = "0.2.2"
1495−source = "registry+https://github.com/rust-lang/crates.io-index"
1496−checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
1497−
1498−[[package]]
1499−name = "uuid"
1500−version = "1.23.4"
1501−source = "registry+https://github.com/rust-lang/crates.io-index"
1502−checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"
1503−dependencies = [
1504− "js-sys",
1505− "wasm-bindgen",
1506−]
1507−
1508[[package]]
1184[[package]]
1509name = "version_check"
1185name = "version_check"
1510version = "0.9.5"
1186version = "0.9.5"
1511source = "registry+https://github.com/rust-lang/crates.io-index"
1187source = "registry+https://github.com/rust-lang/crates.io-index"
1512checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
1188checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
1513
1189
1514−[[package]]
1515−name = "walkdir"
1516−version = "2.5.0"
1517−source = "registry+https://github.com/rust-lang/crates.io-index"
1518−checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
1519−dependencies = [
1520− "same-file",
1521− "winapi-util",
1522−]
1523−
1524[[package]]
1190[[package]]
1525name = "wasi"
1191name = "wasi"
1526version = "0.11.1+wasi-snapshot-preview1"
1192version = "0.11.1+wasi-snapshot-preview1"
@@ -1582,30 +1248,6 @@ dependencies = [
1582 "wasm-bindgen",
1248 "wasm-bindgen",
1583]
1249]
1584
1250
1585−[[package]]
1586−name = "winapi-util"
1587−version = "0.1.11"
1588−source = "registry+https://github.com/rust-lang/crates.io-index"
1589−checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
1590−dependencies = [
1591− "windows-sys",
1592−]
1593−
1594−[[package]]
1595−name = "windows-link"
1596−version = "0.2.1"
1597−source = "registry+https://github.com/rust-lang/crates.io-index"
1598−checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
1599−
1600−[[package]]
1601−name = "windows-sys"
1602−version = "0.61.2"
1603−source = "registry+https://github.com/rust-lang/crates.io-index"
1604−checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
1605−dependencies = [
1606− "windows-link",
1607−]
1608−
1609[[package]]
1251[[package]]
1610name = "writeable"
1252name = "writeable"
1611version = "0.6.3"
1253version = "0.6.3"
shared/Cargo.toml+8−11
@@ -1,34 +1,31 @@
1[package]
1[package]
2name = "shared"
2name = "shared"
3version = "0.1.0"
3version = "0.1.0"
4−edition = "2024"
4+edition = "2021"
5−rust-version = "1.90"
5+rust-version = "1.85"
6license = "Apache-2.0"
6license = "Apache-2.0"
7+description = "Crux core for the opencode Android client"
7
8
8[lib]
9[lib]
9−crate-type = ["cdylib", "lib", "staticlib"]
10+# `lib` for native cargo test + typegen; cdylib/staticlib keep the door open for a
11+# real JNI build once an Android cross-toolchain (NDK + rust-std) is available.
12+crate-type = ["lib", "staticlib", "cdylib"]
10
13
11[[bin]]
14[[bin]]
12name = "codegen"
15name = "codegen"
13−required-features = ["codegen"]
16+required-features = ["typegen"]
14
17
15[features]
18[features]
16−facet_typegen = ["crux_core/facet_typegen"]
19+typegen = ["crux_core/typegen", "dep:anyhow"]
17−codegen = ["facet_typegen", "dep:clap", "dep:anyhow", "crux_core/typegen"]
18
20
19[dependencies]
21[dependencies]
20−facet = "=0.44"
21−boltffi = "0.27"
22crux_core = "0.19"
22crux_core = "0.19"
23crux_http = "0.19"
23crux_http = "0.19"
24serde = { version = "1", features = ["derive"] }
24serde = { version = "1", features = ["derive"] }
25serde_json = "1"
25serde_json = "1"
26base64 = "0.22"
26base64 = "0.22"
27
27
28−# Optional codegen deps
29anyhow = { version = "1", optional = true }
28anyhow = { version = "1", optional = true }
30−clap = { version = "4", optional = true, features = ["derive"] }
31
29
32[dev-dependencies]
30[dev-dependencies]
33−bincode = "1"
34crux_core = { version = "0.19", features = ["testing"] }
31crux_core = { version = "0.19", features = ["testing"] }
shared/build.gradle.ktsdeleted−39
@@ -1,39 +0,0 @@
1−import org.jetbrains.kotlin.gradle.dsl.JvmTarget
2−
3−plugins {
4− alias(libs.plugins.android.library)
5− alias(libs.plugins.kotlin.android)
6−}
7−
8−android {
9− namespace = "soy.iko.opencode.core"
10−
11− compileSdk = 37
12− buildToolsVersion = "37.0.0"
13−
14− defaultConfig {
15− minSdk = 26
16− }
17−
18− compileOptions {
19− sourceCompatibility = JavaVersion.VERSION_11
20− targetCompatibility = JavaVersion.VERSION_11
21− }
22−
23− kotlin {
24− compilerOptions {
25− jvmTarget = JvmTarget.JVM_11
26− }
27− }
28−
29− sourceSets {
30− getByName("main") {
31− kotlin.srcDirs("${projectDir}/../generated")
32− jniLibs.srcDirs("${projectDir}/../generated/jniLibs")
33− }
34− }
35−}
36−
37−dependencies {
38− implementation(libs.kotlinx.coroutines.android)
39−}
shared/src/app.rs+761−572
@@ -1,133 +1,230 @@
1+//! The Crux `App`: model, events, effects, update logic and view.
2+//!
3+//! Streaming works like this: after a successful connect the shell opens the
4+//! `/event` SSE stream and forwards every decoded event as
5+//! [`Event::ServerEvent`]. The core parses those and mutates the chat
6+//! incrementally — creating the assistant message on `message.updated`, growing
7+//! its text on `message.part.updated`, and clearing the "generating" flag on
8+//! `session.idle`. User messages are shown optimistically the moment they're
9+//! sent, so the stream only ever *adds* assistant content.
10+
1use base64::Engine;
11use base64::Engine;
2use crux_core::{
12use crux_core::{
3− App, Command,
4 macros::effect,
13 macros::effect,
5− render::{RenderOperation, render},
14+ render::{render, RenderOperation},
15+ App, Command,
6};
16};
7use crux_http::command::{Http, RequestBuilder};
17use crux_http::command::{Http, RequestBuilder};
8use crux_http::protocol::HttpRequest;
18use crux_http::protocol::HttpRequest;
9−use facet::Facet;
10use serde::{Deserialize, Serialize};
19use serde::{Deserialize, Serialize};
11
20
12−// ─── Events ────────────────────────────────────────────────────────────────
21+use crate::protocol::{self, ServerEvent, WireMessageEnvelope, WirePart};
13
22
14−#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
23+/// Result of an HTTP effect handed back to the core.
15−#[repr(C)]
24+pub type HttpResult = Result<crux_http::Response<String>, crux_http::HttpError>;
16−pub enum Event {
25+
17− // ── Type-generated events (sent from Shell → Core).
26+// ─── Events ──────────────────────────────────────────────────────────────────
18− // These MUST be contiguous starting at index 0 to match the
19− // generated Kotlin/Swift/TS enum indices. Do not interleave
20− // skipped variants here. ──────────────────────────────────────
21
27
22− // Lifecycle
28+pub enum Event {
29+ // Lifecycle / connect
23 Start,
30 Start,
24 ServerUrlChanged(String),
31 ServerUrlChanged(String),
25 UsernameChanged(String),
32 UsernameChanged(String),
26 PasswordChanged(String),
33 PasswordChanged(String),
27 Connect,
34 Connect,
28− CancelAuth,
29
35
30− // Session list
36+ // Sessions
31 LoadSessions,
37 LoadSessions,
32 SelectSession(String),
38 SelectSession(String),
33 CreateSession,
39 CreateSession,
40+ DeleteSession(String),
34
41
35 // Chat
42 // Chat
36 LoadMessages(String),
43 LoadMessages(String),
44+ DraftChanged(String),
37 SendMessage(String),
45 SendMessage(String),
46+ CancelGeneration,
38
47
39− // SSE event received
48+ // A raw event line from the shell's `/event` SSE subscription.
40− EventReceived(String),
49+ ServerEvent(String),
41
50
42− // Navigation
51+ // Navigation / misc
43− NavigateToChat(String),
44 NavigateToSessions,
52 NavigateToSessions,
45 NavigateToConnect,
53 NavigateToConnect,
46−
47− // Errors
48 DismissError,
54 DismissError,
49
55
50− // ── Internal events (skipped from typegen, sent only via then_send).
56+ // ── Internal: results of HTTP effects (never sent by the shell) ──────────
51− // These occupy higher discriminant indices that are never
57+ HealthProbed(HttpResult),
52− // produced by the shell, so the index gap is harmless. ─────────
58+ SessionsLoaded(HttpResult),
53−
59+ SessionCreated(HttpResult),
54− #[serde(skip)]
60+ MessagesLoaded(String, HttpResult),
55− #[facet(skip)]
61+ PromptSent(HttpResult),
56− SessionsLoaded(#[facet(opaque)] HttpResult<String>),
62+ SessionDeleted(HttpResult),
57− #[serde(skip)]
63+ Aborted(HttpResult),
58− #[facet(skip)]
59− SessionCreated(#[facet(opaque)] HttpResult<String>),
60− #[serde(skip)]
61− #[facet(skip)]
62− MessagesLoaded(#[facet(opaque)] HttpResult<String>),
63− #[serde(skip)]
64− #[facet(skip)]
65− MessageSent(#[facet(opaque)] HttpResult<String>),
66− #[serde(skip)]
67− #[facet(skip)]
68− CrashLog(String),
69− #[serde(skip)]
70− #[facet(skip)]
71− HealthProbed(#[facet(opaque)] HttpResult<String>),
72}
64}
73
65
74−// ─── Effects ───────────────────────────────────────────────────────────────
66+// ─── Effects ─────────────────────────────────────────────────────────────────
75
67
76−#[effect(facet_typegen)]
68+#[effect]
77#[derive(Debug)]
69#[derive(Debug)]
78pub enum Effect {
70pub enum Effect {
79 Render(RenderOperation),
71 Render(RenderOperation),
80 Http(HttpRequest),
72 Http(HttpRequest),
81}
73}
82
74
83−// ─── HTTP result wrapper (opaque, not type-generated) ──────────────────────
75+// ─── Model ───────────────────────────────────────────────────────────────────
84−
85−pub type HttpResult<T> = Result<crux_http::Response<T>, crux_http::HttpError>;
86−
87−// ─── Model ─────────────────────────────────────────────────────────────────
88
76
89#[derive(Default)]
77#[derive(Default)]
90pub struct Model {
78pub struct Model {
91 server_url: String,
79 server_url: String,
92 username: String,
80 username: String,
93 password: String,
81 password: String,
94− /// Set once the server replies 401 to an unauthenticated probe.
82+ /// The server answered 401 to an unauthenticated probe — show credentials.
95− /// The view surfaces this so the shell can show credential fields.
96 auth_required: bool,
83 auth_required: bool,
97− /// Set once a request with credentials succeeds. All subsequent
84+ /// Credentials were accepted; attach the auth header to every request.
98− /// requests carry the Authorization header.
99 authed: bool,
85 authed: bool,
100 connected: bool,
86 connected: bool,
101 loading: bool,
87 loading: bool,
102 error: Option<String>,
88 error: Option<String>,
103− sessions: Vec<SessionSummary>,
89+ screen: Screen,
90+
91+ sessions: Vec<SessionView>,
104 current_session_id: Option<String>,
92 current_session_id: Option<String>,
105 current_session_title: String,
93 current_session_title: String,
106− messages: Vec<MessageView>,
94+
107− draft_message: String,
95+ messages: Vec<MsgState>,
108− /// True between sending a message and the assistant reply arriving.
96+ draft: String,
109 generating: bool,
97 generating: bool,
110− /// Accumulated crash logs (sent from the shell's uncaught-exception handler)
98+
111− crash_logs: Vec<String>,
99+ /// Monotonic counter for optimistic (client-side) user-message ids.
100+ local_seq: u64,
101+}
102+
103+impl Model {
104+ fn message_mut(&mut self, id: &str) -> Option<&mut MsgState> {
105+ self.messages.iter_mut().find(|m| m.id == id)
106+ }
107+
108+ fn has_credentials(&self) -> bool {
109+ !self.username.is_empty() || !self.password.is_empty()
110+ }
111+
112+ fn is_current(&self, session_id: &str) -> bool {
113+ self.current_session_id.as_deref() == Some(session_id)
114+ }
115+}
116+
117+/// Internal per-message state. Parts are tracked by id so streaming updates can
118+/// upsert them; the [`MessageView`] handed to the shell is derived from these.
119+struct MsgState {
120+ id: String,
121+ role: String,
122+ time: u64,
123+ status: MessageStatus,
124+ streaming: bool,
125+ text_parts: Vec<(String, String)>,
126+ reasoning_parts: Vec<(String, String)>,
127+ tool_parts: Vec<(String, ToolView)>,
128+}
129+
130+impl MsgState {
131+ fn new(id: String, role: String, time: u64) -> Self {
132+ Self {
133+ id,
134+ role,
135+ time,
136+ status: MessageStatus::Sent,
137+ streaming: false,
138+ text_parts: Vec::new(),
139+ reasoning_parts: Vec::new(),
140+ tool_parts: Vec::new(),
141+ }
142+ }
143+
144+ fn upsert_part(parts: &mut Vec<(String, String)>, id: &str, text: String) {
145+ if let Some(slot) = parts.iter_mut().find(|(pid, _)| pid == id) {
146+ slot.1 = text;
147+ } else {
148+ parts.push((id.to_string(), text));
149+ }
150+ }
151+
152+ fn upsert_tool(&mut self, id: &str, view: ToolView) {
153+ if let Some(slot) = self.tool_parts.iter_mut().find(|(pid, _)| pid == id) {
154+ slot.1 = view;
155+ } else {
156+ self.tool_parts.push((id.to_string(), view));
157+ }
158+ }
159+
160+ fn remove_part(&mut self, part_id: &str) {
161+ self.text_parts.retain(|(pid, _)| pid != part_id);
162+ self.reasoning_parts.retain(|(pid, _)| pid != part_id);
163+ self.tool_parts.retain(|(pid, _)| pid != part_id);
164+ }
165+
166+ fn to_view(&self) -> MessageView {
167+ let join = |parts: &[(String, String)]| {
168+ parts.iter().map(|(_, t)| t.as_str()).collect::<String>()
169+ };
170+ let reasoning = join(&self.reasoning_parts);
171+ MessageView {
172+ id: self.id.clone(),
173+ role: self.role.clone(),
174+ text: join(&self.text_parts),
175+ reasoning: (!reasoning.is_empty()).then_some(reasoning),
176+ tools: self.tool_parts.iter().map(|(_, t)| t.clone()).collect(),
177+ time: self.time,
178+ status: self.status.clone(),
179+ streaming: self.streaming,
180+ }
181+ }
112}
182}
113
183
114−#[derive(Clone, Debug, Default)]
184+// ─── View model ──────────────────────────────────────────────────────────────
115−pub struct SessionSummary {
185+
186+#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
187+pub enum Screen {
188+ #[default]
189+ Connect,
190+ Sessions,
191+ Chat,
192+}
193+
194+#[derive(Serialize, Deserialize, Clone, Debug, Default)]
195+pub struct SessionView {
116 pub id: String,
196 pub id: String,
117 pub title: String,
197 pub title: String,
118}
198}
119
199
120−#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default)]
200+#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
201+pub enum MessageStatus {
202+ #[default]
203+ Sent,
204+ Pending,
205+ Failed,
206+}
207+
208+#[derive(Serialize, Deserialize, Clone, Debug, Default)]
209+pub struct ToolView {
210+ pub name: String,
211+ pub status: String,
212+ pub title: Option<String>,
213+}
214+
215+#[derive(Serialize, Deserialize, Clone, Debug, Default)]
121pub struct MessageView {
216pub struct MessageView {
122 pub id: String,
217 pub id: String,
123 pub role: String,
218 pub role: String,
124 pub text: String,
219 pub text: String,
220+ pub reasoning: Option<String>,
221+ pub tools: Vec<ToolView>,
125 pub time: u64,
222 pub time: u64,
223+ pub status: MessageStatus,
224+ pub streaming: bool,
126}
225}
127
226
128−// ─── ViewModel ─────────────────────────────────────────────────────────────
227+#[derive(Serialize, Deserialize, Clone, Debug, Default)]
129−
130−#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default)]
131pub struct ViewModel {
228pub struct ViewModel {
132 pub screen: Screen,
229 pub screen: Screen,
133 pub server_url: String,
230 pub server_url: String,
@@ -141,63 +238,42 @@ pub struct ViewModel {
141 pub current_session_id: Option<String>,
238 pub current_session_id: Option<String>,
142 pub current_session_title: String,
239 pub current_session_title: String,
143 pub messages: Vec<MessageView>,
240 pub messages: Vec<MessageView>,
144− pub draft_message: String,
241+ pub draft: String,
145− /// True while waiting for the assistant to reply after the user sends.
146 pub generating: bool,
242 pub generating: bool,
147− pub crash_log_count: u32,
148− pub latest_crash_log: Option<String>,
149}
243}
150
244
151−#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
245+// ─── App ─────────────────────────────────────────────────────────────────────
152−#[repr(C)]
153−pub enum Screen {
154− #[default]
155− Connect,
156− Sessions,
157− Chat,
158−}
159−
160−#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default)]
161−pub struct SessionView {
162− pub id: String,
163− pub title: String,
164−}
165−
166−// ─── App ───────────────────────────────────────────────────────────────────
167
246
168#[derive(Default)]
247#[derive(Default)]
169pub struct OpencodeApp;
248pub struct OpencodeApp;
170
249
171impl OpencodeApp {
250impl OpencodeApp {
172− /// Build a GET request to `path`, adding the Basic-Auth header when the
173− /// model has credentials. The header is always added once `authed` is true
174− /// (i.e. after the server has accepted credentials), and also during the
175− /// credential-retry attempt itself.
176 fn get(&self, model: &Model, path: &str) -> RequestBuilder<Effect, Event, String> {
251 fn get(&self, model: &Model, path: &str) -> RequestBuilder<Effect, Event, String> {
177 let url = format!("{}{path}", model.server_url);
252 let url = format!("{}{path}", model.server_url);
178− let req = Http::get(&url).expect_string();
253+ self.with_auth(Http::get(&url).expect_string(), model)
179− self.with_auth(req, model)
180 }
254 }
181
255
182− /// Build a POST request to `path` with the given body bytes.
256+ fn post_json(&self, model: &Model, path: &str, body: &serde_json::Value) -> RequestBuilder<Effect, Event, String> {
183− fn post(&self, model: &Model, path: &str, body: Vec<u8>) -> RequestBuilder<Effect, Event, String> {
184 let url = format!("{}{path}", model.server_url);
257 let url = format!("{}{path}", model.server_url);
185− let req = Http::post(&url).expect_string().body_bytes(body);
258+ let bytes = serde_json::to_vec(body).unwrap_or_default();
259+ let req = Http::post(&url)
260+ .expect_string()
261+ .header("Content-Type", "application/json")
262+ .body_bytes(bytes);
186 self.with_auth(req, model)
263 self.with_auth(req, model)
187 }
264 }
188
265
189− /// Attach the Basic-Auth `Authorization` header if the model carries
266+ fn delete(&self, model: &Model, path: &str) -> RequestBuilder<Effect, Event, String> {
190− /// credentials. Uses RFC 7617 `Basic` scheme with base64-encoded
267+ let url = format!("{}{path}", model.server_url);
191− /// `username:password`.
268+ self.with_auth(Http::delete(&url).expect_string(), model)
192− fn with_auth<E>(
269+ }
193− &self,
270+
194− req: RequestBuilder<Effect, Event, E>,
271+ /// Attach an RFC 7617 Basic-Auth header when the model carries credentials.
195− model: &Model,
272+ fn with_auth<E>(&self, req: RequestBuilder<Effect, Event, E>, model: &Model) -> RequestBuilder<Effect, Event, E>
196− ) -> RequestBuilder<Effect, Event, E>
197 where
273 where
198 E: 'static,
274 E: 'static,
199 {
275 {
200− if !model.username.is_empty() || !model.password.is_empty() {
276+ if model.has_credentials() {
201 let creds = format!("{}:{}", model.username, model.password);
277 let creds = format!("{}:{}", model.username, model.password);
202 let encoded = base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
278 let encoded = base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
203 req.header("Authorization", format!("Basic {encoded}"))
279 req.header("Authorization", format!("Basic {encoded}"))
@@ -205,13 +281,6 @@ impl OpencodeApp {
205 req
281 req
206 }
282 }
207 }
283 }
208−
209− /// Render helper that also stamps the crash-log summary into the view.
210− fn render_with_crashes(&self, _model: &Model) -> Command<Effect, Event> {
211− // render() is the base; the view() function reads the model directly
212− // for crash-log fields, so a plain render suffices.
213− render()
214− }
215}
284}
216
285
217impl App for OpencodeApp {
286impl App for OpencodeApp {
@@ -222,242 +291,256 @@ impl App for OpencodeApp {
222
291
223 fn update(&self, event: Event, model: &mut Model) -> Command<Effect, Event> {
292 fn update(&self, event: Event, model: &mut Model) -> Command<Effect, Event> {
224 match event {
293 match event {
225− Event::Start => {
294+ // ── Lifecycle / connect ─────────────────────────────────────────
226− // Don't reset server_url here — the shell restores it from
295+ Event::Start => render(),
227− // persisted storage via ServerUrlChanged before any connect.
296+
228− render()
297+ // Store the field verbatim while typing; normalizing here would fight
229− }
298+ // the user's edits (e.g. eat the "://" as they type it). The URL is
230−
299+ // normalized once, on Connect.
300+ // Clear any prior error as soon as the user edits a field, so a stale
301+ // message (e.g. "Invalid credentials") doesn't linger while they correct it.
231 Event::ServerUrlChanged(url) => {
302 Event::ServerUrlChanged(url) => {
232 model.server_url = url;
303 model.server_url = url;
304+ if model.error.is_some() {
305+ model.error = None;
306+ }
233 render()
307 render()
234 }
308 }
235−
236 Event::UsernameChanged(u) => {
309 Event::UsernameChanged(u) => {
237 model.username = u;
310 model.username = u;
311+ if model.error.is_some() {
312+ model.error = None;
313+ }
238 render()
314 render()
239 }
315 }
240−
241 Event::PasswordChanged(p) => {
316 Event::PasswordChanged(p) => {
242 model.password = p;
317 model.password = p;
318+ if model.error.is_some() {
319+ model.error = None;
320+ }
243 render()
321 render()
244 }
322 }
245
323
246 Event::Connect => {
324 Event::Connect => {
325+ model.server_url = normalize_url(&model.server_url);
326+ if model.server_url.is_empty() {
327+ model.error = Some("Enter a server URL".to_string());
328+ return render();
329+ }
247 model.loading = true;
330 model.loading = true;
248 model.error = None;
331 model.error = None;
249− // Probe health. `with_auth` attaches credentials if present,
250− // so a retry after a 401 carries the Authorization header.
251− let req = self.get(model, "/global/health");
252− req.build().then_send(|result| Event::HealthProbed(result))
253− }
254−
255− Event::CancelAuth => {
256 model.auth_required = false;
332 model.auth_required = false;
257− model.username.clear();
333+ render().and(self.get(model, "/global/health").build().then_send(Event::HealthProbed))
258− model.password.clear();
259− model.loading = false;
260− render()
261 }
334 }
262
335
336+ Event::HealthProbed(result) => self.on_health_probed(model, result),
337+
338+ // ── Sessions ────────────────────────────────────────────────────
263 Event::LoadSessions => {
339 Event::LoadSessions => {
264 model.loading = true;
340 model.loading = true;
265− self.get(model, "/session").build().then_send(Event::SessionsLoaded)
341+ render().and(self.get(model, "/session").build().then_send(Event::SessionsLoaded))
266 }
342 }
267
343
268 Event::SessionsLoaded(result) => {
344 Event::SessionsLoaded(result) => {
269 model.loading = false;
345 model.loading = false;
270− match result {
346+ match ok_body(result) {
271− Ok(mut response) => {
347+ Ok(body) => {
272− let body = response.take_body().unwrap_or_default();
348+ model.sessions = protocol::parse_sessions(&body)
273− model.sessions = parse_sessions(&body);
349+ .into_iter()
274− model.connected = true;
350+ .map(|s| SessionView {
275− // Refresh the current session's title in case it was
351+ id: s.id,
276− // populated after creation.
352+ title: display_title(&s.title),
277− if let Some(id) = model.current_session_id.clone() {
353+ })
278− if let Some(s) = model.sessions.iter().find(|s| s.id == id) {
354+ .collect();
279− model.current_session_title = s.title.clone();
355+ // Impose a stable alphabetical order so the list doesn't shuffle
280− }
356+ // with whatever order the server happens to return sessions in.
281− }
357+ model.sessions.sort_by_key(|s| s.title.to_lowercase());
282− render()
283− }
284− Err(e) => {
285− model.error = Some(format!("Failed to load sessions: {e}"));
286− render()
287 }
358 }
359+ Err(e) => model.error = Some(e),
288 }
360 }
361+ render()
289 }
362 }
290
363
291 Event::SelectSession(id) => {
364 Event::SelectSession(id) => {
292− model.current_session_id = Some(id.clone());
293 model.current_session_title = model
365 model.current_session_title = model
294 .sessions
366 .sessions
295 .iter()
367 .iter()
296 .find(|s| s.id == id)
368 .find(|s| s.id == id)
297 .map(|s| s.title.clone())
369 .map(|s| s.title.clone())
298 .unwrap_or_default();
370 .unwrap_or_default();
299− Command::event(Event::NavigateToChat(id))
300− }
301−
302− Event::NavigateToChat(id) => {
303 model.current_session_id = Some(id.clone());
371 model.current_session_id = Some(id.clone());
304− model.current_session_title = model
305− .sessions
306− .iter()
307− .find(|s| s.id == id)
308− .map(|s| s.title.clone())
309− .unwrap_or_default();
310 model.messages.clear();
372 model.messages.clear();
373+ model.screen = Screen::Chat;
374+ model.loading = true;
375+ model.error = None;
311 render().and(Command::event(Event::LoadMessages(id)))
376 render().and(Command::event(Event::LoadMessages(id)))
312 }
377 }
313
378
314− Event::NavigateToSessions => {
379+ Event::CreateSession => {
315− model.current_session_id = None;
380+ model.loading = true;
316− model.current_session_title.clear();
381+ render().and(
317− model.messages.clear();
382+ self.post_json(model, "/session", &serde_json::json!({}))
318− model.generating = false;
383+ .build()
319− render()
384+ .then_send(Event::SessionCreated),
385+ )
320 }
386 }
321
387
322− Event::NavigateToConnect => {
388+ Event::SessionCreated(result) => {
323− // Return to the connect screen to switch servers / credentials.
324− // Keep the sessions list so a re-connect can refresh in place.
325− model.current_session_id = None;
326− model.current_session_title.clear();
327− model.messages.clear();
328− model.generating = false;
329− model.connected = false;
330− model.auth_required = false;
331 model.loading = false;
389 model.loading = false;
390+ match ok_body(result) {
391+ Ok(body) => {
392+ if let Some(s) = protocol::parse_session(&body) {
393+ let view = SessionView {
394+ id: s.id.clone(),
395+ title: display_title(&s.title),
396+ };
397+ if !model.sessions.iter().any(|e| e.id == view.id) {
398+ model.sessions.insert(0, view);
399+ }
400+ return render().and(Command::event(Event::SelectSession(s.id)));
401+ }
402+ model.error = Some("Malformed session response".to_string());
403+ }
404+ Err(e) => model.error = Some(e),
405+ }
332 render()
406 render()
333 }
407 }
334
408
335− Event::CreateSession => {
409+ Event::DeleteSession(id) => {
336− model.loading = true;
410+ model.sessions.retain(|s| s.id != id);
337− self.post(model, "/session", Vec::new())
411+ let mut cmd = self.delete(model, &format!("/session/{id}")).build().then_send(Event::SessionDeleted);
338− .build()
412+ if model.is_current(&id) {
339− .then_send(Event::SessionCreated)
413+ model.current_session_id = None;
414+ model.messages.clear();
415+ model.screen = Screen::Sessions;
416+ }
417+ cmd = render().and(cmd);
418+ cmd
340 }
419 }
341
420
342− Event::SessionCreated(result) => {
421+ Event::SessionDeleted(result) => {
343− model.loading = false;
422+ if let Err(e) = ok_body(result) {
344− match result {
423+ model.error = Some(e);
345− Ok(mut response) => {
346− let body = response.take_body().unwrap_or_default();
347− let id = parse_session_id(&body);
348− // Some servers echo the title in the created payload;
349− // fall back to "New session" if absent.
350− let title = extract_string(&body, "title")
351− .filter(|t| !t.is_empty())
352− .unwrap_or_else(|| "New session".to_string());
353− model.current_session_title = title.clone();
354− model.sessions.insert(
355− 0,
356− SessionSummary { id: id.clone(), title },
357− );
358− Command::event(Event::NavigateToChat(id))
359− }
360− Err(e) => {
361− model.error = Some(format!("Failed to create session: {e}"));
362− render()
363− }
364 }
424 }
425+ render()
365 }
426 }
366
427
428+ // ── Chat ────────────────────────────────────────────────────────
367 Event::LoadMessages(id) => {
429 Event::LoadMessages(id) => {
368− model.loading = true;
430+ render().and(
369− let path = format!("/session/{id}/message");
431+ self.get(model, &format!("/session/{id}/message"))
370− self.get(model, &path).build().then_send(Event::MessagesLoaded)
432+ .build()
433+ .then_send(move |result| Event::MessagesLoaded(id.clone(), result)),
434+ )
371 }
435 }
372
436
373− Event::MessagesLoaded(result) => {
437+ Event::MessagesLoaded(session_id, result) => {
438+ if !model.is_current(&session_id) {
439+ return render();
440+ }
374 model.loading = false;
441 model.loading = false;
375− model.generating = false;
442+ match ok_body(result) {
376− match result {
443+ Ok(body) => {
377− Ok(mut response) => {
444+ model.messages = protocol::parse_messages(&body).iter().map(message_from_wire).collect();
378− let body = response.take_body().unwrap_or_default();
445+ model.generating = model.messages.iter().any(|m| m.streaming);
379− model.messages = parse_messages(&body);
380− render()
381− }
382− Err(e) => {
383− model.error = Some(format!("Failed to load messages: {e}"));
384− render()
385 }
446 }
447+ Err(e) => model.error = Some(e),
386 }
448 }
449+ render()
450+ }
451+
452+ Event::DraftChanged(text) => {
453+ model.draft = text;
454+ render()
387 }
455 }
388
456
389 Event::SendMessage(text) => {
457 Event::SendMessage(text) => {
458+ let text = text.trim().to_string();
390 let Some(session_id) = model.current_session_id.clone() else {
459 let Some(session_id) = model.current_session_id.clone() else {
391 return render();
460 return render();
392 };
461 };
393− model.draft_message.clear();
462+ if text.is_empty() {
463+ return render();
464+ }
465+ model.local_seq += 1;
466+ let mut user = MsgState::new(format!("local-{}", model.local_seq), "user".to_string(), 0);
467+ user.status = MessageStatus::Pending;
468+ MsgState::upsert_part(&mut user.text_parts, "local", text.clone());
469+ model.messages.push(user);
470+ model.draft.clear();
394 model.generating = true;
471 model.generating = true;
395− let body = serde_json::json!({
472+ model.error = None;
396− "sessionID": session_id,
473+
397− "parts": [{ "type": "text", "text": text }]
474+ let body = serde_json::json!({ "parts": [{ "type": "text", "text": text }] });
398− })
475+ render().and(
399− .to_string()
476+ self.post_json(model, &format!("/session/{session_id}/prompt_async"), &body)
400− .into_bytes();
477+ .build()
401− let path = format!("/session/{session_id}/prompt_async");
478+ .then_send(Event::PromptSent),
402− self.post(model, &path, body)
479+ )
403− .build()
480+ }
404− .then_send(Event::MessageSent)
481+
405− }
482+ Event::PromptSent(result) => {
406−
483+ match ok_body(result) {
407− Event::MessageSent(result) => {
484+ Ok(_) => set_last_pending(model, MessageStatus::Sent),
408− match result {
409− Ok(_) => {
410− // Reload messages to pick up the assistant reply.
411− if let Some(session_id) = model.current_session_id.clone() {
412− Command::event(Event::LoadMessages(session_id))
413− } else {
414− model.generating = false;
415− render()
416− }
417− }
418 Err(e) => {
485 Err(e) => {
486+ set_last_pending(model, MessageStatus::Failed);
419 model.generating = false;
487 model.generating = false;
420− model.error = Some(format!("Failed to send message: {e}"));
488+ model.error = Some(e);
421− render()
422 }
489 }
423 }
490 }
491+ render()
492+ }
493+
494+ Event::CancelGeneration => {
495+ model.generating = false;
496+ match model.current_session_id.clone() {
497+ Some(id) => render().and(
498+ self.post_json(model, &format!("/session/{id}/abort"), &serde_json::json!({}))
499+ .build()
500+ .then_send(Event::Aborted),
501+ ),
502+ None => render(),
503+ }
424 }
504 }
425
505
426− Event::EventReceived(_data) => {
506+ Event::Aborted(_) => render(),
427− // SSE event — reload messages for the current session.
507+
428− if let Some(session_id) = model.current_session_id.clone() {
508+ // ── SSE ─────────────────────────────────────────────────────────
429− Command::event(Event::LoadMessages(session_id))
509+ Event::ServerEvent(json) => {
430− } else {
510+ if let Some(event) = protocol::parse_event(&json) {
431− render()
511+ apply_server_event(model, event);
432 }
512 }
513+ render()
433 }
514 }
434
515
435− Event::CrashLog(entry) => {
516+ // ── Navigation / misc ───────────────────────────────────────────
436− model.crash_logs.push(entry);
517+ Event::NavigateToSessions => {
437− self.render_with_crashes(model)
518+ model.screen = Screen::Sessions;
519+ model.current_session_id = None;
520+ model.messages.clear();
521+ model.generating = false;
522+ render().and(self.get(model, "/session").build().then_send(Event::SessionsLoaded))
523+ }
524+
525+ Event::NavigateToConnect => {
526+ model.screen = Screen::Connect;
527+ model.connected = false;
528+ model.sessions.clear();
529+ model.messages.clear();
530+ model.current_session_id = None;
531+ render()
438 }
532 }
439
533
440 Event::DismissError => {
534 Event::DismissError => {
441 model.error = None;
535 model.error = None;
442 render()
536 render()
443 }
537 }
444−
445− // ── Internal events (not type-generated, sent via then_send) ───
446− Event::HealthProbed(result) => handle_health_probed(self, model, result),
447 }
538 }
448 }
539 }
449
540
450− fn view(&self, model: &Self::Model) -> Self::ViewModel {
541+ fn view(&self, model: &Model) -> ViewModel {
451− let screen = if model.current_session_id.is_some() {
452− Screen::Chat
453− } else if model.connected {
454− Screen::Sessions
455− } else {
456− Screen::Connect
457− };
458−
459 ViewModel {
542 ViewModel {
460− screen,
543+ screen: model.screen.clone(),
461 server_url: model.server_url.clone(),
544 server_url: model.server_url.clone(),
462 username: model.username.clone(),
545 username: model.username.clone(),
463 password: model.password.clone(),
546 password: model.password.clone(),
@@ -465,398 +548,504 @@ impl App for OpencodeApp {
465 connected: model.connected,
548 connected: model.connected,
466 loading: model.loading,
549 loading: model.loading,
467 error: model.error.clone(),
550 error: model.error.clone(),
468− sessions: model
551+ sessions: model.sessions.clone(),
469− .sessions
470− .iter()
471− .map(|s| SessionView {
472− id: s.id.clone(),
473− title: s.title.clone(),
474− })
475− .collect(),
476 current_session_id: model.current_session_id.clone(),
552 current_session_id: model.current_session_id.clone(),
477 current_session_title: model.current_session_title.clone(),
553 current_session_title: model.current_session_title.clone(),
478− messages: model.messages.clone(),
554+ messages: model.messages.iter().map(MsgState::to_view).collect(),
479− draft_message: model.draft_message.clone(),
555+ draft: model.draft.clone(),
480 generating: model.generating,
556 generating: model.generating,
481− crash_log_count: model.crash_logs.len() as u32,
482− latest_crash_log: model.crash_logs.last().cloned(),
483 }
557 }
484 }
558 }
485}
559}
486
560
487−// ─── Basic-auth detection ──────────────────────────────────────────────────
561+impl OpencodeApp {
488−//
562+ fn on_health_probed(&self, model: &mut Model, result: HttpResult) -> Command<Effect, Event> {
489−// The opencode server uses HTTP Basic Auth when OPENCODE_SERVER_PASSWORD is set
563+ let has_creds = model.has_credentials();
490−// (username defaults to "opencode"). We detect this by probing /global/health
564+ match result {
491−// without credentials:
565+ Ok(response) => {
492−//
566+ let status = response.status().as_u16();
493−// - 200 → server is open; proceed to load sessions.
567+ if status == 401 {
494−// - 401 → server is behind basic auth; surface `auth_required` and wait for
568+ model.loading = false;
495−// the user to supply credentials. The user then re-issues Connect,
569+ if has_creds {
496−// which now attaches the Authorization header to the same probe.
570+ model.error = Some("Invalid credentials".to_string());
497−// A 200 on that retry flips `authed` and proceeds.
571+ } else {
498−// - Other non-2xx → surface as a connection error.
572+ model.auth_required = true;
499−// - Transport error → surface as a connection error.
573+ }
500−
574+ return render();
501−fn handle_health_probed(
502− app: &OpencodeApp,
503− model: &mut Model,
504− result: HttpResult<String>,
505−) -> Command<Effect, Event> {
506− let has_creds = !model.username.is_empty() || !model.password.is_empty();
507− match result {
508− Ok(response) => {
509− let status = response.status().as_u16();
510− if status == 401 { model.loading = false;
511− if has_creds {
512− // We sent credentials but the server still rejected them.
513− model.error = Some("Invalid credentials".to_string());
514− } else {
515− // No credentials were sent — server is behind basic auth.
516− // Surface the credential fields and wait for the user.
517− model.auth_required = true;
518 }
575 }
519− return render();
576+ if (200..300).contains(&status) {
520− }
577+ if has_creds {
521− if (200..300).contains(&status) {
578+ model.authed = true;
522− if has_creds {
579+ }
523− model.authed = true;
580+ model.connected = true;
581+ model.auth_required = false;
582+ model.error = None;
583+ model.screen = Screen::Sessions;
584+ model.loading = true;
585+ return render().and(self.get(model, "/session").build().then_send(Event::SessionsLoaded));
524 }
586 }
525− model.loading = true;
587+ model.loading = false;
526− return app
588+ model.error = Some(format!("Server returned status {status}"));
527− .get(model, "/session")
589+ render()
528− .build()
590+ }
529− .then_send(Event::SessionsLoaded);
591+ Err(e) => {
530− }
592+ model.loading = false;
531− // Other status codes — treat as connection error.
593+ model.error = Some(format!("Connection failed: {e}"));
532− model.loading = false;
594+ render()
533− model.error = Some(format!("Server returned status {status}"));
595+ }
534− render()
535− }
536− Err(e) => {
537− model.loading = false;
538− model.error = Some(format!("Connection failed: {e}"));
539− render()
540 }
596 }
541 }
597 }
542}
598}
543
599
544−// ─── JSON parsing (minimal, avoids pulling a JSON dep into the core) ───────
600+// ─── SSE application ─────────────────────────────────────────────────────────
545−
601+
546−fn parse_sessions(body: &str) -> Vec<SessionSummary> {
602+fn apply_server_event(model: &mut Model, event: ServerEvent) {
547− let mut sessions = Vec::new();
603+ match event {
548− let mut depth = 0i32;
604+ // Only assistant messages are created from the stream — the user's own
549− let mut start = 0usize;
605+ // message is already shown optimistically, so ignoring the server's copy
550− for (i, ch) in body.char_indices() {
606+ // avoids a duplicate bubble.
551− match ch {
607+ ServerEvent::MessageUpdated { properties } => {
552− '{' => {
608+ let info = properties.info;
553− if depth == 0 {
609+ if info.role != "assistant" || !model.is_current(&info.session_id) {
554− start = i;
610+ return;
611+ }
612+ let streaming = info.time.completed.is_none() && info.error.is_none();
613+ if let Some(msg) = model.message_mut(&info.id) {
614+ msg.streaming = streaming;
615+ if msg.time == 0 {
616+ msg.time = info.time.created;
555 }
617 }
556− depth += 1;
618+ } else {
557− }
619+ let mut msg = MsgState::new(info.id.clone(), "assistant".to_string(), info.time.created);
558− '}' => {
620+ msg.streaming = streaming;
559− depth -= 1;
621+ model.messages.push(msg);
560− if depth == 0 {
622+ }
561− let obj = &body[start..=i];
623+ if let Some(err) = info.error {
562− let id = extract_string(obj, "id").unwrap_or_default();
624+ model.error = Some(err.message());
563− let title = extract_string(obj, "title").unwrap_or_default();
625+ model.generating = false;
564− if !id.is_empty() {
626+ }
565− sessions.push(SessionSummary {
627+ }
566− id,
628+
567− title: if title.is_empty() {
629+ // Apply only to a message we already track (an assistant message from the
568− "Untitled".to_string()
630+ // event above). Parts for unknown ids are ignored — see module docs.
569− } else {
631+ ServerEvent::MessagePartUpdated { properties } => {
570− title
632+ let part = properties.part;
571− },
633+ let delta = properties.delta;
572− });
634+ let msg_id = part.message_id().to_string();
635+ let Some(msg) = model.message_mut(&msg_id) else {
636+ return;
637+ };
638+ match part {
639+ WirePart::Text { id, text, synthetic, .. } => {
640+ if synthetic {
641+ return;
573 }
642 }
643+ let value = pick_text(text, &delta, &msg.text_parts, &id);
644+ MsgState::upsert_part(&mut msg.text_parts, &id, value);
645+ }
646+ WirePart::Reasoning { id, text, .. } => {
647+ let value = pick_text(text, &delta, &msg.reasoning_parts, &id);
648+ MsgState::upsert_part(&mut msg.reasoning_parts, &id, value);
649+ }
650+ WirePart::Tool { id, tool, state, .. } => {
651+ let sv = protocol::tool_state_view(&state);
652+ msg.upsert_tool(&id, ToolView { name: tool, status: sv.status, title: sv.title });
653+ }
654+ WirePart::Other => {}
655+ }
656+ }
657+
658+ ServerEvent::MessagePartRemoved { properties } => {
659+ if let Some(msg) = model.message_mut(&properties.message_id) {
660+ msg.remove_part(&properties.part_id);
661+ }
662+ }
663+
664+ ServerEvent::MessageRemoved { properties } => {
665+ model.messages.retain(|m| m.id != properties.message_id);
666+ }
667+
668+ ServerEvent::SessionIdle { properties } => {
669+ if model.is_current(&properties.session_id) {
670+ model.generating = false;
671+ for m in &mut model.messages {
672+ m.streaming = false;
574 }
673 }
575 }
674 }
576− _ => {}
577 }
675 }
676+
677+ ServerEvent::SessionError { properties } => {
678+ let scoped = properties.session_id.as_deref().map_or(true, |s| model.is_current(s));
679+ if scoped {
680+ if let Some(err) = properties.error {
681+ model.error = Some(err.message());
682+ }
683+ model.generating = false;
684+ }
685+ }
686+
687+ ServerEvent::SessionCreated { properties } | ServerEvent::SessionUpdated { properties } => {
688+ let s = properties.info;
689+ let view = SessionView { id: s.id.clone(), title: display_title(&s.title) };
690+ if let Some(existing) = model.sessions.iter_mut().find(|e| e.id == view.id) {
691+ existing.title = view.title.clone();
692+ } else {
693+ model.sessions.insert(0, view);
694+ }
695+ if model.is_current(&s.id) {
696+ model.current_session_title = display_title(&s.title);
697+ }
698+ }
699+
700+ ServerEvent::SessionDeleted { properties } => {
701+ let id = properties.session_id.or(properties.info.map(|i| i.id));
702+ if let Some(id) = id {
703+ model.sessions.retain(|s| s.id != id);
704+ if model.is_current(&id) {
705+ model.current_session_id = None;
706+ model.messages.clear();
707+ model.screen = Screen::Sessions;
708+ }
709+ }
710+ }
711+
712+ ServerEvent::Other => {}
578 }
713 }
579− sessions
580}
714}
581
715
582−fn parse_session_id(body: &str) -> String {
716+// ─── Helpers ─────────────────────────────────────────────────────────────────
583− extract_string(body, "id").unwrap_or_default()
717+
718+/// `part.text` is the full current text when present; otherwise fall back to
719+/// accumulating the incremental `delta` onto whatever we already have.
720+fn pick_text(text: String, delta: &Option<String>, existing: &[(String, String)], part_id: &str) -> String {
721+ if !text.is_empty() {
722+ return text;
723+ }
724+ let prior = existing.iter().find(|(pid, _)| pid == part_id).map(|(_, t)| t.clone()).unwrap_or_default();
725+ match delta {
726+ Some(d) => format!("{prior}{d}"),
727+ None => prior,
728+ }
584}
729}
585
730
586−fn parse_messages(body: &str) -> Vec<MessageView> {
731+fn message_from_wire(env: &WireMessageEnvelope) -> MsgState {
587− let mut messages = Vec::new();
732+ let info = &env.info;
588− let mut depth = 0i32;
733+ let mut msg = MsgState::new(info.id.clone(), info.role.clone(), info.time.created);
589− let mut start = 0usize;
734+ msg.streaming = info.role == "assistant" && info.time.completed.is_none() && info.error.is_none();
590− let mut i = 0usize;
735+ for part in &env.parts {
591− let bytes = body.as_bytes();
736+ match part {
592− while i < body.len() {
737+ WirePart::Text { id, text, synthetic, .. } => {
593− let ch = bytes[i] as char;
738+ if !synthetic {
594− match ch {
739+ MsgState::upsert_part(&mut msg.text_parts, id, text.clone());
595− '{' => {
596− if depth == 0 {
597− start = i;
598− }
599− depth += 1;
600− }
601− '}' => {
602− depth -= 1;
603− if depth == 0 {
604− let obj = &body[start..=i];
605− let id = extract_string(obj, "id").unwrap_or_default();
606− let role = extract_string(obj, "role").unwrap_or_default();
607− let time = extract_number(obj, "created").unwrap_or(0);
608− if !id.is_empty() {
609− let text = extract_message_text(obj);
610− messages.push(MessageView { id, role, text, time });
611− }
612 }
740 }
613 }
741 }
614− _ => {}
742+ WirePart::Reasoning { id, text, .. } => {
743+ MsgState::upsert_part(&mut msg.reasoning_parts, id, text.clone());
744+ }
745+ WirePart::Tool { id, tool, state, .. } => {
746+ let sv = protocol::tool_state_view(state);
747+ msg.upsert_tool(id, ToolView { name: tool.clone(), status: sv.status, title: sv.title });
748+ }
749+ WirePart::Other => {}
615 }
750 }
616− i += 1;
617 }
751 }
618− messages
752+ msg
619}
753}
620
754
621−/// Extract the text from a message part. opencode messages nest the user/assistant
755+fn set_last_pending(model: &mut Model, status: MessageStatus) {
622−/// text inside a `parts` array; we do a shallow scan for `"text":"..."` after the
756+ if let Some(msg) = model.messages.iter_mut().rev().find(|m| m.status == MessageStatus::Pending) {
623−/// first `"parts"` key.
757+ msg.status = status;
624−fn extract_message_text(obj: &str) -> String {
625− if let Some(parts_idx) = obj.find("\"parts\"") {
626− let rest = &obj[parts_idx..];
627− if let Some(text) = extract_string(rest, "text") {
628− return text;
629− }
630 }
758 }
631− extract_string(obj, "text").unwrap_or_default()
632}
759}
633
760
634−fn extract_string(json: &str, key: &str) -> Option<String> {
761+/// Trim whitespace and any trailing `/` so paths concatenate cleanly, and
635− let pattern = format!("\"{key}\"");
762+/// default to an `http://` scheme when the user didn't type one (e.g.
636− let idx = json.find(&pattern)?;
763+/// "192.168.1.10:4096") — otherwise the shell's URL parser rejects it.
637− let rest = &json[idx + pattern.len()..];
764+fn normalize_url(url: &str) -> String {
638− let colon = rest.find(':')?;
765+ let trimmed = url.trim().trim_end_matches('/');
639− let rest = &rest[colon + 1..];
766+ if trimmed.is_empty() {
640− let quote = rest.find('"')?;
767+ String::new()
641− let rest = &rest[quote + 1..];
768+ } else if trimmed.contains("://") {
642− let end = rest.find('"')?;
769+ trimmed.to_string()
643− Some(rest[..end].to_string())
770+ } else {
771+ format!("http://{trimmed}")
772+ }
644}
773}
645
774
646−fn extract_number(json: &str, key: &str) -> Option<u64> {
775+fn display_title(title: &str) -> String {
647− let pattern = format!("\"{key}\"");
776+ let t = title.trim();
648− let idx = json.find(&pattern)?;
777+ if t.is_empty() {
649− let rest = &json[idx + pattern.len()..];
778+ "Untitled".to_string()
650− let colon = rest.find(':')?;
779+ } else {
651− let rest = &rest[colon + 1..].trim_start();
780+ t.to_string()
652− let end = rest
781+ }
653− .find(|c: char| !c.is_ascii_digit())
782+}
654− .unwrap_or(rest.len());
783+
655− rest[..end].parse().ok()
784+/// Reduce an [`HttpResult`] to `Ok(body)` for 2xx, or `Err(message)` otherwise.
785+fn ok_body(result: HttpResult) -> Result<String, String> {
786+ match result {
787+ Ok(mut response) => {
788+ let status = response.status().as_u16();
789+ if (200..300).contains(&status) {
790+ Ok(response.take_body().unwrap_or_default())
791+ } else {
792+ Err(format!("Server returned status {status}"))
793+ }
794+ }
795+ Err(e) => Err(format!("Request failed: {e}")),
796+ }
656}
797}
657
798
658−// ─── Tests ─────────────────────────────────────────────────────────────────
799+// ─── Tests ───────────────────────────────────────────────────────────────────
659
800
660#[cfg(test)]
801#[cfg(test)]
661−mod test {
802+mod tests {
662 use super::*;
803 use super::*;
663
804
805+ fn app() -> OpencodeApp {
806+ OpencodeApp::default()
807+ }
808+
809+ /// Put the model into a connected Chat view for the given session.
810+ fn in_chat(session_id: &str) -> Model {
811+ let mut model = Model::default();
812+ model.server_url = "http://localhost:4096".to_string();
813+ model.connected = true;
814+ model.screen = Screen::Chat;
815+ model.current_session_id = Some(session_id.to_string());
816+ model
817+ }
818+
819+ fn feed(app: &OpencodeApp, model: &mut Model, json: serde_json::Value) {
820+ let _ = app.update(Event::ServerEvent(json.to_string()), model);
821+ }
822+
664 #[test]
823 #[test]
665− fn start_does_not_reset_server_url() {
824+ fn server_url_is_kept_raw_while_typing() {
666− // Start no longer overwrites server_url — the shell restores the
825+ let app = app();
667− // persisted value via ServerUrlChanged so the user's last server
668− // survives a relaunch.
669− let app = OpencodeApp;
670 let mut model = Model::default();
826 let mut model = Model::default();
671− model.server_url = "http://10.0.0.1:4096".to_string();
827+ // Mid-scheme input must survive verbatim — normalizing per keystroke
672− app.update(Event::Start, &mut model).expect_only_render();
828+ // would eat the "://" the user is typing and make the field unusable.
673− assert_eq!(model.server_url, "http://10.0.0.1:4096");
829+ let _ = app.update(Event::ServerUrlChanged("http:/".into()), &mut model);
830+ assert_eq!(app.view(&model).server_url, "http:/");
674 }
831 }
675
832
676 #[test]
833 #[test]
677− fn server_url_change_updates_model() {
834+ fn connect_normalizes_scheme_less_url() {
678− let app = OpencodeApp;
835+ let app = app();
679 let mut model = Model::default();
836 let mut model = Model::default();
680− app.update(Event::Start, &mut model);
837+ // A scheme-less host (what a user often types) must gain http:// on
681− app.update(
838+ // connect, or the shell's URL parser throws and the attempt crashes.
682− Event::ServerUrlChanged("http://10.0.0.1:4096".to_string()),
839+ let _ = app.update(Event::ServerUrlChanged("192.168.1.10:4096".into()), &mut model);
683− &mut model,
840+ assert_eq!(app.view(&model).server_url, "192.168.1.10:4096");
684− )
841+ let _ = app.update(Event::Connect, &mut model);
685− .expect_only_render();
842+ assert_eq!(app.view(&model).server_url, "http://192.168.1.10:4096");
686− assert_eq!(model.server_url, "http://10.0.0.1:4096");
687 }
843 }
688
844
689 #[test]
845 #[test]
690− fn connect_emits_http_effect() {
846+ fn connect_trims_and_keeps_explicit_scheme() {
691− let app = OpencodeApp;
847+ let app = app();
692 let mut model = Model::default();
848 let mut model = Model::default();
693− model.server_url = "http://localhost:4096".to_string();
849+ let _ = app.update(Event::ServerUrlChanged(" https://host:4096/ ".into()), &mut model);
694− app.update(Event::Start, &mut model);
850+ let _ = app.update(Event::Connect, &mut model);
695− let mut cmd = app.update(Event::Connect, &mut model);
851+ assert_eq!(app.view(&model).server_url, "https://host:4096");
696− assert!(cmd.effects().any(|e| matches!(e, Effect::Http(_))));
697− assert!(model.loading);
698 }
852 }
699
853
700 #[test]
854 #[test]
701− fn parse_sessions_extracts_id_and_title() {
855+ fn connect_requires_a_url() {
702− let json = r#"[{"id":"abc123","title":"My Session"},{"id":"def456","title":"Test"}]"#;
856+ let app = app();
703− let sessions = parse_sessions(json);
857+ let mut model = Model::default();
704− assert_eq!(sessions.len(), 2);
858+ let _ = app.update(Event::Connect, &mut model);
705− assert_eq!(sessions[0].id, "abc123");
859+ assert_eq!(app.view(&model).error.as_deref(), Some("Enter a server URL"));
706− assert_eq!(sessions[0].title, "My Session");
707− assert_eq!(sessions[1].id, "def456");
708 }
860 }
709
861
710 #[test]
862 #[test]
711− fn parse_session_id_extracts_id() {
863+ fn sending_adds_optimistic_user_message_and_sets_generating() {
712− let json = r#"{"id":"xyz789","title":"New"}"#;
864+ let app = app();
713− let id = parse_session_id(json);
865+ let mut model = in_chat("ses_1");
714− assert_eq!(id, "xyz789");
866+ let _ = app.update(Event::DraftChanged("hello there".into()), &mut model);
867+ let _ = app.update(Event::SendMessage("hello there".into()), &mut model);
868+
869+ let view = app.view(&model);
870+ assert!(view.generating);
871+ assert!(view.draft.is_empty());
872+ assert_eq!(view.messages.len(), 1);
873+ assert_eq!(view.messages[0].role, "user");
874+ assert_eq!(view.messages[0].text, "hello there");
875+ assert_eq!(view.messages[0].status, MessageStatus::Pending);
715 }
876 }
716
877
717 #[test]
878 #[test]
718− fn extract_string_finds_nested_keys() {
879+ fn empty_send_is_ignored() {
719− let json = r#"{"a":"b","id":"target","c":"d"}"#;
880+ let app = app();
720− assert_eq!(extract_string(json, "id"), Some("target".to_string()));
881+ let mut model = in_chat("ses_1");
721− assert_eq!(extract_string(json, "missing"), None);
882+ let _ = app.update(Event::SendMessage(" ".into()), &mut model);
883+ assert!(app.view(&model).messages.is_empty());
884+ assert!(!app.view(&model).generating);
722 }
885 }
723
886
724 #[test]
887 #[test]
725− fn extract_number_parses_values() {
888+ fn assistant_reply_streams_in_from_sse() {
726− let json = r#"{"created":1234567890}"#;
889+ let app = app();
727− assert_eq!(extract_number(json, "created"), Some(1234567890));
890+ let mut model = in_chat("ses_1");
891+
892+ // Assistant message shell arrives first.
893+ feed(&app, &mut model, serde_json::json!({
894+ "type": "message.updated",
895+ "properties": { "info": {
896+ "id": "msg_a", "role": "assistant", "sessionID": "ses_1",
897+ "time": { "created": 100 }
898+ }}
899+ }));
900+ assert_eq!(app.view(&model).messages.len(), 1);
901+ assert!(app.view(&model).messages[0].streaming);
902+
903+ // Two text deltas for the same part accumulate into full text.
904+ feed(&app, &mut model, serde_json::json!({
905+ "type": "message.part.updated",
906+ "properties": { "part": {
907+ "id": "prt_1", "messageID": "msg_a", "sessionID": "ses_1",
908+ "type": "text", "text": "Hello"
909+ }}
910+ }));
911+ feed(&app, &mut model, serde_json::json!({
912+ "type": "message.part.updated",
913+ "properties": { "part": {
914+ "id": "prt_1", "messageID": "msg_a", "sessionID": "ses_1",
915+ "type": "text", "text": "Hello, world"
916+ }}
917+ }));
918+
919+ let view = app.view(&model);
920+ assert_eq!(view.messages[0].role, "assistant");
921+ assert_eq!(view.messages[0].text, "Hello, world");
728 }
922 }
729
923
730 #[test]
924 #[test]
731− fn navigate_to_sessions_clears_state() {
925+ fn text_delta_accumulates_when_full_text_absent() {
732− let app = OpencodeApp;
926+ let app = app();
733− let mut model = Model::default();
927+ let mut model = in_chat("ses_1");
734− model.current_session_id = Some("test".to_string());
928+ feed(&app, &mut model, serde_json::json!({
735− model.current_session_title = "Test".to_string();
929+ "type": "message.updated",
736− model.generating = true;
930+ "properties": { "info": { "id": "msg_a", "role": "assistant", "sessionID": "ses_1", "time": {"created": 1}}}
737− model.messages.push(MessageView {
931+ }));
738− id: "m1".to_string(),
932+ for delta in ["Wor", "ld"] {
739− role: "user".to_string(),
933+ feed(&app, &mut model, serde_json::json!({
740− text: "hello".to_string(),
934+ "type": "message.part.updated",
741− time: 0,
935+ "properties": {
742− });
936+ "part": { "id": "p", "messageID": "msg_a", "sessionID": "ses_1", "type": "text", "text": "" },
743− app.update(Event::NavigateToSessions, &mut model);
937+ "delta": delta
744− assert!(model.current_session_id.is_none());
938+ }
745− assert!(model.current_session_title.is_empty());
939+ }));
746− assert!(model.messages.is_empty());
940+ }
747− assert!(!model.generating);
941+ assert_eq!(app.view(&model).messages[0].text, "World");
748 }
942 }
749
943
750 #[test]
944 #[test]
751− fn select_session_records_title_from_sessions_list() {
945+ fn user_message_from_sse_is_not_duplicated() {
752− let app = OpencodeApp;
946+ let app = app();
753− let mut model = Model::default();
947+ let mut model = in_chat("ses_1");
754− model.sessions = vec![
948+ let _ = app.update(Event::SendMessage("hi".into()), &mut model);
755− SessionSummary { id: "s1".to_string(), title: "First".to_string() },
949+ // Server echoes the user message on the stream — must be ignored.
756− SessionSummary { id: "s2".to_string(), title: "Second".to_string() },
950+ feed(&app, &mut model, serde_json::json!({
757− ];
951+ "type": "message.updated",
758− app.update(Event::SelectSession("s2".to_string()), &mut model);
952+ "properties": { "info": { "id": "msg_user", "role": "user", "sessionID": "ses_1", "time": {"created": 5}}}
759− assert_eq!(model.current_session_id.as_deref(), Some("s2"));
953+ }));
760− assert_eq!(model.current_session_title, "Second");
954+ let users = app.view(&model).messages.iter().filter(|m| m.role == "user").count();
761− let view = app.view(&model);
955+ assert_eq!(users, 1);
762− assert_eq!(view.current_session_title, "Second");
763 }
956 }
764
957
765 #[test]
958 #[test]
766− fn send_message_sets_generating_until_messages_loaded() {
959+ fn session_idle_clears_generating() {
767− let app = OpencodeApp;
960+ let app = app();
768− let mut model = Model::default();
961+ let mut model = in_chat("ses_1");
769− model.server_url = "http://localhost:4096".to_string();
962+ let _ = app.update(Event::SendMessage("hi".into()), &mut model);
770− model.current_session_id = Some("s1".to_string());
963+ assert!(app.view(&model).generating);
771− app.update(Event::SendMessage("hello".to_string()), &mut model);
964+ feed(&app, &mut model, serde_json::json!({
772− assert!(model.generating);
965+ "type": "session.idle", "properties": { "sessionID": "ses_1" }
773− // Simulate the MessagesLoaded internal event clearing it.
966+ }));
774− let ok_resp = crux_http::testing::ResponseBuilder::ok().body("[]".to_string()).build();
967+ assert!(!app.view(&model).generating);
775− let result: HttpResult<String> = Ok(ok_resp);
776− app.update(Event::MessagesLoaded(result), &mut model);
777− assert!(!model.generating);
778 }
968 }
779
969
780 #[test]
970 #[test]
781− fn failed_send_clears_generating() {
971+ fn idle_for_other_session_is_ignored() {
782− let app = OpencodeApp;
972+ let app = app();
783− let mut model = Model::default();
973+ let mut model = in_chat("ses_1");
784− model.server_url = "http://localhost:4096".to_string();
974+ let _ = app.update(Event::SendMessage("hi".into()), &mut model);
785− model.current_session_id = Some("s1".to_string());
975+ feed(&app, &mut model, serde_json::json!({
786− app.update(Event::SendMessage("hello".to_string()), &mut model);
976+ "type": "session.idle", "properties": { "sessionID": "ses_other" }
787− assert!(model.generating);
977+ }));
788− let err = crux_http::HttpError::Io("boom".to_string());
978+ assert!(app.view(&model).generating);
789− app.update(Event::MessageSent(Err(err)), &mut model);
790− assert!(!model.generating);
791− assert!(model.error.is_some());
792 }
979 }
793
980
794 #[test]
981 #[test]
795− fn auth_header_built_from_credentials() {
982+ fn reasoning_and_tool_parts_are_surfaced() {
796− let app = OpencodeApp;
983+ let app = app();
797− let mut model = Model::default();
984+ let mut model = in_chat("ses_1");
798− model.server_url = "http://localhost:4096".to_string();
985+ feed(&app, &mut model, serde_json::json!({
799− model.username = "opencode".to_string();
986+ "type": "message.updated",
800− model.password = "secret".to_string();
987+ "properties": { "info": { "id": "m", "role": "assistant", "sessionID": "ses_1", "time": {"created": 1}}}
801− // Verify the base64 encoding matches RFC 7617.
988+ }));
802− let creds = format!("{}:{}", model.username, model.password);
989+ feed(&app, &mut model, serde_json::json!({
803− let encoded = base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
990+ "type": "message.part.updated",
804− assert_eq!(encoded, "b3BlbmNvZGU6c2VjcmV0");
991+ "properties": { "part": { "id": "r", "messageID": "m", "type": "reasoning", "text": "thinking..." }}
805− // Building a request should not panic.
992+ }));
806− let _ = app.get(&model, "/global/health");
993+ feed(&app, &mut model, serde_json::json!({
994+ "type": "message.part.updated",
995+ "properties": { "part": {
996+ "id": "t", "messageID": "m", "type": "tool", "tool": "bash",
997+ "state": { "status": "completed", "title": "ls -la" }
998+ }}
999+ }));
1000+ let msg = &app.view(&model).messages[0];
1001+ assert_eq!(msg.reasoning.as_deref(), Some("thinking..."));
1002+ assert_eq!(msg.tools.len(), 1);
1003+ assert_eq!(msg.tools[0].name, "bash");
1004+ assert_eq!(msg.tools[0].status, "completed");
1005+ assert_eq!(msg.tools[0].title.as_deref(), Some("ls -la"));
807 }
1006 }
808
1007
809 #[test]
1008 #[test]
810− fn crash_log_event_accumulates() {
1009+ fn session_created_event_updates_list() {
811− let app = OpencodeApp;
1010+ let app = app();
812− let mut model = Model::default();
1011+ let mut model = in_chat("ses_1");
813− app.update(Event::CrashLog("boom".to_string()), &mut model);
1012+ feed(&app, &mut model, serde_json::json!({
814− assert_eq!(model.crash_logs.len(), 1);
1013+ "type": "session.created",
815− let view = app.view(&model);
1014+ "properties": { "info": { "id": "ses_new", "title": "Fresh" }}
816− assert_eq!(view.crash_log_count, 1);
1015+ }));
817− assert_eq!(view.latest_crash_log.as_deref(), Some("boom"));
1016+ assert!(app.view(&model).sessions.iter().any(|s| s.id == "ses_new" && s.title == "Fresh"));
818 }
1017 }
819
1018
820− /// Verify that the bincode discriminant indices the shell sends match
821− /// the Rust enum variant positions — the type generator skips
822− /// `#[facet(skip)]` variants and renumbers the remaining ones, so the
823− /// shell's index 7 (SelectSession) must land on Rust's SelectSession,
824− /// not on a skipped variant.
825 #[test]
1019 #[test]
826− fn event_discriminants_match_generated_indices() {
1020+ fn unknown_event_types_are_ignored() {
827− // The generated Kotlin Event enum (see generated/.../Core.kt) maps:
1021+ let app = app();
828− // 0=Start, 1=ServerUrlChanged, 2=UsernameChanged, 3=PasswordChanged,
1022+ let mut model = in_chat("ses_1");
829− // 4=Connect, 5=CancelAuth, 6=LoadSessions, 7=SelectSession,
1023+ feed(&app, &mut model, serde_json::json!({
830− // 8=CreateSession, 9=LoadMessages, 10=SendMessage, 11=EventReceived,
1024+ "type": "pty.created", "properties": { "whatever": true }
831− // 12=NavigateToChat, 13=NavigateToSessions, 14=NavigateToConnect,
1025+ }));
832− // 15=DismissError
1026+ feed(&app, &mut model, serde_json::json!({ "type": "totally.new.event" }));
833− //
1027+ // No panic, no state change.
834− // Serialize each Rust variant and check the leading u32 index.
1028+ assert!(app.view(&model).messages.is_empty());
835− let cases: &[(Event, u32)] = &[
1029+ }
836− (Event::Start, 0),
1030+
837− (Event::ServerUrlChanged(String::new()), 1),
1031+ #[test]
838− (Event::UsernameChanged(String::new()), 2),
1032+ fn messages_loaded_parses_info_and_parts() {
839− (Event::PasswordChanged(String::new()), 3),
1033+ let app = app();
840− (Event::Connect, 4),
1034+ let mut model = in_chat("ses_1");
841− (Event::CancelAuth, 5),
1035+ let body = serde_json::json!([
842− (Event::LoadSessions, 6),
1036+ { "info": { "id": "m1", "role": "user", "sessionID": "ses_1", "time": {"created": 1} },
843− (Event::SelectSession(String::new()), 7),
1037+ "parts": [{ "id": "p1", "type": "text", "text": "Question?" }] },
844− (Event::CreateSession, 8),
1038+ { "info": { "id": "m2", "role": "assistant", "sessionID": "ses_1", "time": {"created": 2, "completed": 3} },
845− (Event::LoadMessages(String::new()), 9),
1039+ "parts": [{ "id": "p2", "type": "text", "text": "Answer." }] }
846− (Event::SendMessage(String::new()), 10),
1040+ ]).to_string();
847− (Event::EventReceived(String::new()), 11),
1041+ let result: HttpResult = Ok(crux_http::testing::ResponseBuilder::ok().body(body).build());
848− (Event::NavigateToChat(String::new()), 12),
1042+ let _ = app.update(Event::MessagesLoaded("ses_1".into(), result), &mut model);
849− (Event::NavigateToSessions, 13),
1043+
850− (Event::NavigateToConnect, 14),
1044+ let view = app.view(&model);
851− (Event::DismissError, 15),
1045+ assert_eq!(view.messages.len(), 2);
852− ];
1046+ assert_eq!(view.messages[0].text, "Question?");
853− for (event, expected) in cases {
1047+ assert_eq!(view.messages[1].text, "Answer.");
854− let bytes = bincode::serialize(event).unwrap();
1048+ assert!(!view.messages[1].streaming);
855− let idx = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
1049+ assert!(!view.generating);
856− assert_eq!(
857− idx, *expected,
858− "Event discriminant mismatch for {event:?}: got {idx}, expected {expected}"
859− );
860− }
861 }
1050 }
862}
1051}
shared/src/bin/codegen.rs+27−32
@@ -1,40 +1,35 @@
1−use std::path::PathBuf;
1+//! Crux type-generation for the shared domain (built with `--features typegen`).
2−
2+//!
3−use clap::{Parser, ValueEnum};
3+//! Demonstrates the Crux type-sharing pipeline: the core's view types are the
4−use crux_core::type_generation::facet::{Config, TypeRegistry};
4+//! single source of truth, and this binary emits matching JVM type definitions
5−use shared::OpencodeApp;
5+//! for the shell to consume across an FFI boundary. In this NDK-less build the
6−
6+//! Android shell hand-mirrors these types (see `app/.../core/ViewModel.kt`);
7−#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
7+//! wiring a real `.so` would have it consume the generated output instead.
8−enum Language {
8+//!
9− Kotlin,
9+//! Run: `cd shared && cargo run --features typegen --bin codegen`
10−}
10+//! Output: `generated/` (JVM/Java sources + the bincode serde runtime).
11
11
12−#[derive(Parser)]
12+use std::path::PathBuf;
13−#[command(version, about, long_about = None)]
14−struct Args {
15− #[arg(short, long, value_enum)]
16− language: Language,
17− #[arg(short, long)]
18− output_dir: PathBuf,
19−}
20
13
21−fn main() -> anyhow::Result<()> {
14+use anyhow::Result;
22− let args = Args::parse();
15+use crux_core::typegen::TypeGen;
16+use shared::{MessageStatus, MessageView, Screen, SessionView, ToolView, ViewModel};
23
17
24− let typegen_app = TypeRegistry::new()
18+fn main() -> Result<()> {
25− .register_app::<OpencodeApp>()?
19+ let mut gen = TypeGen::new();
26− .build()?;
27
20
28− let name = match args.language {
21+ // Register leaf types before the aggregates that reference them.
29− Language::Kotlin => "soy.iko.opencode.core",
22+ gen.register_type::<Screen>()?;
30− };
23+ gen.register_type::<MessageStatus>()?;
31− let config = Config::builder(name, &args.output_dir).build();
24+ gen.register_type::<ToolView>()?;
25+ gen.register_type::<SessionView>()?;
26+ gen.register_type::<MessageView>()?;
27+ gen.register_type::<ViewModel>()?;
32
28
33− match args.language {
29+ let out = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../generated");
34− Language::Kotlin => {
30+ std::fs::create_dir_all(&out)?;
35− typegen_app.kotlin(&config)?;
31+ gen.java("soy.iko.opencode.shared", &out)?;
36− }
37− }
38
32
33+ println!("Generated shared JVM types into {}", out.display());
39 Ok(())
34 Ok(())
40}
35}
shared/src/ffi.rsdeleted−53
@@ -1,53 +0,0 @@
1−use crux_core::{
2− Core,
3− bridge::{Bridge, EffectId},
4−};
5−
6−use crate::OpencodeApp;
7−
8−pub struct CoreFfi {
9− core: Bridge<OpencodeApp>,
10−}
11−
12−impl Default for CoreFfi {
13− fn default() -> Self {
14− Self::new()
15− }
16−}
17−
18−#[boltffi::export]
19−impl CoreFfi {
20− #[must_use]
21− pub fn new() -> Self {
22− Self {
23− core: Bridge::new(Core::new()),
24− }
25− }
26−
27− #[must_use]
28− pub fn update(&self, data: &[u8]) -> Vec<u8> {
29− let mut effects = Vec::new();
30− match self.core.update(data, &mut effects) {
31− Ok(()) => effects,
32− Err(e) => panic!("{e}"),
33− }
34− }
35−
36− #[must_use]
37− pub fn resolve(&self, id: u32, data: &[u8]) -> Vec<u8> {
38− let mut effects = Vec::new();
39− match self.core.resolve(EffectId(id), data, &mut effects) {
40− Ok(()) => effects,
41− Err(e) => panic!("{e}"),
42− }
43− }
44−
45− #[must_use]
46− pub fn view(&self) -> Vec<u8> {
47− let mut view_model = Vec::new();
48− match self.core.view(&mut view_model) {
49− Ok(()) => view_model,
50− Err(e) => panic!("{e}"),
51− }
52− }
53−}
shared/src/lib.rs+13−2
@@ -1,6 +1,17 @@
1−#![allow(clippy::used_underscore_items)]
1+//! Crux core for the opencode Android client.
2+//!
3+//! The core owns all state and logic (connect/auth, session list, chat, and the
4+//! streaming of assistant replies from the SSE event stream). The platform shell
5+//! (Android / Jetpack Compose) is a thin driver: it renders [`ViewModel`], turns
6+//! user actions into [`Event`]s, performs the effects the core asks for (HTTP
7+//! requests, and — outside the core — the `/event` SSE subscription), and feeds
8+//! server-sent events back in as [`Event::ServerEvent`].
9+//!
10+//! Because HTTP request/response is the only network capability Crux models,
11+//! the long-lived SSE connection lives in the shell; each decoded event is
12+//! handed to the core verbatim as a JSON string.
2
13
3mod app;
14mod app;
4−pub mod ffi;
15+mod protocol;
5
16
6pub use app::*;
17pub use app::*;
shared/src/protocol.rsnew file+248
@@ -0,0 +1,248 @@
1+//! Wire types for the opencode HTTP + SSE API.
2+//!
3+//! These mirror the JSON shapes the opencode server emits (`sst/opencode`).
4+//! They are deliberately lenient: every unknown field is ignored and every
5+//! discriminated union has a catch-all `Other` arm so that new server versions
6+//! (which add event / part / tool-state variants over time) never break the
7+//! stream parser.
8+
9+use serde::Deserialize;
10+
11+// ─── Sessions ────────────────────────────────────────────────────────────────
12+
13+#[derive(Deserialize, Debug, Clone)]
14+pub struct WireSession {
15+ pub id: String,
16+ #[serde(default)]
17+ pub title: String,
18+}
19+
20+// ─── Messages ────────────────────────────────────────────────────────────────
21+
22+/// One element of `GET /session/{id}/message`: `{ info, parts }`.
23+#[derive(Deserialize, Debug)]
24+pub struct WireMessageEnvelope {
25+ pub info: WireMessageInfo,
26+ #[serde(default)]
27+ pub parts: Vec<WirePart>,
28+}
29+
30+#[derive(Deserialize, Debug, Clone)]
31+pub struct WireMessageInfo {
32+ pub id: String,
33+ #[serde(default)]
34+ pub role: String,
35+ #[serde(default, rename = "sessionID")]
36+ pub session_id: String,
37+ #[serde(default)]
38+ pub time: WireTime,
39+ #[serde(default)]
40+ pub error: Option<WireError>,
41+}
42+
43+#[derive(Deserialize, Debug, Clone, Default)]
44+pub struct WireTime {
45+ #[serde(default)]
46+ pub created: u64,
47+ /// Present once an assistant message has finished generating.
48+ #[serde(default)]
49+ pub completed: Option<u64>,
50+}
51+
52+/// Message / part content. Only the variants a chat UI renders are modelled;
53+/// everything else (`file`, `agent`, `step-start`, `step-finish`, `snapshot`,
54+/// `patch`, …) falls through to `Other`.
55+#[derive(Deserialize, Debug, Clone)]
56+#[serde(tag = "type", rename_all = "lowercase")]
57+pub enum WirePart {
58+ Text {
59+ #[serde(default)]
60+ id: String,
61+ #[serde(default, rename = "messageID")]
62+ message_id: String,
63+ #[serde(default)]
64+ text: String,
65+ #[serde(default)]
66+ synthetic: bool,
67+ },
68+ Reasoning {
69+ #[serde(default)]
70+ id: String,
71+ #[serde(default, rename = "messageID")]
72+ message_id: String,
73+ #[serde(default)]
74+ text: String,
75+ },
76+ Tool {
77+ #[serde(default)]
78+ id: String,
79+ #[serde(default, rename = "messageID")]
80+ message_id: String,
81+ #[serde(default)]
82+ tool: String,
83+ #[serde(default)]
84+ state: serde_json::Value,
85+ },
86+ #[serde(other)]
87+ Other,
88+}
89+
90+impl WirePart {
91+ pub fn message_id(&self) -> &str {
92+ match self {
93+ WirePart::Text { message_id, .. }
94+ | WirePart::Reasoning { message_id, .. }
95+ | WirePart::Tool { message_id, .. } => message_id,
96+ WirePart::Other => "",
97+ }
98+ }
99+}
100+
101+/// Compact view of a `tool` part's state (the union keyed on `status`).
102+pub struct ToolStateView {
103+ pub status: String,
104+ pub title: Option<String>,
105+}
106+
107+/// Pull the `status` and a human title/output out of a tool part's `state` blob.
108+pub fn tool_state_view(state: &serde_json::Value) -> ToolStateView {
109+ let status = state
110+ .get("status")
111+ .and_then(|v| v.as_str())
112+ .unwrap_or("pending")
113+ .to_string();
114+ let title = state
115+ .get("title")
116+ .and_then(|v| v.as_str())
117+ .or_else(|| state.get("error").and_then(|v| v.as_str()))
118+ .map(str::to_string);
119+ ToolStateView { status, title }
120+}
121+
122+// ─── Errors ──────────────────────────────────────────────────────────────────
123+
124+#[derive(Deserialize, Debug, Clone)]
125+pub struct WireError {
126+ #[serde(default)]
127+ pub name: String,
128+ #[serde(default)]
129+ pub data: serde_json::Value,
130+}
131+
132+impl WireError {
133+ /// Best human-readable message: `data.message` if present, else the error name.
134+ pub fn message(&self) -> String {
135+ self.data
136+ .get("message")
137+ .and_then(|v| v.as_str())
138+ .map(str::to_string)
139+ .filter(|s| !s.is_empty())
140+ .unwrap_or_else(|| {
141+ if self.name.is_empty() {
142+ "Unknown error".to_string()
143+ } else {
144+ self.name.clone()
145+ }
146+ })
147+ }
148+}
149+
150+// ─── SSE `/event` stream ─────────────────────────────────────────────────────
151+
152+/// The SSE envelope: `{ "type": "...", "properties": { ... } }`. Unknown event
153+/// types decode to `Other` and are ignored.
154+#[derive(Deserialize, Debug)]
155+#[serde(tag = "type")]
156+pub enum ServerEvent {
157+ #[serde(rename = "message.updated")]
158+ MessageUpdated { properties: MessageUpdatedProps },
159+ #[serde(rename = "message.part.updated")]
160+ MessagePartUpdated { properties: PartUpdatedProps },
161+ #[serde(rename = "message.part.removed")]
162+ MessagePartRemoved { properties: PartRemovedProps },
163+ #[serde(rename = "message.removed")]
164+ MessageRemoved { properties: MessageRemovedProps },
165+ #[serde(rename = "session.idle")]
166+ SessionIdle { properties: SessionIdProps },
167+ #[serde(rename = "session.error")]
168+ SessionError { properties: SessionErrorProps },
169+ #[serde(rename = "session.updated")]
170+ SessionUpdated { properties: SessionInfoProps },
171+ #[serde(rename = "session.created")]
172+ SessionCreated { properties: SessionInfoProps },
173+ #[serde(rename = "session.deleted")]
174+ SessionDeleted { properties: SessionDeletedProps },
175+ #[serde(other)]
176+ Other,
177+}
178+
179+#[derive(Deserialize, Debug)]
180+pub struct MessageUpdatedProps {
181+ pub info: WireMessageInfo,
182+}
183+
184+#[derive(Deserialize, Debug)]
185+pub struct PartUpdatedProps {
186+ pub part: WirePart,
187+ #[serde(default)]
188+ pub delta: Option<String>,
189+}
190+
191+#[derive(Deserialize, Debug)]
192+pub struct PartRemovedProps {
193+ #[serde(default, rename = "messageID")]
194+ pub message_id: String,
195+ #[serde(default, rename = "partID")]
196+ pub part_id: String,
197+}
198+
199+#[derive(Deserialize, Debug)]
200+pub struct MessageRemovedProps {
201+ #[serde(default, rename = "messageID")]
202+ pub message_id: String,
203+}
204+
205+#[derive(Deserialize, Debug)]
206+pub struct SessionIdProps {
207+ #[serde(default, rename = "sessionID")]
208+ pub session_id: String,
209+}
210+
211+#[derive(Deserialize, Debug)]
212+pub struct SessionErrorProps {
213+ #[serde(default, rename = "sessionID")]
214+ pub session_id: Option<String>,
215+ #[serde(default)]
216+ pub error: Option<WireError>,
217+}
218+
219+#[derive(Deserialize, Debug)]
220+pub struct SessionInfoProps {
221+ pub info: WireSession,
222+}
223+
224+#[derive(Deserialize, Debug)]
225+pub struct SessionDeletedProps {
226+ #[serde(default, rename = "sessionID")]
227+ pub session_id: Option<String>,
228+ #[serde(default)]
229+ pub info: Option<WireSession>,
230+}
231+
232+// ─── Parse helpers ───────────────────────────────────────────────────────────
233+
234+pub fn parse_sessions(body: &str) -> Vec<WireSession> {
235+ serde_json::from_str(body).unwrap_or_default()
236+}
237+
238+pub fn parse_session(body: &str) -> Option<WireSession> {
239+ serde_json::from_str(body).ok()
240+}
241+
242+pub fn parse_messages(body: &str) -> Vec<WireMessageEnvelope> {
243+ serde_json::from_str(body).unwrap_or_default()
244+}
245+
246+pub fn parse_event(json: &str) -> Option<ServerEvent> {
247+ serde_json::from_str(json).ok()
248+}