git.iko.soy/opencode-android
on master help sign in
256 files changed+8016−47791
since splitsnapshots
unifiedsplit
.direnv/bin/nix-direnv-reload−19 .direnv/flake-inputs/01x5k4nlxcpyd85nnr0b9gm89rm8ff4x-source−1 .direnv/flake-inputs/kfs4nfy1705ksbn0gv15ls921cc90h2z-source−1 .direnv/flake-inputs/y4nm07b4ag6b9l0db8himn2xr1hyxfwr-source−1 .direnv/flake-inputs/yj1wxm9hh8610iyzqnz75kvs6xl8j3my-source−1 .direnv/flake-profile-a5d5b61aa8a61b7d9d765e1daf971a9a578f1cfa−1 .direnv/flake-profile-a5d5b61aa8a61b7d9d765e1daf971a9a578f1cfa.rc−2250 .github/workflows/build.yml+12−28 .github/workflows/release.yml+53−36 .gitignore+20 AGENTS.md−197 CLAUDE.md+40−1 README.md+126−64 app/build.gradle.kts+46−117 app/detekt-baseline.xml−34 app/proguard-rules.pro+13−44 app/src/androidTest/java/soy/iko/opencode/ApplicationBootstrapTest.kt−36 app/src/androidTest/java/soy/iko/opencode/data/repo/CrashLoggerTest.kt−67 app/src/androidTest/java/soy/iko/opencode/data/repo/DraftStoreTest.kt−51 app/src/main/AndroidManifest.xml+6−110 app/src/main/java/soy/iko/opencode/CoreViewModel.kt+66 app/src/main/java/soy/iko/opencode/MainActivity.kt+15−398 app/src/main/java/soy/iko/opencode/OpencodeApp.kt−130 app/src/main/java/soy/iko/opencode/core/HttpClient.kt+75 app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+668 app/src/main/java/soy/iko/opencode/core/Protocol.kt+148 app/src/main/java/soy/iko/opencode/core/SseClient.kt+63 app/src/main/java/soy/iko/opencode/core/ViewModel.kt+77 app/src/main/java/soy/iko/opencode/data/model/Agent.kt−37 app/src/main/java/soy/iko/opencode/data/model/BusEvent.kt−109 app/src/main/java/soy/iko/opencode/data/model/Common.kt−41 app/src/main/java/soy/iko/opencode/data/model/Files.kt−44 app/src/main/java/soy/iko/opencode/data/model/Message.kt−69 app/src/main/java/soy/iko/opencode/data/model/Part.kt−127 app/src/main/java/soy/iko/opencode/data/model/Permission.kt−58 app/src/main/java/soy/iko/opencode/data/model/Project.kt−32 app/src/main/java/soy/iko/opencode/data/model/Prompt.kt−68 app/src/main/java/soy/iko/opencode/data/model/Provider.kt−84 app/src/main/java/soy/iko/opencode/data/model/Search.kt−101 app/src/main/java/soy/iko/opencode/data/model/ServerProfile.kt−27 app/src/main/java/soy/iko/opencode/data/model/Session.kt−68 app/src/main/java/soy/iko/opencode/data/model/Todo.kt−95 app/src/main/java/soy/iko/opencode/data/model/ToolState.kt−62 app/src/main/java/soy/iko/opencode/data/network/CertPinUtil.kt−35 app/src/main/java/soy/iko/opencode/data/network/EventStreamClient.kt−335 app/src/main/java/soy/iko/opencode/data/network/HttpClientFactory.kt−167 app/src/main/java/soy/iko/opencode/data/network/NetworkConfig.kt−442 app/src/main/java/soy/iko/opencode/data/network/OpencodeApiClient.kt−540 app/src/main/java/soy/iko/opencode/data/network/OpencodeJson.kt−37 app/src/main/java/soy/iko/opencode/data/repo/AttachmentDraftStore.kt−114 app/src/main/java/soy/iko/opencode/data/repo/BackupManager.kt−180 app/src/main/java/soy/iko/opencode/data/repo/CrashLogger.kt−274 app/src/main/java/soy/iko/opencode/data/repo/DraftStore.kt−260 app/src/main/java/soy/iko/opencode/data/repo/ErrorKind.kt−78 app/src/main/java/soy/iko/opencode/data/repo/FileBrowserPrefs.kt−90 app/src/main/java/soy/iko/opencode/data/repo/MessageCacheStore.kt−137 app/src/main/java/soy/iko/opencode/data/repo/OutboxStore.kt−168 app/src/main/java/soy/iko/opencode/data/repo/ProfileStore.kt−251 app/src/main/java/soy/iko/opencode/data/repo/RecentModelsStore.kt−80 app/src/main/java/soy/iko/opencode/data/repo/RecentSessionsStore.kt−64 app/src/main/java/soy/iko/opencode/data/repo/SearchHistoryStore.kt−68 app/src/main/java/soy/iko/opencode/data/repo/SessionPrefsStore.kt−73 app/src/main/java/soy/iko/opencode/data/repo/SessionRepository.kt−647 app/src/main/java/soy/iko/opencode/data/repo/SettingsStore.kt−279 app/src/main/java/soy/iko/opencode/di/AppContainer.kt−1504 app/src/main/java/soy/iko/opencode/di/OpencodeConnection.kt−47 app/src/main/java/soy/iko/opencode/notification/NotificationActionReceiver.kt−195 app/src/main/java/soy/iko/opencode/notification/NotificationChannels.kt−65 app/src/main/java/soy/iko/opencode/notification/RunForegroundService.kt−210 app/src/main/java/soy/iko/opencode/notification/SessionNotifications.kt−527 app/src/main/java/soy/iko/opencode/platform/AppShortcuts.kt−58 app/src/main/java/soy/iko/opencode/platform/NewSessionTileService.kt−33 app/src/main/java/soy/iko/opencode/platform/SessionsWidgetProvider.kt−83 app/src/main/java/soy/iko/opencode/platform/SessionsWidgetService.kt−68 app/src/main/java/soy/iko/opencode/ui/AppLockGate.kt−302 app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+90−583 app/src/main/java/soy/iko/opencode/ui/Routes.kt−39 app/src/main/java/soy/iko/opencode/ui/VmFactory.kt−16 app/src/main/java/soy/iko/opencode/ui/chat/AgentPickerSheet.kt−318 app/src/main/java/soy/iko/opencode/ui/chat/AttachmentResult.kt−12 app/src/main/java/soy/iko/opencode/ui/chat/Attachments.kt−115 app/src/main/java/soy/iko/opencode/ui/chat/ChatAttachments.kt−258 app/src/main/java/soy/iko/opencode/ui/chat/ChatScreen.kt−3292 app/src/main/java/soy/iko/opencode/ui/chat/ChatViewModel.kt−1812 app/src/main/java/soy/iko/opencode/ui/chat/CommandPickerSheet.kt−248 app/src/main/java/soy/iko/opencode/ui/chat/ConversationExport.kt−236 app/src/main/java/soy/iko/opencode/ui/chat/CostFormat.kt−60 app/src/main/java/soy/iko/opencode/ui/chat/MessageBubble.kt−1418 app/src/main/java/soy/iko/opencode/ui/chat/ModelPickerSheet.kt−330 app/src/main/java/soy/iko/opencode/ui/chat/PartRenderer.kt−798 app/src/main/java/soy/iko/opencode/ui/chat/PermissionDialog.kt−312 app/src/main/java/soy/iko/opencode/ui/chat/TodoPlan.kt−205 app/src/main/java/soy/iko/opencode/ui/chat/TtsController.kt−245 app/src/main/java/soy/iko/opencode/ui/chat/ViewSourceDialog.kt−76 app/src/main/java/soy/iko/opencode/ui/components/AppTopBar.kt−82 app/src/main/java/soy/iko/opencode/ui/components/Autofill.kt−49 app/src/main/java/soy/iko/opencode/ui/components/ChatTextPrefs.kt−54 app/src/main/java/soy/iko/opencode/ui/components/CodeHighlighter.kt−534 app/src/main/java/soy/iko/opencode/ui/components/CommandPalette.kt−171 app/src/main/java/soy/iko/opencode/ui/components/CommonStates.kt−170 app/src/main/java/soy/iko/opencode/ui/components/CompactNavBar.kt−106 app/src/main/java/soy/iko/opencode/ui/components/ConnectionBanner.kt−266 app/src/main/java/soy/iko/opencode/ui/components/DiffView.kt−598 app/src/main/java/soy/iko/opencode/ui/components/EmptyState.kt−99 app/src/main/java/soy/iko/opencode/ui/components/GatedHapticFeedback.kt−33 app/src/main/java/soy/iko/opencode/ui/components/LargeScreenNavRail.kt−109 app/src/main/java/soy/iko/opencode/ui/components/LoadingSize.kt−12 app/src/main/java/soy/iko/opencode/ui/components/LoadingSpinner.kt−40 app/src/main/java/soy/iko/opencode/ui/components/MarkdownText.kt−811 app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+479 app/src/main/java/soy/iko/opencode/ui/components/PaletteAction.kt−11 app/src/main/java/soy/iko/opencode/ui/components/QrCode.kt−175 app/src/main/java/soy/iko/opencode/ui/components/ReducedMotion.kt−131 app/src/main/java/soy/iko/opencode/ui/components/RelativeTimeUnit.kt−41 app/src/main/java/soy/iko/opencode/ui/components/RemoteImage.kt−577 app/src/main/java/soy/iko/opencode/ui/components/SectionHeader.kt−25 app/src/main/java/soy/iko/opencode/ui/components/SkeletonRow.kt−97 app/src/main/java/soy/iko/opencode/ui/components/TimeFormat.kt−194 app/src/main/java/soy/iko/opencode/ui/file/FileBrowserScreen.kt−1016 app/src/main/java/soy/iko/opencode/ui/file/FileBrowserViewModel.kt−279 app/src/main/java/soy/iko/opencode/ui/file/FileViewModel.kt−91 app/src/main/java/soy/iko/opencode/ui/file/FileViewScreen.kt−1229 app/src/main/java/soy/iko/opencode/ui/file/TwoPaneFileBrowser.kt−117 app/src/main/java/soy/iko/opencode/ui/mcp/McpScreen.kt−498 app/src/main/java/soy/iko/opencode/ui/mcp/McpServerInfo.kt−76 app/src/main/java/soy/iko/opencode/ui/mcp/McpViewModel.kt−169 app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+590 app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+222 app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+402 app/src/main/java/soy/iko/opencode/ui/search/GlobalSearchScreen.kt−427 app/src/main/java/soy/iko/opencode/ui/search/GlobalSearchViewModel.kt−346 app/src/main/java/soy/iko/opencode/ui/server/ServerEditScreen.kt−578 app/src/main/java/soy/iko/opencode/ui/server/ServerEditViewModel.kt−523 app/src/main/java/soy/iko/opencode/ui/server/ServerListScreen.kt−822 app/src/main/java/soy/iko/opencode/ui/server/ServerListViewModel.kt−272 app/src/main/java/soy/iko/opencode/ui/session/NewSessionDialog.kt−315 app/src/main/java/soy/iko/opencode/ui/session/SessionListScreen.kt−2014 app/src/main/java/soy/iko/opencode/ui/session/SessionListViewModel.kt−1105 app/src/main/java/soy/iko/opencode/ui/session/TwoPaneSessionChat.kt−292 app/src/main/java/soy/iko/opencode/ui/settings/DiagnosticsScreen.kt−671 app/src/main/java/soy/iko/opencode/ui/settings/SettingsScreen.kt−1660 app/src/main/java/soy/iko/opencode/ui/theme/Color.kt+19 app/src/main/java/soy/iko/opencode/ui/theme/Shapes.kt−19 app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+38−179 app/src/main/java/soy/iko/opencode/ui/theme/Type.kt+15 app/src/main/java/soy/iko/opencode/ui/theme/Typography.kt−136 app/src/main/java/soy/iko/opencode/ui/usage/UsageAggregation.kt−151 app/src/main/java/soy/iko/opencode/ui/usage/UsageScreen.kt−419 app/src/main/java/soy/iko/opencode/ui/usage/UsageViewModel.kt−147 app/src/main/java/soy/iko/opencode/util/Contexts.kt−15 app/src/main/java/soy/iko/opencode/util/Coroutines.kt−56 app/src/main/res/drawable/ic_action_block.xml−10 app/src/main/res/drawable/ic_action_check.xml−9 app/src/main/res/drawable/ic_action_refresh.xml−9 app/src/main/res/drawable/ic_action_reply.xml−9 app/src/main/res/drawable/ic_action_stop.xml−9 app/src/main/res/drawable/ic_launcher_foreground.xml−13 app/src/main/res/drawable/ic_stat_notify.xml−9 app/src/main/res/drawable/widget_background.xml−8 app/src/main/res/layout/widget_session_item.xml−21 app/src/main/res/layout/widget_sessions.xml−64 app/src/main/res/mipmap-anydpi/ic_launcher.xml−6 app/src/main/res/values-es/strings.xml−915 app/src/main/res/values-es/strings_cross_ux.xml−7 app/src/main/res/values-es/strings_diag_ux.xml−4 app/src/main/res/values-es/strings_notif_ux.xml−5 app/src/main/res/values-es/strings_settings_ux.xml−12 app/src/main/res/values-night/colors.xml+1−15 app/src/main/res/values-night/themes.xml+2−2 app/src/main/res/values/colors.xml+1−19 app/src/main/res/values/strings.xml−938 app/src/main/res/values/strings_cross_ux.xml−7 app/src/main/res/values/strings_diag_ux.xml−4 app/src/main/res/values/strings_notif_ux.xml−8 app/src/main/res/values/strings_settings_ux.xml−12 app/src/main/res/values/themes.xml+7−16 app/src/main/res/xml/data_extraction_rules.xml−15 app/src/main/res/xml/file_paths.xml−9 app/src/main/res/xml/network_security_config.xml−15 app/src/main/res/xml/sessions_widget_info.xml−10 app/src/test/java/soy/iko/opencode/M5DecodingTest.kt−144 app/src/test/java/soy/iko/opencode/M6Test.kt−102 app/src/test/java/soy/iko/opencode/OpencodeJsonTest.kt−122 app/src/test/java/soy/iko/opencode/UxTest.kt−104 app/src/test/java/soy/iko/opencode/core/ConnectUrlTest.kt+69 app/src/test/java/soy/iko/opencode/data/model/TodoPlanTest.kt−90 app/src/test/java/soy/iko/opencode/data/network/EventStreamClientTest.kt−37 app/src/test/java/soy/iko/opencode/data/network/NormalizeBaseUrlTest.kt−42 app/src/test/java/soy/iko/opencode/data/network/OpencodeApiClientTest.kt−115 app/src/test/java/soy/iko/opencode/data/network/WithRetryTest.kt−254 app/src/test/java/soy/iko/opencode/data/repo/CrashLoggerScrubTest.kt−46 app/src/test/java/soy/iko/opencode/data/repo/ErrorKindTest.kt−60 app/src/test/java/soy/iko/opencode/data/repo/MessageStoreTest.kt−385 app/src/test/java/soy/iko/opencode/data/repo/OutboxStoreTest.kt−44 app/src/test/java/soy/iko/opencode/data/repo/SessionRepositoryTest.kt−73 app/src/test/java/soy/iko/opencode/di/UnreadTrackingTest.kt−56 app/src/test/java/soy/iko/opencode/ui/chat/ChatViewModelTest.kt−639 app/src/test/java/soy/iko/opencode/ui/chat/ConversationExportTest.kt−120 app/src/test/java/soy/iko/opencode/ui/chat/ToolDurationFormatTest.kt−45 app/src/test/java/soy/iko/opencode/ui/components/CodeHighlighterLanguageTest.kt−66 app/src/test/java/soy/iko/opencode/ui/components/DiffParseTest.kt−55 app/src/test/java/soy/iko/opencode/ui/components/ExtractCodeTextTest.kt−56 app/src/test/java/soy/iko/opencode/ui/components/ExtractFenceLanguageTest.kt−28 app/src/test/java/soy/iko/opencode/ui/file/FileBrowserViewModelTest.kt−219 app/src/test/java/soy/iko/opencode/ui/file/FileViewModelTest.kt−70 app/src/test/java/soy/iko/opencode/ui/mcp/McpParserTest.kt−52 app/src/test/java/soy/iko/opencode/ui/search/GlobalSearchViewModelTest.kt−120 app/src/test/java/soy/iko/opencode/ui/server/CertPinValidationTest.kt−39 app/src/test/java/soy/iko/opencode/ui/server/ServerEditViewModelTest.kt−460 app/src/test/java/soy/iko/opencode/ui/session/SessionListViewModelTest.kt−634 app/src/test/java/soy/iko/opencode/ui/testing/TestFakes.kt−480 app/src/test/java/soy/iko/opencode/ui/usage/UsageAggregationTest.kt−67 build.gradle.kts+2−1 config/detekt/detekt.yml−68 flake.lock+3−3 flake.nix+29−19 generated/com/novi/bincode/BincodeDeserializer.java+38 generated/com/novi/bincode/BincodeSerializer.java+33 generated/com/novi/serde/ArrayLen.java+12 generated/com/novi/serde/BinaryDeserializer.java+195 generated/com/novi/serde/BinarySerializer.java+146 generated/com/novi/serde/Bytes.java+54 generated/com/novi/serde/DeserializationError.java+11 generated/com/novi/serde/Deserializer.java+56 generated/com/novi/serde/Int128.java+11 generated/com/novi/serde/SerializationError.java+11 generated/com/novi/serde/Serializer.java+58 generated/com/novi/serde/Slice.java+40 generated/com/novi/serde/Tuple2.java+40 generated/com/novi/serde/Tuple3.java+46 generated/com/novi/serde/Tuple4.java+54 generated/com/novi/serde/Tuple5.java+61 generated/com/novi/serde/Tuple6.java+67 generated/com/novi/serde/Unit.java+20 generated/com/novi/serde/Unsigned.java+11 generated/soy/iko/opencode/shared/MessageStatus.java+150 generated/soy/iko/opencode/shared/MessageView.java+131 generated/soy/iko/opencode/shared/Requests.java+27 generated/soy/iko/opencode/shared/Screen.java+150 generated/soy/iko/opencode/shared/SessionView.java+77 generated/soy/iko/opencode/shared/ToolView.java+86 generated/soy/iko/opencode/shared/TraitHelpers.java+71 generated/soy/iko/opencode/shared/ViewModel.java+185 gradle.properties+5−2 gradle/libs.versions.toml+29−60 gradle/wrapper/gradle-wrapper.properties+1−1 renovate.json−32 scripts/run-device.sh−106 scripts/run.sh−95 settings.gradle.kts+3 shared/Cargo.lock+1358 shared/Cargo.toml+31 shared/src/app.rs+1051 shared/src/bin/codegen.rs+35 shared/src/lib.rs+17 shared/src/protocol.rs+248
.direnv/bin/nix-direnv-reloaddeleted−19
@@ -1,19 +0,0 @@
1−#!/usr/bin/env bash
2−set -e
3−if [[ ! -d "/home/iko/opencode-android" ]]; then
4− echo "Cannot find source directory; Did you move it?"
5− echo "(Looking for "/home/iko/opencode-android")"
6− echo 'Cannot force reload with this script - use "direnv reload" manually and then try again'
7− exit 1
8−fi
9−
10−# rebuild the cache forcefully
11−_nix_direnv_force_reload=1 direnv exec "/home/iko/opencode-android" true
12−
13−# Update the mtime for .envrc.
14−# This will cause direnv to reload again - but without re-building.
15−touch "/home/iko/opencode-android/.envrc"
16−
17−# Also update the timestamp of whatever profile_rc we have.
18−# This makes sure that we know we are up to date.
19−touch -r "/home/iko/opencode-android/.envrc" "/home/iko/opencode-android/.direnv"/*.rc
.direnv/flake-inputs/01x5k4nlxcpyd85nnr0b9gm89rm8ff4x-sourcedeleted−1
@@ -1 +0,0 @@
1−/nix/store/01x5k4nlxcpyd85nnr0b9gm89rm8ff4x-source
.direnv/flake-inputs/kfs4nfy1705ksbn0gv15ls921cc90h2z-sourcedeleted−1
@@ -1 +0,0 @@
1−/nix/store/kfs4nfy1705ksbn0gv15ls921cc90h2z-source
.direnv/flake-inputs/y4nm07b4ag6b9l0db8himn2xr1hyxfwr-sourcedeleted−1
@@ -1 +0,0 @@
1−/nix/store/y4nm07b4ag6b9l0db8himn2xr1hyxfwr-source
.direnv/flake-inputs/yj1wxm9hh8610iyzqnz75kvs6xl8j3my-sourcedeleted−1
@@ -1 +0,0 @@
1−/nix/store/yj1wxm9hh8610iyzqnz75kvs6xl8j3my-source
.direnv/flake-profile-a5d5b61aa8a61b7d9d765e1daf971a9a578f1cfadeleted−1
@@ -1 +0,0 @@
1−/nix/store/n53brq0w7p7wvbsxw4i8y3sxraf91hci-nix-shell-env
.direnv/flake-profile-a5d5b61aa8a61b7d9d765e1daf971a9a578f1cfa.rcdeleted−2250
@@ -1,2250 +0,0 @@
1−unset shellHook
2−PATH=${PATH:-}
3−nix_saved_PATH="$PATH"
4−XDG_DATA_DIRS=${XDG_DATA_DIRS:-}
5−nix_saved_XDG_DATA_DIRS="$XDG_DATA_DIRS"
6−ANDROID_HOME='/nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk/libexec/android-sdk'
7−export ANDROID_HOME
8−ANDROID_SDK_ROOT='/nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk/libexec/android-sdk'
9−export ANDROID_SDK_ROOT
10−AR='ar'
11−export AR
12−AS='as'
13−export AS
14−BASH='/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin/bash'
15−CC='gcc'
16−export CC
17−CLASSPATH=''
18−export CLASSPATH
19−CONFIG_SHELL='/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin/bash'
20−export CONFIG_SHELL
21−CXX='g++'
22−export CXX
23−GRADLE_OPTS='-Dorg.gradle.project.android.aapt2FromMavenOverride=/nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk/libexec/android-sdk/build-tools/35.0.0/aapt2'
24−export GRADLE_OPTS
25−HOSTTYPE='x86_64'
26−HOST_PATH='/nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2/bin:/nix/store/hwcbpab3i98nbx7alfq4ggsfgv3i2kc3-gradle-8.14.4/bin:/nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk/bin:/nix/store/sr26flm2nkfa12dkrwj2630kqsfakky4-coreutils-9.11/bin:/nix/store/zjwih3d9rrrw4ixll52wsy0538p7vdfd-findutils-4.10.0/bin:/nix/store/3c05s0vxy8wafaa7lkj4bfh69wa0ch10-diffutils-3.12/bin:/nix/store/0hamsiy8hsyfw1hmizbc3bf93ad7fa1v-gnused-4.9/bin:/nix/store/w8xlvapzxcz23ba312q119p57bnc7200-gnugrep-3.12/bin:/nix/store/cdd73p8qiphg0scs02i6lrg1sjsdvbkx-gawk-5.4.0/bin:/nix/store/066fzlsj0wdq2sqxjrksysfxyr4r5f72-gnutar-1.35/bin:/nix/store/h304h5a5y9h1pl6crhz65jlri91nxyay-gzip-1.14/bin:/nix/store/lc20sfvskz0my6phs73nmsnlrxp06kgb-bzip2-1.0.8-bin/bin:/nix/store/i4jf7w00lr5q85r55rc35n83l7iwys73-gnumake-4.4.1/bin:/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin:/nix/store/vm55g5jg7ra19gdsxsxr092vpb52ayiz-patch-2.8/bin:/nix/store/y5zljns1fbcdgh5pp1szjlw0j11xxvcy-xz-5.8.3-bin/bin:/nix/store/y1fmsp7vhpdaclpqbsgm2qyl7yixx4ci-file-5.47/bin'
27−export HOST_PATH
28−IFS='
29−'
30−IN_NIX_SHELL='impure'
31−export IN_NIX_SHELL
32−JAVA_HOME='/nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2'
33−export JAVA_HOME
34−LD='ld'
35−export LD
36−LINENO='80'
37−MACHTYPE='x86_64-pc-linux-gnu'
38−NIX_BINTOOLS='/nix/store/z4zcd87nx2hrsdayd0vl2mx5ncj3ikd8-binutils-wrapper-2.46'
39−export NIX_BINTOOLS
40−NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu='1'
41−export NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu
42−NIX_BUILD_CORES='4'
43−export NIX_BUILD_CORES
44−NIX_CC='/nix/store/xcnqqnhw9hb4j5rjgds2yjryi8qki5f3-gcc-wrapper-15.2.0'
45−export NIX_CC
46−NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu='1'
47−export NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu
48−NIX_CFLAGS_COMPILE=' -frandom-seed=n53brq0w7p -isystem /nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2/include -isystem /nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2/include'
49−export NIX_CFLAGS_COMPILE
50−NIX_ENFORCE_NO_NATIVE='1'
51−export NIX_ENFORCE_NO_NATIVE
52−NIX_HARDENING_ENABLE='bindnow format fortify fortify3 libcxxhardeningfast pic relro stackclashprotection stackprotector strictflexarrays1 strictoverflow zerocallusedregs'
53−export NIX_HARDENING_ENABLE
54−NIX_LDFLAGS='-rpath /home/iko/opencode-android/outputs/out/lib '
55−export NIX_LDFLAGS
56−NIX_NO_SELF_RPATH='1'
57−NIX_STORE='/nix/store'
58−export NIX_STORE
59−NM='nm'
60−export NM
61−OBJCOPY='objcopy'
62−export OBJCOPY
63−OBJDUMP='objdump'
64−export OBJDUMP
65−OLDPWD=''
66−export OLDPWD
67−OPTERR='1'
68−OSTYPE='linux-gnu'
69−PATH='/nix/store/jbav217344pndjbghzyjmh0mkzy1973i-patchelf-0.15.2/bin:/nix/store/xcnqqnhw9hb4j5rjgds2yjryi8qki5f3-gcc-wrapper-15.2.0/bin:/nix/store/sq0nrnfwhkc5ljvklnrk5ps4358g4nbj-gcc-15.2.0/bin:/nix/store/521dd0054ifhzmjfmpx9mz0hr7wh7sig-glibc-2.42-67-bin/bin:/nix/store/sr26flm2nkfa12dkrwj2630kqsfakky4-coreutils-9.11/bin:/nix/store/z4zcd87nx2hrsdayd0vl2mx5ncj3ikd8-binutils-wrapper-2.46/bin:/nix/store/39lyf5g2iz4jd2r6q4g5whk9vw09zglj-binutils-2.46/bin:/nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2/bin:/nix/store/hwcbpab3i98nbx7alfq4ggsfgv3i2kc3-gradle-8.14.4/bin:/nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk/bin:/nix/store/sr26flm2nkfa12dkrwj2630kqsfakky4-coreutils-9.11/bin:/nix/store/zjwih3d9rrrw4ixll52wsy0538p7vdfd-findutils-4.10.0/bin:/nix/store/3c05s0vxy8wafaa7lkj4bfh69wa0ch10-diffutils-3.12/bin:/nix/store/0hamsiy8hsyfw1hmizbc3bf93ad7fa1v-gnused-4.9/bin:/nix/store/w8xlvapzxcz23ba312q119p57bnc7200-gnugrep-3.12/bin:/nix/store/cdd73p8qiphg0scs02i6lrg1sjsdvbkx-gawk-5.4.0/bin:/nix/store/066fzlsj0wdq2sqxjrksysfxyr4r5f72-gnutar-1.35/bin:/nix/store/h304h5a5y9h1pl6crhz65jlri91nxyay-gzip-1.14/bin:/nix/store/lc20sfvskz0my6phs73nmsnlrxp06kgb-bzip2-1.0.8-bin/bin:/nix/store/i4jf7w00lr5q85r55rc35n83l7iwys73-gnumake-4.4.1/bin:/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin:/nix/store/vm55g5jg7ra19gdsxsxr092vpb52ayiz-patch-2.8/bin:/nix/store/y5zljns1fbcdgh5pp1szjlw0j11xxvcy-xz-5.8.3-bin/bin:/nix/store/y1fmsp7vhpdaclpqbsgm2qyl7yixx4ci-file-5.47/bin'
70−export PATH
71−PS4='+ '
72−RANLIB='ranlib'
73−export RANLIB
74−READELF='readelf'
75−export READELF
76−SHELL='/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin/bash'
77−export SHELL
78−SIZE='size'
79−export SIZE
80−SOURCE_DATE_EPOCH='315532800'
81−export SOURCE_DATE_EPOCH
82−STRINGS='strings'
83−export STRINGS
84−STRIP='strip'
85−export STRIP
86−XDG_DATA_DIRS='/nix/store/jbav217344pndjbghzyjmh0mkzy1973i-patchelf-0.15.2/share'
87−export XDG_DATA_DIRS
88−__structuredAttrs=''
89−export __structuredAttrs
90−_substituteStream_has_warned_replace_deprecation='false'
91−buildInputs='/nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2 /nix/store/hwcbpab3i98nbx7alfq4ggsfgv3i2kc3-gradle-8.14.4 /nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk'
92−export buildInputs
93−buildPhase='{ echo "------------------------------------------------------------";
94− echo " WARNING: the existence of this path is not guaranteed.";
95− echo " It is an internal implementation detail for pkgs.mkShell.";
96− echo "------------------------------------------------------------";
97− echo;
98− # Record all build inputs as runtime dependencies
99− export;
100−} >> "$out"
101−'
102−export buildPhase
103−builder='/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin/bash'
104−export builder
105−checkPhase='gradleCheckPhase'
106−cmakeFlags=''
107−export cmakeFlags
108−configureFlags=''
109−export configureFlags
110−defaultBuildInputs=''
111−defaultNativeBuildInputs='/nix/store/jbav217344pndjbghzyjmh0mkzy1973i-patchelf-0.15.2 /nix/store/iymsdj1yqiy7d8pylqvjqxqiqb9lqq94-update-autotools-gnu-config-scripts-hook /nix/store/0y5xmdb7qfvimjwbq7ibg1xdgkgjwqng-no-broken-symlinks.sh /nix/store/cv1d7p48379km6a85h4zp6kr86brh32q-audit-tmpdir.sh /nix/store/85clx3b0xkdf58jn161iy80y5223ilbi-compress-man-pages.sh /nix/store/p3l1a5y7nllfyrjn2krlwgcc3z0cd3fq-make-symlinks-relative.sh /nix/store/5yzw0vhkyszf2d179m0qfkgxmp5wjjx4-move-docs.sh /nix/store/fyaryjvghbkpfnsyw97hb3lyb37s1pd6-move-lib64.sh /nix/store/kd4xwxjpjxi71jkm6ka0np72if9rm3y0-move-sbin.sh /nix/store/pag6l61paj1dc9sv15l7bm5c17xn5kyk-move-systemd-user-units.sh /nix/store/cmzya9irvxzlkh7lfy6i82gbp0saxqj3-multiple-outputs.sh /nix/store/x8c40nfigps493a07sdr2pm5s9j1cdc0-patch-shebangs.sh /nix/store/cickvswrvann041nqxb0rxilc46svw1n-prune-libtool-files.sh /nix/store/xyff06pkhki3qy1ls77w10s0v79c9il0-reproducible-builds.sh /nix/store/z7k98578dfzi6l3hsvbivzm7hfqlk0zc-set-source-date-epoch-to-latest.sh /nix/store/pilsssjjdxvdphlg2h19p0bfx5q0jzkn-strip.sh /nix/store/xcnqqnhw9hb4j5rjgds2yjryi8qki5f3-gcc-wrapper-15.2.0'
112−depsBuildBuild=''
113−export depsBuildBuild
114−depsBuildBuildPropagated=''
115−export depsBuildBuildPropagated
116−depsBuildTarget=''
117−export depsBuildTarget
118−depsBuildTargetPropagated=''
119−export depsBuildTargetPropagated
120−depsHostHost=''
121−export depsHostHost
122−depsHostHostPropagated=''
123−export depsHostHostPropagated
124−depsTargetTarget=''
125−export depsTargetTarget
126−depsTargetTargetPropagated=''
127−export depsTargetTargetPropagated
128−doCheck=''
129−export doCheck
130−doInstallCheck=''
131−export doInstallCheck
132−dontAddDisableDepTrack='1'
133−export dontAddDisableDepTrack
134−declare -a envBuildBuildHooks=()
135−declare -a envBuildHostHooks=()
136−declare -a envBuildTargetHooks=()
137−declare -a envHostHostHooks=('ccWrapper_addCVars' 'bintoolsWrapper_addLDVars' )
138−declare -a envHostTargetHooks=('ccWrapper_addCVars' 'bintoolsWrapper_addLDVars' )
139−declare -a envTargetTargetHooks=('addPkgToClassPath' )
140−declare -a fixupOutputHooks=('if [ -z "${dontPatchELF-}" ]; then patchELF "$prefix"; fi' 'if [[ -z "${noAuditTmpdir-}" && -e "$prefix" ]]; then auditTmpdir "$prefix"; fi' 'if [ -z "${dontGzipMan-}" ]; then compressManPages "$prefix"; fi' '_moveLib64' '_moveSbin' '_moveSystemdUserUnits' 'patchShebangsAuto' '_pruneLibtoolFiles' '_doStrip' )
141−initialPath='/nix/store/sr26flm2nkfa12dkrwj2630kqsfakky4-coreutils-9.11 /nix/store/zjwih3d9rrrw4ixll52wsy0538p7vdfd-findutils-4.10.0 /nix/store/3c05s0vxy8wafaa7lkj4bfh69wa0ch10-diffutils-3.12 /nix/store/0hamsiy8hsyfw1hmizbc3bf93ad7fa1v-gnused-4.9 /nix/store/w8xlvapzxcz23ba312q119p57bnc7200-gnugrep-3.12 /nix/store/cdd73p8qiphg0scs02i6lrg1sjsdvbkx-gawk-5.4.0 /nix/store/066fzlsj0wdq2sqxjrksysfxyr4r5f72-gnutar-1.35 /nix/store/h304h5a5y9h1pl6crhz65jlri91nxyay-gzip-1.14 /nix/store/lc20sfvskz0my6phs73nmsnlrxp06kgb-bzip2-1.0.8-bin /nix/store/i4jf7w00lr5q85r55rc35n83l7iwys73-gnumake-4.4.1 /nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9 /nix/store/vm55g5jg7ra19gdsxsxr092vpb52ayiz-patch-2.8 /nix/store/y5zljns1fbcdgh5pp1szjlw0j11xxvcy-xz-5.8.3-bin /nix/store/y1fmsp7vhpdaclpqbsgm2qyl7yixx4ci-file-5.47'
142−mesonFlags=''
143−export mesonFlags
144−name='nix-shell-env'
145−export name
146−nativeBuildInputs=''
147−export nativeBuildInputs
148−out='/home/iko/opencode-android/outputs/out'
149−export out
150−outputBin='out'
151−outputDev='out'
152−outputDevdoc='REMOVE'
153−outputDevman='out'
154−outputDoc='out'
155−outputInclude='out'
156−outputInfo='out'
157−outputLib='out'
158−outputMan='out'
159−outputs='out'
160−export outputs
161−patches=''
162−export patches
163−phases='buildPhase'
164−export phases
165−pkg='/nix/store/xcnqqnhw9hb4j5rjgds2yjryi8qki5f3-gcc-wrapper-15.2.0'
166−declare -a pkgsBuildBuild=()
167−declare -a pkgsBuildHost=('/nix/store/jbav217344pndjbghzyjmh0mkzy1973i-patchelf-0.15.2' '/nix/store/iymsdj1yqiy7d8pylqvjqxqiqb9lqq94-update-autotools-gnu-config-scripts-hook' '/nix/store/0y5xmdb7qfvimjwbq7ibg1xdgkgjwqng-no-broken-symlinks.sh' '/nix/store/cv1d7p48379km6a85h4zp6kr86brh32q-audit-tmpdir.sh' '/nix/store/85clx3b0xkdf58jn161iy80y5223ilbi-compress-man-pages.sh' '/nix/store/p3l1a5y7nllfyrjn2krlwgcc3z0cd3fq-make-symlinks-relative.sh' '/nix/store/5yzw0vhkyszf2d179m0qfkgxmp5wjjx4-move-docs.sh' '/nix/store/fyaryjvghbkpfnsyw97hb3lyb37s1pd6-move-lib64.sh' '/nix/store/kd4xwxjpjxi71jkm6ka0np72if9rm3y0-move-sbin.sh' '/nix/store/pag6l61paj1dc9sv15l7bm5c17xn5kyk-move-systemd-user-units.sh' '/nix/store/cmzya9irvxzlkh7lfy6i82gbp0saxqj3-multiple-outputs.sh' '/nix/store/x8c40nfigps493a07sdr2pm5s9j1cdc0-patch-shebangs.sh' '/nix/store/cickvswrvann041nqxb0rxilc46svw1n-prune-libtool-files.sh' '/nix/store/xyff06pkhki3qy1ls77w10s0v79c9il0-reproducible-builds.sh' '/nix/store/z7k98578dfzi6l3hsvbivzm7hfqlk0zc-set-source-date-epoch-to-latest.sh' '/nix/store/pilsssjjdxvdphlg2h19p0bfx5q0jzkn-strip.sh' '/nix/store/xcnqqnhw9hb4j5rjgds2yjryi8qki5f3-gcc-wrapper-15.2.0' '/nix/store/z4zcd87nx2hrsdayd0vl2mx5ncj3ikd8-binutils-wrapper-2.46' )
168−declare -a pkgsBuildTarget=()
169−declare -a pkgsHostHost=()
170−declare -a pkgsHostTarget=('/nix/store/q6zvjlnhypm88y989l8fq0hjqrz9agda-openjdk-17.0.20+2' '/nix/store/2dsv152lhz5rxl24fkb6sis3q165swv6-set-java-classpath-hook' '/nix/store/hwcbpab3i98nbx7alfq4ggsfgv3i2kc3-gradle-8.14.4' '/nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk' )
171−declare -a pkgsTargetTarget=()
172−declare -a postFixupHooks=('noBrokenSymlinksInAllOutputs' '_makeSymlinksRelative' '_multioutPropagateDev' )
173−declare -a postUnpackHooks=('_updateSourceDateEpochFromSourceRoot' )
174−declare -a preConfigureHooks=('mitmCacheConfigureHook' '_multioutConfig' 'gradleConfigureHook' )
175−preConfigurePhases=' updateAutotoolsGnuConfigScriptsPhase'
176−declare -a preFixupHooks=('_moveToShare' '_multioutDocs' '_multioutDevs' )
177−preferLocalBuild='1'
178−export preferLocalBuild
179−prefix='/home/iko/opencode-android/outputs/out'
180−declare -a propagatedBuildDepFiles=('propagated-build-build-deps' 'propagated-native-build-inputs' 'propagated-build-target-deps' )
181−propagatedBuildInputs=''
182−export propagatedBuildInputs
183−declare -a propagatedHostDepFiles=('propagated-host-host-deps' 'propagated-build-inputs' )
184−propagatedNativeBuildInputs=''
185−export propagatedNativeBuildInputs
186−declare -a propagatedTargetDepFiles=('propagated-target-target-deps' )
187−shell='/nix/store/zh1ijdhb6gng1509b1zrilb6xlzx60j6-bash-5.3p9/bin/bash'
188−export shell
189−shellHook='echo "opencode-android dev shell"
190−echo " JDK: $(java -version 2>&1 | head -1)"
191−echo " ANDROID_HOME: $ANDROID_HOME"
192−echo " aapt2: /nix/store/absfk78zd45lgyjp0nh19y6gpdnd3lpi-androidsdk/libexec/android-sdk/build-tools/35.0.0/aapt2"
193−echo ""
194−echo "Build: ./gradlew assembleDebug"
195−echo "Device: adb devices"
196−'
197−export shellHook
198−stdenv='/nix/store/xknwpg5yjxxsffmwdmpys269543wpdy5-stdenv-linux'
199−export stdenv
200−strictDeps=''
201−export strictDeps
202−system='x86_64-linux'
203−export system
204−declare -a unpackCmdHooks=('_defaultUnpack' )
205−_activatePkgs ()
206−{
207−
208− local hostOffset targetOffset;
209− local pkg;
210− for hostOffset in "${allPlatOffsets[@]}";
211− do
212− local pkgsVar="${pkgAccumVarVars[hostOffset + 1]}";
213− for targetOffset in "${allPlatOffsets[@]}";
214− do
215− (( hostOffset <= targetOffset )) || continue;
216− local pkgsRef="${pkgsVar}[$targetOffset - $hostOffset]";
217− local pkgsSlice="${!pkgsRef}[@]";
218− for pkg in ${!pkgsSlice+"${!pkgsSlice}"};
219− do
220− activatePackage "$pkg" "$hostOffset" "$targetOffset";
221− done;
222− done;
223− done
224−}
225−_addRpathPrefix ()
226−{
227−
228− if [ "${NIX_NO_SELF_RPATH:-0}" != 1 ]; then
229− export NIX_LDFLAGS="-rpath $1/lib ${NIX_LDFLAGS-}";
230− fi
231−}
232−_addToEnv ()
233−{
234−
235− local depHostOffset depTargetOffset;
236− local pkg;
237− for depHostOffset in "${allPlatOffsets[@]}";
238− do
239− local hookVar="${pkgHookVarVars[depHostOffset + 1]}";
240− local pkgsVar="${pkgAccumVarVars[depHostOffset + 1]}";
241− for depTargetOffset in "${allPlatOffsets[@]}";
242− do
243− (( depHostOffset <= depTargetOffset )) || continue;
244− local hookRef="${hookVar}[$depTargetOffset - $depHostOffset]";
245− if [[ -z "${strictDeps-}" ]]; then
246− local visitedPkgs="";
247− for pkg in "${pkgsBuildBuild[@]}" "${pkgsBuildHost[@]}" "${pkgsBuildTarget[@]}" "${pkgsHostHost[@]}" "${pkgsHostTarget[@]}" "${pkgsTargetTarget[@]}";
248− do
249− if [[ "$visitedPkgs" = *"$pkg"* ]]; then
250− continue;
251− fi;
252− runHook "${!hookRef}" "$pkg";
253− visitedPkgs+=" $pkg";
254− done;
255− else
256− local pkgsRef="${pkgsVar}[$depTargetOffset - $depHostOffset]";
257− local pkgsSlice="${!pkgsRef}[@]";
258− for pkg in ${!pkgsSlice+"${!pkgsSlice}"};
259− do
260− runHook "${!hookRef}" "$pkg";
261− done;
262− fi;
263− done;
264− done
265−}
266−_allFlags ()
267−{
268−
269− export system pname name version;
270− while IFS='' read -r varName; do
271− nixTalkativeLog "@${varName}@ -> ${!varName}";
272− args+=("--subst-var" "$varName");
273− done < <(awk 'BEGIN { for (v in ENVIRON) if (v ~ /^[a-z][a-zA-Z0-9_]*$/) print v }')
274−}
275−_assignFirst ()
276−{
277−
278− local varName="$1";
279− local _var;
280− local REMOVE=REMOVE;
281− shift;
282− for _var in "$@";
283− do
284− if [ -n "${!_var-}" ]; then
285− eval "${varName}"="${_var}";
286− return;
287− fi;
288− done;
289− echo;
290− echo "error: _assignFirst: could not find a non-empty variable whose name to assign to ${varName}.";
291− echo " The following variables were all unset or empty:";
292− echo " $*";
293− if [ -z "${out:-}" ]; then
294− echo ' If you do not want an "out" output in your derivation, make sure to define';
295− echo ' the other specific required outputs. This can be achieved by picking one';
296− echo " of the above as an output.";
297− echo ' You do not have to remove "out" if you want to have a different default';
298− echo ' output, because the first output is taken as a default.';
299− echo;
300− fi;
301− return 1
302−}
303−_callImplicitHook ()
304−{
305−
306− local def="$1";
307− local hookName="$2";
308− if declare -F "$hookName" > /dev/null; then
309− nixTalkativeLog "calling implicit '$hookName' function hook";
310− "$hookName";
311− else
312− if type -p "$hookName" > /dev/null; then
313− nixTalkativeLog "sourcing implicit '$hookName' script hook";
314− source "$hookName";
315− else
316− if [ -n "${!hookName:-}" ]; then
317− nixTalkativeLog "evaling implicit '$hookName' string hook";
318− eval "${!hookName}";
319− else
320− return "$def";
321− fi;
322− fi;
323− fi
324−}
325−_defaultUnpack ()
326−{
327−
328− local fn="$1";
329− local destination;
330− if [ -d "$fn" ]; then
331− destination="$(stripHash "$fn")";
332− if [ -e "$destination" ]; then
333− echo "Cannot copy $fn to $destination: destination already exists!";
334− echo "Did you specify two \"srcs\" with the same \"name\"?";
335− return 1;
336− fi;
337− cp -r --preserve=timestamps --reflink=auto -- "$fn" "$destination";
338− else
339− case "$fn" in
340− *.tar.xz | *.tar.lzma | *.txz)
341− ( XZ_OPT="--threads=$NIX_BUILD_CORES" xz -d < "$fn";
342− true ) | tar xf - --mode=+w --warning=no-timestamp
343− ;;
344− *.tar | *.tar.* | *.tgz | *.tbz2 | *.tbz)
345− tar xf "$fn" --mode=+w --warning=no-timestamp
346− ;;
347− *)
348− return 1
349− ;;
350− esac;
351− fi
352−}
353−_doStrip ()
354−{
355−
356− local -ra flags=(dontStripHost dontStripTarget);
357− local -ra debugDirs=(stripDebugList stripDebugListTarget);
358− local -ra allDirs=(stripAllList stripAllListTarget);
359− local -ra stripCmds=(STRIP STRIP_FOR_TARGET);
360− local -ra ranlibCmds=(RANLIB RANLIB_FOR_TARGET);
361− stripDebugList=${stripDebugList[*]:-lib lib32 lib64 libexec bin sbin Applications Library/Frameworks};
362− stripDebugListTarget=${stripDebugListTarget[*]:-};
363− stripAllList=${stripAllList[*]:-};
364− stripAllListTarget=${stripAllListTarget[*]:-};
365− local i;
366− for i in ${!stripCmds[@]};
367− do
368− local -n flag="${flags[$i]}";
369− local -n debugDirList="${debugDirs[$i]}";
370− local -n allDirList="${allDirs[$i]}";
371− local -n stripCmd="${stripCmds[$i]}";
372− local -n ranlibCmd="${ranlibCmds[$i]}";
373− if [[ -n "${dontStrip-}" || -n "${flag-}" ]] || ! type -f "${stripCmd-}" 2> /dev/null 1>&2; then
374− continue;
375− fi;
376− stripDirs "$stripCmd" "$ranlibCmd" "$debugDirList" "${stripDebugFlags[*]:--S -p}";
377− stripDirs "$stripCmd" "$ranlibCmd" "$allDirList" "${stripAllFlags[*]:--s -p}";
378− done
379−}
380−_eval ()
381−{
382−
383− if declare -F "$1" > /dev/null 2>&1; then
384− "$@";
385− else
386− eval "$1";
387− fi
388−}
389−_logHook ()
390−{
391−
392− if [[ -z ${NIX_LOG_FD-} ]]; then
393− return;
394− fi;
395− local hookKind="$1";
396− local hookExpr="$2";
397− shift 2;
398− if declare -F "$hookExpr" > /dev/null 2>&1; then
399− nixTalkativeLog "calling '$hookKind' function hook '$hookExpr'" "$@";
400− else
401− if type -p "$hookExpr" > /dev/null; then
402− nixTalkativeLog "sourcing '$hookKind' script hook '$hookExpr'";
403− else
404− if [[ "$hookExpr" != "_callImplicitHook"* ]]; then
405− local exprToOutput;
406− if [[ ${NIX_DEBUG:-0} -ge 5 ]]; then
407− exprToOutput="$hookExpr";
408− else
409− local hookExprLine;
410− while IFS= read -r hookExprLine; do
411− hookExprLine="${hookExprLine#"${hookExprLine%%[![:space:]]*}"}";
412− if [[ -n "$hookExprLine" ]]; then
413− exprToOutput+="$hookExprLine\\n ";
414− fi;
415− done <<< "$hookExpr";
416− exprToOutput="${exprToOutput%%\\n }";
417− fi;
418− nixTalkativeLog "evaling '$hookKind' string hook '$exprToOutput'";
419− fi;
420− fi;
421− fi
422−}
423−_makeSymlinksRelative ()
424−{
425−
426− local prefixes;
427− prefixes=();
428− for output in $(getAllOutputNames);
429− do
430− [ ! -e "${!output}" ] && continue;
431− prefixes+=("${!output}");
432− done;
433− find "${prefixes[@]}" -type l -printf '%H\0%p\0' | xargs -0 -n2 -r -P "$NIX_BUILD_CORES" sh -c '
434− output="$1"
435− link="$2"
436−
437− linkTarget=$(readlink "$link")
438−
439− # only touch links that point inside the same output tree
440− [[ $linkTarget == "$output"/* ]] || exit 0
441−
442− if [ ! -e "$linkTarget" ]; then
443− echo "the symlink $link is broken, it points to $linkTarget (which is missing)"
444− fi
445−
446− echo "making symlink relative: $link"
447− ln -snrf "$linkTarget" "$link"
448− ' _
449−}
450−_moveLib64 ()
451−{
452−
453− if [ "${dontMoveLib64-}" = 1 ]; then
454− return;
455− fi;
456− if [ ! -e "$prefix/lib64" -o -L "$prefix/lib64" ]; then
457− return;
458− fi;
459− echo "moving $prefix/lib64/* to $prefix/lib";
460− mkdir -p $prefix/lib;
461− shopt -s dotglob;
462− for i in $prefix/lib64/*;
463− do
464− mv --no-clobber "$i" $prefix/lib;
465− done;
466− shopt -u dotglob;
467− rmdir $prefix/lib64;
468− ln -s lib $prefix/lib64
469−}
470−_moveSbin ()
471−{
472−
473− if [ "${dontMoveSbin-}" = 1 ]; then
474− return;
475− fi;
476− if [ ! -e "$prefix/sbin" -o -L "$prefix/sbin" ]; then
477− return;
478− fi;
479− echo "moving $prefix/sbin/* to $prefix/bin";
480− mkdir -p $prefix/bin;
481− shopt -s dotglob;
482− for i in $prefix/sbin/*;
483− do
484− mv "$i" $prefix/bin;
485− done;
486− shopt -u dotglob;
487− rmdir $prefix/sbin;
488− ln -s bin $prefix/sbin
489−}
490−_moveSystemdUserUnits ()
491−{
492−
493− if [ "${dontMoveSystemdUserUnits:-0}" = 1 ]; then
494− return;
495− fi;
496− if [ ! -e "${prefix:?}/lib/systemd/user" ]; then
497− return;
498− fi;
499− local source="$prefix/lib/systemd/user";
500− local target="$prefix/share/systemd/user";
501− echo "moving $source/* to $target";
502− mkdir -p "$target";
503− ( shopt -s dotglob;
504− for i in "$source"/*;
505− do
506− mv "$i" "$target";
507− done );
508− rmdir "$source";
509− ln -s "$target" "$source"
510−}
511−_moveToShare ()
512−{
513−
514− if [ -n "$__structuredAttrs" ]; then
515− if [ -z "${forceShare-}" ]; then
516− forceShare=(man doc info);
517− fi;
518− else
519− forceShare=(${forceShare:-man doc info});
520− fi;
521− if [[ -z "$out" ]]; then
522− return;
523− fi;
524− for d in "${forceShare[@]}";
525− do
526− if [ -d "$out/$d" ]; then
527− if [ -d "$out/share/$d" ]; then
528− echo "both $d/ and share/$d/ exist!";
529− else
530− echo "moving $out/$d to $out/share/$d";
531− mkdir -p $out/share;
532− mv $out/$d $out/share/;
533− fi;
534− fi;
535− done
536−}
537−_multioutConfig ()
538−{
539−
540− if [ "$(getAllOutputNames)" = "out" ] || [ -z "${setOutputFlags-1}" ]; then
541− return;
542− fi;
543− if [ -z "${shareDocName:-}" ]; then
544− local confScript="${configureScript:-}";
545− if [ -z "$confScript" ] && [ -x ./configure ]; then
546− confScript=./configure;
547− fi;
548− if [ -f "$confScript" ]; then
549− local shareDocName="$(sed -n "s/^PACKAGE_TARNAME='\(.*\)'$/\1/p" < "$confScript")";
550− fi;
551− if [ -z "$shareDocName" ] || echo "$shareDocName" | grep -q '[^a-zA-Z0-9_-]'; then
552− shareDocName="$(echo "$name" | sed 's/-[^a-zA-Z].*//')";
553− fi;
554− fi;
555− prependToVar configureFlags --bindir="${!outputBin}"/bin --sbindir="${!outputBin}"/sbin --includedir="${!outputInclude}"/include --mandir="${!outputMan}"/share/man --infodir="${!outputInfo}"/share/info --docdir="${!outputDoc}"/share/doc/"${shareDocName}" --libdir="${!outputLib}"/lib --libexecdir="${!outputLib}"/libexec --localedir="${!outputLib}"/share/locale;
556− prependToVar installFlags pkgconfigdir="${!outputDev}"/lib/pkgconfig m4datadir="${!outputDev}"/share/aclocal aclocaldir="${!outputDev}"/share/aclocal
557−}
558−_multioutDevs ()
559−{
560−
561− if [ "$(getAllOutputNames)" = "out" ] || [ -z "${moveToDev-1}" ]; then
562− return;
563− fi;
564− moveToOutput include "${!outputInclude}";
565− moveToOutput lib/pkgconfig "${!outputDev}";
566− moveToOutput share/pkgconfig "${!outputDev}";
567− moveToOutput lib/cmake "${!outputDev}";
568− moveToOutput share/aclocal "${!outputDev}";
569− for f in "${!outputDev}"/{lib,share}/pkgconfig/*.pc;
570− do
571− echo "Patching '$f' includedir to output ${!outputInclude}";
572− sed -i "/^includedir=/s,=\${prefix},=${!outputInclude}," "$f";
573− done
574−}
575−_multioutDocs ()
576−{
577−
578− local REMOVE=REMOVE;
579− moveToOutput share/info "${!outputInfo}";
580− moveToOutput share/doc "${!outputDoc}";
581− moveToOutput share/gtk-doc "${!outputDevdoc}";
582− moveToOutput share/devhelp/books "${!outputDevdoc}";
583− moveToOutput share/man "${!outputMan}";
584− moveToOutput share/man/man3 "${!outputDevman}"
585−}
586−_multioutPropagateDev ()
587−{
588−
589− if [ "$(getAllOutputNames)" = "out" ]; then
590− return;
591− fi;
592− local outputFirst;
593− for outputFirst in $(getAllOutputNames);
594− do
595− break;
596− done;
597− local propagaterOutput="$outputDev";
598− if [ -z "$propagaterOutput" ]; then
599− propagaterOutput="$outputFirst";
600− fi;
601− if [ -z "${propagatedBuildOutputs+1}" ]; then
602− local po_dirty="$outputBin $outputInclude $outputLib";
603− set +o pipefail;
604− propagatedBuildOutputs=`echo "$po_dirty" | tr -s ' ' '\n' | grep -v -F "$propagaterOutput" | sort -u | tr '\n' ' ' `;
605− set -o pipefail;
606− fi;
607− if [ -z "$propagatedBuildOutputs" ]; then
608− return;
609− fi;
610− mkdir -p "${!propagaterOutput}"/nix-support;
611− for output in $propagatedBuildOutputs;
612− do
613− echo -n " ${!output}" >> "${!propagaterOutput}"/nix-support/propagated-build-inputs;
614− done
615−}
616−_nixLogWithLevel ()
617−{
618−
619− [[ -z ${NIX_LOG_FD-} || ${NIX_DEBUG:-0} -lt ${1:?} ]] && return 0;
620− local logLevel;
621− case "${1:?}" in
622− 0)
623− logLevel=ERROR
624− ;;
625− 1)
626− logLevel=WARN
627− ;;
628− 2)
629− logLevel=NOTICE
630− ;;
631− 3)
632− logLevel=INFO
633− ;;
634− 4)
635− logLevel=TALKATIVE
636− ;;
637− 5)
638− logLevel=CHATTY
639− ;;
640− 6)
641− logLevel=DEBUG
642− ;;
643− 7)
644− logLevel=VOMIT
645− ;;
646− *)
647− echo "_nixLogWithLevel: called with invalid log level: ${1:?}" >&"$NIX_LOG_FD";
648− return 1
649− ;;
650− esac;
651− local callerName="${FUNCNAME[2]}";
652− if [[ $callerName == "_callImplicitHook" ]]; then
653− callerName="${hookName:?}";
654− fi;
655− printf "%s: %s: %s\n" "$logLevel" "$callerName" "${2:?}" >&"$NIX_LOG_FD"
656−}
657−_overrideFirst ()
658−{
659−
660− if [ -z "${!1-}" ]; then
661− _assignFirst "$@";
662− fi
663−}
664−_pruneLibtoolFiles ()
665−{
666−
667− if [ "${dontPruneLibtoolFiles-}" ] || [ ! -e "$prefix" ]; then
668− return;
669− fi;
670− find "$prefix" -type f -name '*.la' -exec grep -q '^# Generated by .*libtool' {} \; -exec grep -q "^old_library=''" {} \; -exec sed -i {} -e "/^dependency_libs='[^']/ c dependency_libs='' #pruned" \;
671−}
672−_updateSourceDateEpochFromSourceRoot ()
673−{
674−
675− if [ -n "$sourceRoot" ]; then
676− updateSourceDateEpoch "$sourceRoot";
677− fi
678−}
679−activatePackage ()
680−{
681−
682− local pkg="$1";
683− local -r hostOffset="$2";
684− local -r targetOffset="$3";
685− (( hostOffset <= targetOffset )) || exit 1;
686− if [ -f "$pkg" ]; then
687− nixTalkativeLog "sourcing setup hook '$pkg'";
688− source "$pkg";
689− fi;
690− if [[ -z "${strictDeps-}" || "$hostOffset" -le -1 ]]; then
691− addToSearchPath _PATH "$pkg/bin";
692− fi;
693− if (( hostOffset <= -1 )); then
694− addToSearchPath _XDG_DATA_DIRS "$pkg/share";
695− fi;
696− if [[ "$hostOffset" -eq 0 && -d "$pkg/bin" ]]; then
697− addToSearchPath _HOST_PATH "$pkg/bin";
698− fi;
699− if [[ -f "$pkg/nix-support/setup-hook" ]]; then
700− nixTalkativeLog "sourcing setup hook '$pkg/nix-support/setup-hook'";
701− source "$pkg/nix-support/setup-hook";
702− fi
703−}
704−addEnvHooks ()
705−{
706−
707− local depHostOffset="$1";
708− shift;
709− local pkgHookVarsSlice="${pkgHookVarVars[$depHostOffset + 1]}[@]";
710− local pkgHookVar;
711− for pkgHookVar in "${!pkgHookVarsSlice}";
712− do
713− eval "${pkgHookVar}s"'+=("$@")';
714− done
715−}
716−addPkgToClassPath ()
717−{
718−
719− local jar;
720− for jar in $1/share/java/*.jar;
721− do
722− export CLASSPATH=''${CLASSPATH-}''${CLASSPATH:+:}''${jar};
723− done
724−}
725−addToSearchPath ()
726−{
727−
728− addToSearchPathWithCustomDelimiter ":" "$@"
729−}
730−addToSearchPathWithCustomDelimiter ()
731−{
732−
733− local delimiter="$1";
734− local varName="$2";
735− local dir="$3";
736− if [[ -d "$dir" && "${!varName:+${delimiter}${!varName}${delimiter}}" != *"${delimiter}${dir}${delimiter}"* ]]; then
737− export "${varName}=${!varName:+${!varName}${delimiter}}${dir}";
738− fi
739−}
740−appendToVar ()
741−{
742−
743− local -n nameref="$1";
744− local useArray type;
745− if [ -n "$__structuredAttrs" ]; then
746− useArray=true;
747− else
748− useArray=false;
749− fi;
750− if type=$(declare -p "$1" 2> /dev/null); then
751− case "${type#* }" in
752− -A*)
753− echo "appendToVar(): ERROR: trying to use appendToVar on an associative array, use variable+=([\"X\"]=\"Y\") instead." 1>&2;
754− return 1
755− ;;
756− -a*)
757− useArray=true
758− ;;
759− *)
760− useArray=false
761− ;;
762− esac;
763− fi;
764− shift;
765− if $useArray; then
766− nameref=(${nameref+"${nameref[@]}"} "$@");
767− else
768− nameref="${nameref-} $*";
769− fi
770−}
771−auditTmpdir ()
772−{
773−
774− local dir="$1";
775− [ -e "$dir" ] || return 0;
776− echo "checking for references to $TMPDIR/ in $dir...";
777− local tmpdir elf_fifo script_fifo;
778− tmpdir="$(mktemp -d)";
779− elf_fifo="$tmpdir/elf";
780− script_fifo="$tmpdir/script";
781− mkfifo "$elf_fifo" "$script_fifo";
782− ( find "$dir" -type f -not -path '*/.build-id/*' -print0 | while IFS= read -r -d '' file; do
783− if isELF "$file"; then
784− printf '%s\0' "$file" 1>&3;
785− else
786− if isScript "$file"; then
787− filename=${file##*/};
788− dir=${file%/*};
789− if [ -e "$dir/.$filename-wrapped" ]; then
790− printf '%s\0' "$file" 1>&4;
791− fi;
792− fi;
793− fi;
794− done;
795− exec 3>&- 4>&- ) 3> "$elf_fifo" 4> "$script_fifo" & ( xargs -0 -r -P "$NIX_BUILD_CORES" -n 1 sh -c '
796− if { printf :; patchelf --print-rpath "$1"; } | grep -q -F ":$TMPDIR/"; then
797− echo "RPATH of binary $1 contains a forbidden reference to $TMPDIR/"
798− exit 1
799− fi
800− ' _ < "$elf_fifo" ) & local pid_elf=$!;
801− local pid_script;
802− ( xargs -0 -r -P "$NIX_BUILD_CORES" -n 1 sh -c '
803− if grep -q -F "$TMPDIR/" "$1"; then
804− echo "wrapper script $1 contains a forbidden reference to $TMPDIR/"
805− exit 1
806− fi
807− ' _ < "$script_fifo" ) & local pid_script=$!;
808− wait "$pid_elf" || {
809− echo "Some binaries contain forbidden references to $TMPDIR/. Check the error above!";
810− exit 1
811− };
812− wait "$pid_script" || {
813− echo "Some scripts contain forbidden references to $TMPDIR/. Check the error above!";
814− exit 1
815− };
816− rm -r "$tmpdir"
817−}
818−bintoolsWrapper_addLDVars ()
819−{
820−
821− local role_post;
822− getHostRoleEnvHook;
823− if [[ -d "$1/lib64" && ! -L "$1/lib64" ]]; then
824− export NIX_LDFLAGS${role_post}+=" -L$1/lib64";
825− fi;
826− if [[ -d "$1/lib" ]]; then
827− local -a glob=($1/lib/lib*);
828− if [ "${#glob[*]}" -gt 0 ]; then
829− export NIX_LDFLAGS${role_post}+=" -L$1/lib";
830− fi;
831− fi
832−}
833−buildPhase ()
834−{
835−
836− runHook preBuild;
837− if [[ -z "${makeFlags-}" && -z "${makefile:-}" && ! ( -e Makefile || -e makefile || -e GNUmakefile ) ]]; then
838− echo "no Makefile or custom buildPhase, doing nothing";
839− else
840− foundMakefile=1;
841− local flagsArray=(${enableParallelBuilding:+-j${NIX_BUILD_CORES}} SHELL="$SHELL");
842− concatTo flagsArray makeFlags makeFlagsArray buildFlags buildFlagsArray;
843− echoCmd 'build flags' "${flagsArray[@]}";
844− make ${makefile:+-f $makefile} "${flagsArray[@]}";
845− unset flagsArray;
846− fi;
847− runHook postBuild
848−}
849−ccWrapper_addCVars ()
850−{
851−
852− local role_post;
853− getHostRoleEnvHook;
854− local found=;
855− if [ -d "$1/include" ]; then
856− export NIX_CFLAGS_COMPILE${role_post}+=" -isystem $1/include";
857− found=1;
858− fi;
859− if [ -d "$1/Library/Frameworks" ]; then
860− export NIX_CFLAGS_COMPILE${role_post}+=" -iframework $1/Library/Frameworks";
861− found=1;
862− fi;
863− if [[ -n "" && -n ${NIX_STORE:-} && -n $found ]]; then
864− local scrubbed="$NIX_STORE/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-${1#"$NIX_STORE"/*-}";
865− export NIX_CFLAGS_COMPILE${role_post}+=" -fmacro-prefix-map=$1=$scrubbed";
866− fi
867−}
868−checkPhase ()
869−{
870−
871− runHook preCheck;
872− if [[ -z "${foundMakefile:-}" ]]; then
873− echo "no Makefile or custom checkPhase, doing nothing";
874− runHook postCheck;
875− return;
876− fi;
877− if [[ -z "${checkTarget:-}" ]]; then
878− if make -n ${makefile:+-f $makefile} check > /dev/null 2>&1; then
879− checkTarget="check";
880− else
881− if make -n ${makefile:+-f $makefile} test > /dev/null 2>&1; then
882− checkTarget="test";
883− fi;
884− fi;
885− fi;
886− if [[ -z "${checkTarget:-}" ]]; then
887− echo "no check/test target in ${makefile:-Makefile}, doing nothing";
888− else
889− local flagsArray=(${enableParallelChecking:+-j${NIX_BUILD_CORES}} SHELL="$SHELL");
890− concatTo flagsArray makeFlags makeFlagsArray checkFlags=VERBOSE=y checkFlagsArray checkTarget;
891− echoCmd 'check flags' "${flagsArray[@]}";
892− make ${makefile:+-f $makefile} "${flagsArray[@]}";
893− unset flagsArray;
894− fi;
895− runHook postCheck
896−}
897−compressManPages ()
898−{
899−
900− local dir="$1";
901− if [ -L "$dir"/share ] || [ -L "$dir"/share/man ] || [ ! -d "$dir/share/man" ]; then
902− return;
903− fi;
904− echo "gzipping man pages under $dir/share/man/";
905− find "$dir"/share/man/ -type f -a '!' -regex '.*\.\(bz2\|gz\|xz\)$' -print0 | xargs -0 -n1 -P "$NIX_BUILD_CORES" gzip -n -f;
906− find "$dir"/share/man/ -type l -a '!' -regex '.*\.\(bz2\|gz\|xz\)$' -print0 | sort -z | while IFS= read -r -d '' f; do
907− local target;
908− target="$(readlink -f "$f")";
909− if [ -f "$target".gz ]; then
910− ln -sf "$target".gz "$f".gz && rm "$f";
911− fi;
912− done
913−}
914−concatStringsSep ()
915−{
916−
917− local sep="$1";
918− local name="$2";
919− local type oldifs;
920− if type=$(declare -p "$name" 2> /dev/null); then
921− local -n nameref="$name";
922− case "${type#* }" in
923− -A*)
924− echo "concatStringsSep(): ERROR: trying to use concatStringsSep on an associative array." 1>&2;
925− return 1
926− ;;
927− -a*)
928− local IFS="$(printf '\036')"
929− ;;
930− *)
931− local IFS=" "
932− ;;
933− esac;
934− local ifs_separated="${nameref[*]}";
935− echo -n "${ifs_separated//"$IFS"/"$sep"}";
936− fi
937−}
938−concatTo ()
939−{
940−
941− local -;
942− set -o noglob;
943− local -n targetref="$1";
944− shift;
945− local arg default name type;
946− for arg in "$@";
947− do
948− IFS="=" read -r name default <<< "$arg";
949− local -n nameref="$name";
950− if [[ -z "${nameref[*]}" && -n "$default" ]]; then
951− targetref+=("$default");
952− else
953− if type=$(declare -p "$name" 2> /dev/null); then
954− case "${type#* }" in
955− -A*)
956− echo "concatTo(): ERROR: trying to use concatTo on an associative array." 1>&2;
957− return 1
958− ;;
959− -a*)
960− targetref+=("${nameref[@]}")
961− ;;
962− *)
963− if [[ "$name" = *"Array" ]]; then
964− nixErrorLog "concatTo(): $name is not declared as array, treating as a singleton. This will become an error in future";
965− targetref+=(${nameref+"${nameref[@]}"});
966− else
967− targetref+=(${nameref-});
968− fi
969− ;;
970− esac;
971− fi;
972− fi;
973− done
974−}
975−configurePhase ()
976−{
977−
978− runHook preConfigure;
979− : "${configureScript=}";
980− if [[ -z "$configureScript" && -x ./configure ]]; then
981− configureScript=./configure;
982− fi;
983− if [ -z "${dontFixLibtool:-}" ]; then
984− export lt_cv_deplibs_check_method="${lt_cv_deplibs_check_method-pass_all}";
985− local i;
986− find . -iname "ltmain.sh" -print0 | while IFS='' read -r -d '' i; do
987− echo "fixing libtool script $i";
988− fixLibtool "$i";
989− done;
990− CONFIGURE_MTIME_REFERENCE=$(mktemp configure.mtime.reference.XXXXXX);
991− find . -executable -type f -name configure -exec grep -l 'GNU Libtool is free software; you can redistribute it and/or modify' {} \; -exec touch -r {} "$CONFIGURE_MTIME_REFERENCE" \; -exec sed -i s_/usr/bin/file_file_g {} \; -exec touch -r "$CONFIGURE_MTIME_REFERENCE" {} \;;
992− rm -f "$CONFIGURE_MTIME_REFERENCE";
993− fi;
994− if [[ -z "${dontAddPrefix:-}" && -n "$prefix" ]]; then
995− local -r prefixKeyOrDefault="${prefixKey:---prefix=}";
996− if [ "${prefixKeyOrDefault: -1}" = " " ]; then
997− prependToVar configureFlags "$prefix";
998− prependToVar configureFlags "${prefixKeyOrDefault::-1}";
999− else
1000− prependToVar configureFlags "$prefixKeyOrDefault$prefix";
1001− fi;
1002− fi;
1003− if [[ -f "$configureScript" ]]; then
1004− if [ -z "${dontAddDisableDepTrack:-}" ]; then
1005− if grep -q dependency-tracking "$configureScript"; then
1006− prependToVar configureFlags --disable-dependency-tracking;
1007− fi;
1008− fi;
1009− if [ -z "${dontDisableStatic:-}" ]; then
1010− if grep -q enable-static "$configureScript"; then
1011− prependToVar configureFlags --disable-static;
1012− fi;
1013− fi;
1014− if [ -z "${dontPatchShebangsInConfigure:-}" ]; then
1015− patchShebangs --build "$configureScript";
1016− fi;
1017− fi;
1018− if [ -n "$configureScript" ]; then
1019− local -a flagsArray;
1020− concatTo flagsArray configureFlags configureFlagsArray;
1021− echoCmd 'configure flags' "${flagsArray[@]}";
1022− $configureScript "${flagsArray[@]}";
1023− unset flagsArray;
1024− else
1025− echo "no configure script, doing nothing";
1026− fi;
1027− runHook postConfigure
1028−}
1029−consumeEntire ()
1030−{
1031−
1032− if IFS='' read -r -d '' "$1"; then
1033− echo "consumeEntire(): ERROR: Input null bytes, won't process" 1>&2;
1034− return 1;
1035− fi
1036−}
1037−definePhases ()
1038−{
1039−
1040− if [ -z "${phases[*]:-}" ]; then
1041− phases="${prePhases[*]:-} unpackPhase patchPhase ${preConfigurePhases[*]:-} configurePhase ${preBuildPhases[*]:-} buildPhase checkPhase ${preInstallPhases[*]:-} installPhase ${preFixupPhases[*]:-} fixupPhase installCheckPhase ${preDistPhases[*]:-} distPhase ${postPhases[*]:-}";
1042− fi
1043−}
1044−distPhase ()
1045−{
1046−
1047− runHook preDist;
1048− local flagsArray=();
1049− concatTo flagsArray distFlags distFlagsArray distTarget=dist;
1050− echo 'dist flags: %q' "${flagsArray[@]}";
1051− make ${makefile:+-f $makefile} "${flagsArray[@]}";
1052− if [ "${dontCopyDist:-0}" != 1 ]; then
1053− mkdir -p "$out/tarballs";
1054− cp -pvd ${tarballs[*]:-*.tar.gz} "$out/tarballs";
1055− fi;
1056− runHook postDist
1057−}
1058−dumpVars ()
1059−{
1060−
1061− if [[ "${noDumpEnvVars:-0}" != 1 && -d "$NIX_BUILD_TOP" ]]; then
1062− local old_umask;
1063− old_umask=$(umask);
1064− umask 0077;
1065− export 2> /dev/null > "$NIX_BUILD_TOP/env-vars";
1066− umask "$old_umask";
1067− fi
1068−}
1069−echoCmd ()
1070−{
1071−
1072− printf "%s:" "$1";
1073− shift;
1074− printf ' %q' "$@";
1075− echo
1076−}
1077−exitHandler ()
1078−{
1079−
1080− exitCode="$?";
1081− set +e;
1082− if [ -n "${showBuildStats:-}" ]; then
1083− read -r -d '' -a buildTimes < <(times);
1084− echo "build times:";
1085− echo "user time for the shell ${buildTimes[0]}";
1086− echo "system time for the shell ${buildTimes[1]}";
1087− echo "user time for all child processes ${buildTimes[2]}";
1088− echo "system time for all child processes ${buildTimes[3]}";
1089− fi;
1090− if (( "$exitCode" != 0 )); then
1091− runHook failureHook;
1092− if [ -n "${succeedOnFailure:-}" ]; then
1093− echo "build failed with exit code $exitCode (ignored)";
1094− mkdir -p "$out/nix-support";
1095− printf "%s" "$exitCode" > "$out/nix-support/failed";
1096− exit 0;
1097− fi;
1098− else
1099− runHook exitHook;
1100− fi;
1101− return "$exitCode"
1102−}
1103−findInputs ()
1104−{
1105−
1106− local -r pkg="$1";
1107− local -r hostOffset="$2";
1108− local -r targetOffset="$3";
1109− (( hostOffset <= targetOffset )) || exit 1;
1110− local varVar="${pkgAccumVarVars[hostOffset + 1]}";
1111− local varRef="$varVar[$((targetOffset - hostOffset))]";
1112− local var="${!varRef}";
1113− unset -v varVar varRef;
1114− local varSlice="$var[*]";
1115− case " ${!varSlice-} " in
1116− *" $pkg "*)
1117− return 0
1118− ;;
1119− esac;
1120− unset -v varSlice;
1121− eval "$var"'+=("$pkg")';
1122− if ! [ -e "$pkg" ]; then
1123− echo "build input $pkg does not exist" 1>&2;
1124− exit 1;
1125− fi;
1126− function mapOffset ()
1127− {
1128− local -r inputOffset="$1";
1129− local -n outputOffset="$2";
1130− if (( inputOffset <= 0 )); then
1131− outputOffset=$((inputOffset + hostOffset));
1132− else
1133− outputOffset=$((inputOffset - 1 + targetOffset));
1134− fi
1135− };
1136− local relHostOffset;
1137− for relHostOffset in "${allPlatOffsets[@]}";
1138− do
1139− local files="${propagatedDepFilesVars[relHostOffset + 1]}";
1140− local hostOffsetNext;
1141− mapOffset "$relHostOffset" hostOffsetNext;
1142− (( -1 <= hostOffsetNext && hostOffsetNext <= 1 )) || continue;
1143− local relTargetOffset;
1144− for relTargetOffset in "${allPlatOffsets[@]}";
1145− do
1146− (( "$relHostOffset" <= "$relTargetOffset" )) || continue;
1147− local fileRef="${files}[$relTargetOffset - $relHostOffset]";
1148− local file="${!fileRef}";
1149− unset -v fileRef;
1150− local targetOffsetNext;
1151− mapOffset "$relTargetOffset" targetOffsetNext;
1152− (( -1 <= hostOffsetNext && hostOffsetNext <= 1 )) || continue;
1153− [[ -f "$pkg/nix-support/$file" ]] || continue;
1154− local pkgNext;
1155− read -r -d '' pkgNext < "$pkg/nix-support/$file" || true;
1156− for pkgNext in $pkgNext;
1157− do
1158− findInputs "$pkgNext" "$hostOffsetNext" "$targetOffsetNext";
1159− done;
1160− done;
1161− done
1162−}
1163−fixLibtool ()
1164−{
1165−
1166− local search_path;
1167− for flag in $NIX_LDFLAGS;
1168− do
1169− case $flag in
1170− -L*)
1171− search_path+=" ${flag#-L}"
1172− ;;
1173− esac;
1174− done;
1175− sed -i "$1" -e "s^eval \(sys_lib_search_path=\).*^\1'${search_path:-}'^" -e 's^eval sys_lib_.+search_path=.*^^'
1176−}
1177−fixupPhase ()
1178−{
1179−
1180− local output;
1181− for output in $(getAllOutputNames);
1182− do
1183− if [ -e "${!output}" ]; then
1184− chmod -R u+w,u-s,g-s "${!output}";
1185− fi;
1186− done;
1187− runHook preFixup;
1188− local output;
1189− for output in $(getAllOutputNames);
1190− do
1191− prefix="${!output}" runHook fixupOutput;
1192− done;
1193− recordPropagatedDependencies;
1194− if [ -n "${setupHook:-}" ]; then
1195− mkdir -p "${!outputDev}/nix-support";
1196− substituteAll "$setupHook" "${!outputDev}/nix-support/setup-hook";
1197− fi;
1198− if [ -n "${setupHooks:-}" ]; then
1199− mkdir -p "${!outputDev}/nix-support";
1200− local hook;
1201− for hook in ${setupHooks[@]};
1202− do
1203− local content;
1204− consumeEntire content < "$hook";
1205− substituteAllStream content "file '$hook'" >> "${!outputDev}/nix-support/setup-hook";
1206− unset -v content;
1207− done;
1208− unset -v hook;
1209− fi;
1210− if [ -n "${propagatedUserEnvPkgs[*]:-}" ]; then
1211− mkdir -p "${!outputBin}/nix-support";
1212− printWords "${propagatedUserEnvPkgs[@]}" > "${!outputBin}/nix-support/propagated-user-env-packages";
1213− fi;
1214− runHook postFixup
1215−}
1216−genericBuild ()
1217−{
1218−
1219− export GZIP_NO_TIMESTAMPS=1;
1220− if [ -f "${buildCommandPath:-}" ]; then
1221− source "$buildCommandPath";
1222− return;
1223− fi;
1224− if [ -n "${buildCommand:-}" ]; then
1225− eval "$buildCommand";
1226− return;
1227− fi;
1228− definePhases;
1229− for curPhase in ${phases[*]};
1230− do
1231− runPhase "$curPhase";
1232− done
1233−}
1234−getAllOutputNames ()
1235−{
1236−
1237− if [ -n "$__structuredAttrs" ]; then
1238− echo "${!outputs[*]}";
1239− else
1240− echo "$outputs";
1241− fi
1242−}
1243−getHostRole ()
1244−{
1245−
1246− getRole "$hostOffset"
1247−}
1248−getHostRoleEnvHook ()
1249−{
1250−
1251− getRole "$depHostOffset"
1252−}
1253−getRole ()
1254−{
1255−
1256− case $1 in
1257− -1)
1258− role_post='_FOR_BUILD'
1259− ;;
1260− 0)
1261− role_post=''
1262− ;;
1263− 1)
1264− role_post='_FOR_TARGET'
1265− ;;
1266− *)
1267− echo "binutils-wrapper-2.46: used as improper sort of dependency" 1>&2;
1268− return 1
1269− ;;
1270− esac
1271−}
1272−getTargetRole ()
1273−{
1274−
1275− getRole "$targetOffset"
1276−}
1277−getTargetRoleEnvHook ()
1278−{
1279−
1280− getRole "$depTargetOffset"
1281−}
1282−getTargetRoleWrapper ()
1283−{
1284−
1285− case $targetOffset in
1286− -1)
1287− export NIX_BINTOOLS_WRAPPER_TARGET_BUILD_x86_64_unknown_linux_gnu=1
1288− ;;
1289− 0)
1290− export NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu=1
1291− ;;
1292− 1)
1293− export NIX_BINTOOLS_WRAPPER_TARGET_TARGET_x86_64_unknown_linux_gnu=1
1294− ;;
1295− *)
1296− echo "binutils-wrapper-2.46: used as improper sort of dependency" 1>&2;
1297− return 1
1298− ;;
1299− esac
1300−}
1301−gradle ()
1302−{
1303−
1304− local flagsArray=();
1305− concatTo flagsArray gradleFlags gradleFlagsArray;
1306− command gradle "${flagsArray[@]}" "$@"
1307−}
1308−gradleBuildPhase ()
1309−{
1310−
1311− runHook preBuild;
1312− gradle ${enableParallelBuilding:+--parallel} ${gradleBuildTask:-assemble};
1313− runHook postBuild
1314−}
1315−gradleCheckPhase ()
1316−{
1317−
1318− runHook preCheck;
1319− gradle ${enableParallelChecking:+--parallel} ${gradleCheckTask:-test};
1320− runHook postCheck
1321−}
1322−gradleConfigureHook ()
1323−{
1324−
1325− if [ -z "${GRADLE_USER_HOME-}" ]; then
1326− GRADLE_USER_HOME="$(mktemp -d)";
1327− fi;
1328− export GRADLE_USER_HOME;
1329− export TERM=dumb;
1330− gradleFlagsArray+=(--no-daemon -Dorg.gradle.console=plain --init-script "${gradleInitScript:-/nix/store/qyybvyq09wv36br9lfd8jac92fgwy8f2-init-build.gradle}");
1331− if [ -n "${MITM_CACHE_CA-}" ]; then
1332− if [ -z "${MITM_CACHE_KEYSTORE-}" ]; then
1333− MITM_CACHE_KEYSTORE="$MITM_CACHE_CERT_DIR/keystore";
1334− MITM_CACHE_KS_PWD="$(head -c10 /dev/random | base32)";
1335− echo y | /nix/store/vs2j17dr25ph3h1k4w1ngxnn8y5br1sa-openjdk-21.0.12+2/bin/keytool -importcert -file "$MITM_CACHE_CA" -alias alias -keystore "$MITM_CACHE_KEYSTORE" -storepass "$MITM_CACHE_KS_PWD";
1336− fi;
1337− gradleFlagsArray+=(-Dhttp.proxyHost="$MITM_CACHE_HOST" -Dhttp.proxyPort="$MITM_CACHE_PORT");
1338− gradleFlagsArray+=(-Dhttps.proxyHost="$MITM_CACHE_HOST" -Dhttps.proxyPort="$MITM_CACHE_PORT");
1339− gradleFlagsArray+=(-Djavax.net.ssl.trustStore="$MITM_CACHE_KEYSTORE" -Djavax.net.ssl.trustStorePassword="$MITM_CACHE_KS_PWD");
1340− else
1341− gradleFlagsArray+=(--offline);
1342− fi;
1343− if ! [[ -v enableParallelBuilding ]]; then
1344− enableParallelBuilding=1;
1345− fi;
1346− if ! [[ -v enableParallelChecking ]]; then
1347− enableParallelChecking=1;
1348− fi;
1349− if ! [[ -v enableParallelUpdating ]]; then
1350− enableParallelUpdating=1;
1351− fi
1352−}
1353−gradleUpdateScript ()
1354−{
1355−
1356− runHook preBuild;
1357− runHook preGradleUpdate;
1358− gradle ${enableParallelUpdating:+--parallel} ${gradleUpdateTask:-nixDownloadDeps};
1359− runHook postGradleUpdate
1360−}
1361−installCheckPhase ()
1362−{
1363−
1364− runHook preInstallCheck;
1365− if [[ -z "${foundMakefile:-}" ]]; then
1366− echo "no Makefile or custom installCheckPhase, doing nothing";
1367− else
1368− if [[ -z "${installCheckTarget:-}" ]] && ! make -n ${makefile:+-f $makefile} "${installCheckTarget:-installcheck}" > /dev/null 2>&1; then
1369− echo "no installcheck target in ${makefile:-Makefile}, doing nothing";
1370− else
1371− local flagsArray=(${enableParallelChecking:+-j${NIX_BUILD_CORES}} SHELL="$SHELL");
1372− concatTo flagsArray makeFlags makeFlagsArray installCheckFlags installCheckFlagsArray installCheckTarget=installcheck;
1373− echoCmd 'installcheck flags' "${flagsArray[@]}";
1374− make ${makefile:+-f $makefile} "${flagsArray[@]}";
1375− unset flagsArray;
1376− fi;
1377− fi;
1378− runHook postInstallCheck
1379−}
1380−installPhase ()
1381−{
1382−
1383− runHook preInstall;
1384− if [[ -z "${makeFlags-}" && -z "${makefile:-}" && ! ( -e Makefile || -e makefile || -e GNUmakefile ) ]]; then
1385− echo "no Makefile or custom installPhase, doing nothing";
1386− runHook postInstall;
1387− return;
1388− else
1389− foundMakefile=1;
1390− fi;
1391− if [ -n "$prefix" ]; then
1392− mkdir -p "$prefix";
1393− fi;
1394− local flagsArray=(${enableParallelInstalling:+-j${NIX_BUILD_CORES}} SHELL="$SHELL");
1395− concatTo flagsArray makeFlags makeFlagsArray installFlags installFlagsArray installTargets=install;
1396− echoCmd 'install flags' "${flagsArray[@]}";
1397− make ${makefile:+-f $makefile} "${flagsArray[@]}";
1398− unset flagsArray;
1399− runHook postInstall
1400−}
1401−isELF ()
1402−{
1403−
1404− local fn="$1";
1405− local fd;
1406− local magic;
1407− exec {fd}< "$fn";
1408− LANG=C read -r -n 4 -u "$fd" magic;
1409− exec {fd}>&-;
1410− if [ "$magic" = 'ELF' ]; then
1411− return 0;
1412− else
1413− return 1;
1414− fi
1415−}
1416−isMachO ()
1417−{
1418−
1419− local fn="$1";
1420− local fd;
1421− local magic;
1422− exec {fd}< "$fn";
1423− LANG=C read -r -n 4 -u "$fd" magic;
1424− exec {fd}>&-;
1425− if [[ "$magic" = $(echo -ne "\xfe\xed\xfa\xcf") || "$magic" = $(echo -ne "\xcf\xfa\xed\xfe") ]]; then
1426− return 0;
1427− else
1428− if [[ "$magic" = $(echo -ne "\xfe\xed\xfa\xce") || "$magic" = $(echo -ne "\xce\xfa\xed\xfe") ]]; then
1429− return 0;
1430− else
1431− if [[ "$magic" = $(echo -ne "\xca\xfe\xba\xbe") || "$magic" = $(echo -ne "\xbe\xba\xfe\xca") ]]; then
1432− return 0;
1433− else
1434− return 1;
1435− fi;
1436− fi;
1437− fi
1438−}
1439−isScript ()
1440−{
1441−
1442− local fn="$1";
1443− local fd;
1444− local magic;
1445− exec {fd}< "$fn";
1446− LANG=C read -r -n 2 -u "$fd" magic;
1447− exec {fd}>&-;
1448− if [[ "$magic" =~ \#! ]]; then
1449− return 0;
1450− else
1451− return 1;
1452− fi
1453−}
1454−mapOffset ()
1455−{
1456−
1457− local -r inputOffset="$1";
1458− local -n outputOffset="$2";
1459− if (( inputOffset <= 0 )); then
1460− outputOffset=$((inputOffset + hostOffset));
1461− else
1462− outputOffset=$((inputOffset - 1 + targetOffset));
1463− fi
1464−}
1465−mitmCacheConfigureHook ()
1466−{
1467−
1468− if [ -d "$mitmCache" ] && [ -z "$MITM_CACHE_CERT_DIR" ]; then
1469− MITM_CACHE_CERT_DIR="$(mktemp -d)";
1470− pushd "$MITM_CACHE_CERT_DIR";
1471− MITM_CACHE_CA="$MITM_CACHE_CERT_DIR/ca.cer";
1472− /nix/store/clvbx203wyqkdnqc5ngyhjlhcqn5s9x9-openssl-3.6.2-bin/bin/openssl genrsa -out ca.key 2048;
1473− /nix/store/clvbx203wyqkdnqc5ngyhjlhcqn5s9x9-openssl-3.6.2-bin/bin/openssl req -x509 -new -nodes -key ca.key -sha256 -days 1 -out ca.cer -subj "/C=AL/ST=a/L=a/O=a/OU=a/CN=example.org";
1474− MITM_CACHE_HOST="127.0.0.1";
1475− MITM_CACHE_PORT="${mitmCachePort:-$(/nix/store/ibdb2kp2gkqqbicwxp663s39sd5824zg-python3.13-ephemeral-port-reserve-1.1.4/bin/ephemeral-port-reserve "$MITM_CACHE_HOST")}";
1476− MITM_CACHE_ADDRESS="$MITM_CACHE_HOST:$MITM_CACHE_PORT";
1477− export http_proxy="$MITM_CACHE_ADDRESS";
1478− export https_proxy="$MITM_CACHE_ADDRESS";
1479− export SSL_CERT_FILE="$MITM_CACHE_CA";
1480− export NIX_SSL_CERT_FILE="$MITM_CACHE_CA";
1481− mitm-cache -l"$MITM_CACHE_ADDRESS" replay "$mitmCache" > /dev/null 2> /dev/null & popd;
1482− fi
1483−}
1484−moveToOutput ()
1485−{
1486−
1487− local patt="$1";
1488− local dstOut="$2";
1489− local output;
1490− for output in $(getAllOutputNames);
1491− do
1492− if [ "${!output}" = "$dstOut" ]; then
1493− continue;
1494− fi;
1495− local srcPath;
1496− for srcPath in "${!output}"/$patt;
1497− do
1498− if [ ! -e "$srcPath" ] && [ ! -L "$srcPath" ]; then
1499− continue;
1500− fi;
1501− if [ "$dstOut" = REMOVE ]; then
1502− echo "Removing $srcPath";
1503− rm -r "$srcPath";
1504− else
1505− local dstPath="$dstOut${srcPath#${!output}}";
1506− echo "Moving $srcPath to $dstPath";
1507− if [ -d "$dstPath" ] && [ -d "$srcPath" ]; then
1508− rmdir "$srcPath" --ignore-fail-on-non-empty;
1509− if [ -d "$srcPath" ]; then
1510− mv -t "$dstPath" "$srcPath"/*;
1511− rmdir "$srcPath";
1512− fi;
1513− else
1514− mkdir -p "$(readlink -m "$dstPath/..")";
1515− mv "$srcPath" "$dstPath";
1516− fi;
1517− fi;
1518− local srcParent="$(readlink -m "$srcPath/..")";
1519− if [ -n "$(find "$srcParent" -maxdepth 0 -type d -empty 2> /dev/null)" ]; then
1520− echo "Removing empty $srcParent/ and (possibly) its parents";
1521− rmdir -p --ignore-fail-on-non-empty "$srcParent" 2> /dev/null || true;
1522− fi;
1523− done;
1524− done
1525−}
1526−nixChattyLog ()
1527−{
1528−
1529− _nixLogWithLevel 5 "$*"
1530−}
1531−nixDebugLog ()
1532−{
1533−
1534− _nixLogWithLevel 6 "$*"
1535−}
1536−nixErrorLog ()
1537−{
1538−
1539− _nixLogWithLevel 0 "$*"
1540−}
1541−nixInfoLog ()
1542−{
1543−
1544− _nixLogWithLevel 3 "$*"
1545−}
1546−nixLog ()
1547−{
1548−
1549− [[ -z ${NIX_LOG_FD-} ]] && return 0;
1550− local callerName="${FUNCNAME[1]}";
1551− if [[ $callerName == "_callImplicitHook" ]]; then
1552− callerName="${hookName:?}";
1553− fi;
1554− printf "%s: %s\n" "$callerName" "$*" >&"$NIX_LOG_FD"
1555−}
1556−nixNoticeLog ()
1557−{
1558−
1559− _nixLogWithLevel 2 "$*"
1560−}
1561−nixTalkativeLog ()
1562−{
1563−
1564− _nixLogWithLevel 4 "$*"
1565−}
1566−nixVomitLog ()
1567−{
1568−
1569− _nixLogWithLevel 7 "$*"
1570−}
1571−nixWarnLog ()
1572−{
1573−
1574− _nixLogWithLevel 1 "$*"
1575−}
1576−noBrokenSymlinks ()
1577−{
1578−
1579− local -r output="${1:?}";
1580− local path;
1581− local pathParent;
1582− local symlinkTarget;
1583− local -i numDanglingSymlinks=0;
1584− local -i numReflexiveSymlinks=0;
1585− local -i numUnreadableSymlinks=0;
1586− if [[ ! -e $output ]]; then
1587− nixWarnLog "skipping non-existent output $output";
1588− return 0;
1589− fi;
1590− nixInfoLog "running on $output";
1591− while IFS= read -r -d '' path; do
1592− pathParent="$(dirname "$path")";
1593− if ! symlinkTarget="$(readlink "$path")"; then
1594− nixErrorLog "the symlink $path is unreadable";
1595− numUnreadableSymlinks+=1;
1596− continue;
1597− fi;
1598− if [[ $symlinkTarget == /* ]]; then
1599− nixInfoLog "symlink $path points to absolute target $symlinkTarget";
1600− else
1601− nixInfoLog "symlink $path points to relative target $symlinkTarget";
1602− symlinkTarget="$(realpath --no-symlinks --canonicalize-missing "$pathParent/$symlinkTarget")";
1603− fi;
1604− if [[ $symlinkTarget = "$TMPDIR"/* ]]; then
1605− nixErrorLog "the symlink $path points to $TMPDIR directory: $symlinkTarget";
1606− numDanglingSymlinks+=1;
1607− continue;
1608− fi;
1609− if [[ $symlinkTarget != "$NIX_STORE"/* ]]; then
1610− nixInfoLog "symlink $path points outside the Nix store; ignoring";
1611− continue;
1612− fi;
1613− if [[ $path == "$symlinkTarget" ]]; then
1614− nixErrorLog "the symlink $path is reflexive";
1615− numReflexiveSymlinks+=1;
1616− else
1617− if [[ ! -e $symlinkTarget ]]; then
1618− nixErrorLog "the symlink $path points to a missing target: $symlinkTarget";
1619− numDanglingSymlinks+=1;
1620− else
1621− nixDebugLog "the symlink $path is irreflexive and points to a target which exists";
1622− fi;
1623− fi;
1624− done < <(find "$output" -type l -print0);
1625− if ((numDanglingSymlinks > 0 || numReflexiveSymlinks > 0 || numUnreadableSymlinks > 0)); then
1626− nixErrorLog "found $numDanglingSymlinks dangling symlinks, $numReflexiveSymlinks reflexive symlinks and $numUnreadableSymlinks unreadable symlinks";
1627− exit 1;
1628− fi;
1629− return 0
1630−}
1631−noBrokenSymlinksInAllOutputs ()
1632−{
1633−
1634− if [[ -z ${dontCheckForBrokenSymlinks-} ]]; then
1635− for output in $(getAllOutputNames);
1636− do
1637− noBrokenSymlinks "${!output}";
1638− done;
1639− fi
1640−}
1641−patchELF ()
1642−{
1643−
1644− local dir="$1";
1645− [ -e "$dir" ] || return 0;
1646− echo "shrinking RPATHs of ELF executables and libraries in $dir";
1647− local i;
1648− while IFS= read -r -d '' i; do
1649− if [[ "$i" =~ .build-id ]]; then
1650− continue;
1651− fi;
1652− if ! isELF "$i"; then
1653− continue;
1654− fi;
1655− echo "shrinking $i";
1656− patchelf --shrink-rpath "$i" || true;
1657− done < <(find "$dir" -type f -print0)
1658−}
1659−patchPhase ()
1660−{
1661−
1662− runHook prePatch;
1663− local -a patchesArray;
1664− concatTo patchesArray patches;
1665− local -a flagsArray;
1666− concatTo flagsArray patchFlags=-p1;
1667− for i in "${patchesArray[@]}";
1668− do
1669− echo "applying patch $i";
1670− local uncompress=cat;
1671− case "$i" in
1672− *.gz)
1673− uncompress="gzip -d"
1674− ;;
1675− *.bz2)
1676− uncompress="bzip2 -d"
1677− ;;
1678− *.xz)
1679− uncompress="xz -d"
1680− ;;
1681− *.lzma)
1682− uncompress="lzma -d"
1683− ;;
1684− esac;
1685− $uncompress < "$i" 2>&1 | patch "${flagsArray[@]}";
1686− done;
1687− runHook postPatch
1688−}
1689−patchShebangs ()
1690−{
1691−
1692− local pathName;
1693− local update=false;
1694− while [[ $# -gt 0 ]]; do
1695− case "$1" in
1696− --host)
1697− pathName=HOST_PATH;
1698− shift
1699− ;;
1700− --build)
1701− pathName=PATH;
1702− shift
1703− ;;
1704− --update)
1705− update=true;
1706− shift
1707− ;;
1708− --)
1709− shift;
1710− break
1711− ;;
1712− -* | --*)
1713− echo "Unknown option $1 supplied to patchShebangs" 1>&2;
1714− return 1
1715− ;;
1716− *)
1717− break
1718− ;;
1719− esac;
1720− done;
1721− echo "patching script interpreter paths in $@";
1722− local f;
1723− local oldPath;
1724− local newPath;
1725− local arg0;
1726− local args;
1727− local oldInterpreterLine;
1728− local newInterpreterLine;
1729− if [[ $# -eq 0 ]]; then
1730− echo "No arguments supplied to patchShebangs" 1>&2;
1731− return 0;
1732− fi;
1733− local f;
1734− while IFS= read -r -d '' f; do
1735− isScript "$f" || continue;
1736− read -r oldInterpreterLine < "$f" || [ "$oldInterpreterLine" ];
1737− read -r oldPath arg0 args <<< "${oldInterpreterLine:2}";
1738− if [[ -z "${pathName:-}" ]]; then
1739− if [[ -n $strictDeps && $f == "$NIX_STORE"* ]]; then
1740− pathName=HOST_PATH;
1741− else
1742− pathName=PATH;
1743− fi;
1744− fi;
1745− if [[ "$oldPath" == *"/bin/env" ]]; then
1746− if [[ $arg0 == "-S" ]]; then
1747− arg0=${args%% *};
1748− [[ "$args" == *" "* ]] && args=${args#* } || args=;
1749− newPath="$(PATH="${!pathName}" type -P "env" || true)";
1750− args="-S $(PATH="${!pathName}" type -P "$arg0" || true) $args";
1751− else
1752− if [[ $arg0 == "-"* || $arg0 == *"="* ]]; then
1753− echo "$f: unsupported interpreter directive \"$oldInterpreterLine\" (set dontPatchShebangs=1 and handle shebang patching yourself)" 1>&2;
1754− exit 1;
1755− else
1756− newPath="$(PATH="${!pathName}" type -P "$arg0" || true)";
1757− fi;
1758− fi;
1759− else
1760− if [[ -z $oldPath ]]; then
1761− oldPath="/bin/sh";
1762− fi;
1763− newPath="$(PATH="${!pathName}" type -P "$(basename "$oldPath")" || true)";
1764− args="$arg0 $args";
1765− fi;
1766− newInterpreterLine="$newPath $args";
1767− newInterpreterLine=${newInterpreterLine%${newInterpreterLine##*[![:space:]]}};
1768− if [[ -n "$oldPath" && ( "$update" == true || "${oldPath:0:${#NIX_STORE}}" != "$NIX_STORE" ) ]]; then
1769− if [[ -n "$newPath" && "$newPath" != "$oldPath" ]]; then
1770− echo "$f: interpreter directive changed from \"$oldInterpreterLine\" to \"$newInterpreterLine\"";
1771− escapedInterpreterLine=${newInterpreterLine//\\/\\\\};
1772− timestamp=$(stat --printf "%y" "$f");
1773− tmpFile=$(mktemp -t patchShebangs.XXXXXXXXXX);
1774− sed -e "1 s|.*|#\!$escapedInterpreterLine|" "$f" > "$tmpFile";
1775− local restoreReadOnly;
1776− if [[ ! -w "$f" ]]; then
1777− chmod +w "$f";
1778− restoreReadOnly=true;
1779− fi;
1780− cat "$tmpFile" > "$f";
1781− rm "$tmpFile";
1782− if [[ -n "${restoreReadOnly:-}" ]]; then
1783− chmod -w "$f";
1784− fi;
1785− touch --date "$timestamp" "$f";
1786− fi;
1787− fi;
1788− done < <(find "$@" -type f -perm -0100 -print0)
1789−}
1790−patchShebangsAuto ()
1791−{
1792−
1793− if [[ -z "${dontPatchShebangs-}" && -e "$prefix" ]]; then
1794− if [[ "$output" != out && "$output" = "$outputDev" ]]; then
1795− patchShebangs --build "$prefix";
1796− else
1797− patchShebangs --host "$prefix";
1798− fi;
1799− fi
1800−}
1801−prependToVar ()
1802−{
1803−
1804− local -n nameref="$1";
1805− local useArray type;
1806− if [ -n "$__structuredAttrs" ]; then
1807− useArray=true;
1808− else
1809− useArray=false;
1810− fi;
1811− if type=$(declare -p "$1" 2> /dev/null); then
1812− case "${type#* }" in
1813− -A*)
1814− echo "prependToVar(): ERROR: trying to use prependToVar on an associative array." 1>&2;
1815− return 1
1816− ;;
1817− -a*)
1818− useArray=true
1819− ;;
1820− *)
1821− useArray=false
1822− ;;
1823− esac;
1824− fi;
1825− shift;
1826− if $useArray; then
1827− nameref=("$@" ${nameref+"${nameref[@]}"});
1828− else
1829− nameref="$* ${nameref-}";
1830− fi
1831−}
1832−printLines ()
1833−{
1834−
1835− (( "$#" > 0 )) || return 0;
1836− printf '%s\n' "$@"
1837−}
1838−printPhases ()
1839−{
1840−
1841− definePhases;
1842− local phase;
1843− for phase in ${phases[*]};
1844− do
1845− printf '%s\n' "$phase";
1846− done
1847−}
1848−printWords ()
1849−{
1850−
1851− (( "$#" > 0 )) || return 0;
1852− printf '%s ' "$@"
1853−}
1854−recordPropagatedDependencies ()
1855−{
1856−
1857− declare -ra flatVars=(depsBuildBuildPropagated propagatedNativeBuildInputs depsBuildTargetPropagated depsHostHostPropagated propagatedBuildInputs depsTargetTargetPropagated);
1858− declare -ra flatFiles=("${propagatedBuildDepFiles[@]}" "${propagatedHostDepFiles[@]}" "${propagatedTargetDepFiles[@]}");
1859− local propagatedInputsIndex;
1860− for propagatedInputsIndex in "${!flatVars[@]}";
1861− do
1862− local propagatedInputsSlice="${flatVars[$propagatedInputsIndex]}[@]";
1863− local propagatedInputsFile="${flatFiles[$propagatedInputsIndex]}";
1864− [[ -n "${!propagatedInputsSlice}" ]] || continue;
1865− mkdir -p "${!outputDev}/nix-support";
1866− printWords ${!propagatedInputsSlice} > "${!outputDev}/nix-support/$propagatedInputsFile";
1867− done
1868−}
1869−runHook ()
1870−{
1871−
1872− local hookName="$1";
1873− shift;
1874− local hooksSlice="${hookName%Hook}Hooks[@]";
1875− local hook;
1876− for hook in "_callImplicitHook 0 $hookName" ${!hooksSlice+"${!hooksSlice}"};
1877− do
1878− _logHook "$hookName" "$hook" "$@";
1879− _eval "$hook" "$@";
1880− done;
1881− return 0
1882−}
1883−runOneHook ()
1884−{
1885−
1886− local hookName="$1";
1887− shift;
1888− local hooksSlice="${hookName%Hook}Hooks[@]";
1889− local hook ret=1;
1890− for hook in "_callImplicitHook 1 $hookName" ${!hooksSlice+"${!hooksSlice}"};
1891− do
1892− _logHook "$hookName" "$hook" "$@";
1893− if _eval "$hook" "$@"; then
1894− ret=0;
1895− break;
1896− fi;
1897− done;
1898− return "$ret"
1899−}
1900−runPhase ()
1901−{
1902−
1903− local curPhase="$*";
1904− if [[ "$curPhase" = unpackPhase && -n "${dontUnpack:-}" ]]; then
1905− return;
1906− fi;
1907− if [[ "$curPhase" = patchPhase && -n "${dontPatch:-}" ]]; then
1908− return;
1909− fi;
1910− if [[ "$curPhase" = configurePhase && -n "${dontConfigure:-}" ]]; then
1911− return;
1912− fi;
1913− if [[ "$curPhase" = buildPhase && -n "${dontBuild:-}" ]]; then
1914− return;
1915− fi;
1916− if [[ "$curPhase" = checkPhase && -z "${doCheck:-}" ]]; then
1917− return;
1918− fi;
1919− if [[ "$curPhase" = installPhase && -n "${dontInstall:-}" ]]; then
1920− return;
1921− fi;
1922− if [[ "$curPhase" = fixupPhase && -n "${dontFixup:-}" ]]; then
1923− return;
1924− fi;
1925− if [[ "$curPhase" = installCheckPhase && -z "${doInstallCheck:-}" ]]; then
1926− return;
1927− fi;
1928− if [[ "$curPhase" = distPhase && -z "${doDist:-}" ]]; then
1929− return;
1930− fi;
1931− showPhaseHeader "$curPhase";
1932− dumpVars;
1933− local startTime endTime;
1934− startTime=$(date +"%s");
1935− eval "${!curPhase:-$curPhase}";
1936− endTime=$(date +"%s");
1937− showPhaseFooter "$curPhase" "$startTime" "$endTime";
1938− if [ "$curPhase" = unpackPhase ]; then
1939− [ -n "${sourceRoot:-}" ] && chmod +x -- "${sourceRoot}";
1940− cd -- "${sourceRoot:-.}";
1941− fi
1942−}
1943−showPhaseFooter ()
1944−{
1945−
1946− local phase="$1";
1947− local startTime="$2";
1948− local endTime="$3";
1949− local delta=$(( endTime - startTime ));
1950− (( delta < 30 )) && return;
1951− local H=$((delta/3600));
1952− local M=$((delta%3600/60));
1953− local S=$((delta%60));
1954− echo -n "$phase completed in ";
1955− (( H > 0 )) && echo -n "$H hours ";
1956− (( M > 0 )) && echo -n "$M minutes ";
1957− echo "$S seconds"
1958−}
1959−showPhaseHeader ()
1960−{
1961−
1962− local phase="$1";
1963− echo "Running phase: $phase";
1964− if [[ -z ${NIX_LOG_FD-} ]]; then
1965− return;
1966− fi;
1967− printf "@nix { \"action\": \"setPhase\", \"phase\": \"%s\" }\n" "$phase" >&"$NIX_LOG_FD"
1968−}
1969−stripDirs ()
1970−{
1971−
1972− local cmd="$1";
1973− local ranlibCmd="$2";
1974− local paths="$3";
1975− local stripFlags="$4";
1976− local excludeFlags=();
1977− local pathsNew=;
1978− [ -z "$cmd" ] && echo "stripDirs: Strip command is empty" 1>&2 && exit 1;
1979− [ -z "$ranlibCmd" ] && echo "stripDirs: Ranlib command is empty" 1>&2 && exit 1;
1980− local pattern;
1981− if [ -n "${stripExclude:-}" ]; then
1982− for pattern in "${stripExclude[@]}";
1983− do
1984− excludeFlags+=(-a '!' '(' -name "$pattern" -o -wholename "$prefix/$pattern" ')');
1985− done;
1986− fi;
1987− local p;
1988− for p in ${paths};
1989− do
1990− if [ -e "$prefix/$p" ]; then
1991− pathsNew="${pathsNew} $prefix/$p";
1992− fi;
1993− done;
1994− paths=${pathsNew};
1995− if [ -n "${paths}" ]; then
1996− echo "stripping (with command $cmd and flags $stripFlags) in $paths";
1997− local striperr;
1998− striperr="$(mktemp --tmpdir="$TMPDIR" 'striperr.XXXXXX')";
1999− find $paths -type f "${excludeFlags[@]}" -a '!' -path "$prefix/lib/debug/*" -printf '%D-%i,%p\0' | sort -t, -k1,1 -u -z | cut -d, -f2- -z | xargs -r -0 -n1 -P "$NIX_BUILD_CORES" -- $cmd $stripFlags 2> "$striperr" || exit_code=$?;
2000− [[ "$exit_code" = 123 || -z "$exit_code" ]] || ( cat "$striperr" 1>&2 && exit 1 );
2001− rm "$striperr";
2002− find $paths -name '*.a' -type f -exec $ranlibCmd '{}' \; 2> /dev/null;
2003− fi
2004−}
2005−stripHash ()
2006−{
2007−
2008− local strippedName casematchOpt=0;
2009− strippedName="$(basename -- "$1")";
2010− shopt -q nocasematch && casematchOpt=1;
2011− shopt -u nocasematch;
2012− if [[ "$strippedName" =~ ^[a-z0-9]{32}- ]]; then
2013− echo "${strippedName:33}";
2014− else
2015− echo "$strippedName";
2016− fi;
2017− if (( casematchOpt )); then
2018− shopt -s nocasematch;
2019− fi
2020−}
2021−substitute ()
2022−{
2023−
2024− local input="$1";
2025− local output="$2";
2026− shift 2;
2027− if [ ! -f "$input" ]; then
2028− echo "substitute(): ERROR: file '$input' does not exist" 1>&2;
2029− return 1;
2030− fi;
2031− local content;
2032− consumeEntire content < "$input";
2033− if [ -e "$output" ]; then
2034− chmod +w "$output";
2035− fi;
2036− substituteStream content "file '$input'" "$@" > "$output"
2037−}
2038−substituteAll ()
2039−{
2040−
2041− local input="$1";
2042− local output="$2";
2043− local -a args=();
2044− _allFlags;
2045− substitute "$input" "$output" "${args[@]}"
2046−}
2047−substituteAllInPlace ()
2048−{
2049−
2050− local fileName="$1";
2051− shift;
2052− substituteAll "$fileName" "$fileName" "$@"
2053−}
2054−substituteAllStream ()
2055−{
2056−
2057− local -a args=();
2058− _allFlags;
2059− substituteStream "$1" "$2" "${args[@]}"
2060−}
2061−substituteInPlace ()
2062−{
2063−
2064− local -a fileNames=();
2065− for arg in "$@";
2066− do
2067− if [[ "$arg" = "--"* ]]; then
2068− break;
2069− fi;
2070− fileNames+=("$arg");
2071− shift;
2072− done;
2073− if ! [[ "${#fileNames[@]}" -gt 0 ]]; then
2074− echo "substituteInPlace called without any files to operate on (files must come before options!)" 1>&2;
2075− return 1;
2076− fi;
2077− for file in "${fileNames[@]}";
2078− do
2079− substitute "$file" "$file" "$@";
2080− done
2081−}
2082−substituteStream ()
2083−{
2084−
2085− local var=$1;
2086− local description=$2;
2087− shift 2;
2088− while (( "$#" )); do
2089− local replace_mode="$1";
2090− case "$1" in
2091− --replace)
2092− if ! "$_substituteStream_has_warned_replace_deprecation"; then
2093− echo "substituteStream() in derivation $name: WARNING: '--replace' is deprecated, use --replace-{fail,warn,quiet}. ($description)" 1>&2;
2094− _substituteStream_has_warned_replace_deprecation=true;
2095− fi;
2096− replace_mode='--replace-warn'
2097− ;&
2098− --replace-quiet | --replace-warn | --replace-fail)
2099− pattern="$2";
2100− replacement="$3";
2101− shift 3;
2102− if ! [[ "${!var}" == *"$pattern"* ]]; then
2103− if [ "$replace_mode" == --replace-warn ]; then
2104− printf "substituteStream() in derivation $name: WARNING: pattern %q doesn't match anything in %s\n" "$pattern" "$description" 1>&2;
2105− else
2106− if [ "$replace_mode" == --replace-fail ]; then
2107− printf "substituteStream() in derivation $name: ERROR: pattern %q doesn't match anything in %s\n" "$pattern" "$description" 1>&2;
2108− return 1;
2109− fi;
2110− fi;
2111− fi;
2112− eval "$var"'=${'"$var"'//"$pattern"/"$replacement"}'
2113− ;;
2114− --subst-var)
2115− local varName="$2";
2116− shift 2;
2117− if ! [[ "$varName" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
2118− echo "substituteStream() in derivation $name: ERROR: substitution variables must be valid Bash names, \"$varName\" isn't." 1>&2;
2119− return 1;
2120− fi;
2121− if [ -z ${!varName+x} ]; then
2122− echo "substituteStream() in derivation $name: ERROR: variable \$$varName is unset" 1>&2;
2123− return 1;
2124− fi;
2125− pattern="@$varName@";
2126− replacement="${!varName}";
2127− eval "$var"'=${'"$var"'//"$pattern"/"$replacement"}'
2128− ;;
2129− --subst-var-by)
2130− pattern="@$2@";
2131− replacement="$3";
2132− eval "$var"'=${'"$var"'//"$pattern"/"$replacement"}';
2133− shift 3
2134− ;;
2135− *)
2136− echo "substituteStream() in derivation $name: ERROR: Invalid command line argument: $1" 1>&2;
2137− return 1
2138− ;;
2139− esac;
2140− done;
2141− printf "%s" "${!var}"
2142−}
2143−unpackFile ()
2144−{
2145−
2146− curSrc="$1";
2147− echo "unpacking source archive $curSrc";
2148− if ! runOneHook unpackCmd "$curSrc"; then
2149− echo "do not know how to unpack source archive $curSrc";
2150− exit 1;
2151− fi
2152−}
2153−unpackPhase ()
2154−{
2155−
2156− runHook preUnpack;
2157− if [ -z "${srcs:-}" ]; then
2158− if [ -z "${src:-}" ]; then
2159− echo 'variable $src or $srcs should point to the source';
2160− exit 1;
2161− fi;
2162− srcs="$src";
2163− fi;
2164− local -a srcsArray;
2165− concatTo srcsArray srcs;
2166− local dirsBefore="";
2167− for i in *;
2168− do
2169− if [ -d "$i" ]; then
2170− dirsBefore="$dirsBefore $i ";
2171− fi;
2172− done;
2173− for i in "${srcsArray[@]}";
2174− do
2175− unpackFile "$i";
2176− done;
2177− : "${sourceRoot=}";
2178− if [ -n "${setSourceRoot:-}" ]; then
2179− runOneHook setSourceRoot;
2180− else
2181− if [ -z "$sourceRoot" ]; then
2182− for i in *;
2183− do
2184− if [ -d "$i" ]; then
2185− case $dirsBefore in
2186− *\ $i\ *)
2187−
2188− ;;
2189− *)
2190− if [ -n "$sourceRoot" ]; then
2191− echo "unpacker produced multiple directories";
2192− exit 1;
2193− fi;
2194− sourceRoot="$i"
2195− ;;
2196− esac;
2197− fi;
2198− done;
2199− fi;
2200− fi;
2201− if [ -z "$sourceRoot" ]; then
2202− echo "unpacker appears to have produced no directories";
2203− exit 1;
2204− fi;
2205− echo "source root is $sourceRoot";
2206− if [ "${dontMakeSourcesWritable:-0}" != 1 ]; then
2207− chmod -R u+w -- "$sourceRoot";
2208− fi;
2209− runHook postUnpack
2210−}
2211−updateAutotoolsGnuConfigScriptsPhase ()
2212−{
2213−
2214− if [ -n "${dontUpdateAutotoolsGnuConfigScripts-}" ]; then
2215− return;
2216− fi;
2217− for script in config.sub config.guess;
2218− do
2219− for f in $(find . -type f -name "$script");
2220− do
2221− echo "Updating Autotools / GNU config script to a newer upstream version: $f";
2222− cp -f "/nix/store/4i7gvqwiq5mbl5pxh43frzq2nibxvwb5-gnu-config-2024-01-01/$script" "$f";
2223− done;
2224− done
2225−}
2226−updateSourceDateEpoch ()
2227−{
2228−
2229− local path="$1";
2230− [[ $path == -* ]] && path="./$path";
2231− local -a res=($(find "$path" -type f -not -newer "$NIX_BUILD_TOP/.." -printf '%T@ "%p"\0' | sort -n --zero-terminated | tail -n1 --zero-terminated | head -c -1));
2232− local time="${res[0]//\.[0-9]*/}";
2233− local newestFile="${res[1]}";
2234− if [ "${time:-0}" -gt "$SOURCE_DATE_EPOCH" ]; then
2235− echo "setting SOURCE_DATE_EPOCH to timestamp $time of file $newestFile";
2236− export SOURCE_DATE_EPOCH="$time";
2237− local now="$(date +%s)";
2238− if [ "$time" -gt $((now - 60)) ]; then
2239− echo "warning: file $newestFile may be generated; SOURCE_DATE_EPOCH may be non-deterministic";
2240− fi;
2241− fi
2242−}
2243−PATH="$PATH${nix_saved_PATH:+:$nix_saved_PATH}"
2244−XDG_DATA_DIRS="$XDG_DATA_DIRS${nix_saved_XDG_DATA_DIRS:+:$nix_saved_XDG_DATA_DIRS}"
2245−export NIX_BUILD_TOP="$(mktemp -d -t nix-shell.XXXXXX)"
2246−export TMP="$NIX_BUILD_TOP"
2247−export TMPDIR="$NIX_BUILD_TOP"
2248−export TEMP="$NIX_BUILD_TOP"
2249−export TEMPDIR="$NIX_BUILD_TOP"
2250−eval "${shellHook:-}"
.github/workflows/build.yml+12−28
@@ -12,7 +12,19 @@ concurrency:
1212 cancel-in-progress: true
1313
1414jobs:
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+
1526 build:
27+ name: Android app
1628 runs-on: ubuntu-latest
1729
1830 steps:
@@ -30,43 +42,15 @@ jobs:
3042 - name: Run unit tests
3143 run: ./gradlew testDebugUnitTest --no-daemon
3244
33− - name: Static analysis (detekt)
34− run: ./gradlew detekt --no-daemon
35−
3645 - name: Lint
3746 run: ./gradlew lintDebug --no-daemon
3847
3948 - name: Build debug APK
4049 run: ./gradlew assembleDebug --no-daemon
4150
42− - name: Decode release keystore
43− run: |
44− mkdir -p keystore
45− printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > keystore/opencode-release.jks
46− env:
47− OPENCODE_STORE_BASE64: ${{ secrets.OPENCODE_STORE_BASE64 }}
48−
49− - name: Build release APK
50− env:
51− OPENCODE_STORE_FILE: ${{ github.workspace }}/keystore/opencode-release.jks
52− OPENCODE_STORE_PASSWORD: ${{ secrets.OPENCODE_STORE_PASSWORD }}
53− OPENCODE_KEY_ALIAS: ${{ secrets.OPENCODE_KEY_ALIAS }}
54− OPENCODE_KEY_PASSWORD: ${{ secrets.OPENCODE_KEY_PASSWORD }}
55− run: ./gradlew assembleRelease --no-daemon
56−
5751 - name: Upload debug APK
5852 uses: actions/upload-artifact@v4
5953 with:
6054 name: opencode-debug.apk
6155 path: app/build/outputs/apk/debug/*.apk
6256 if-no-files-found: error
63−
64− # The release output dir is `release/` when unsigned but `release-signed/` (or a
65− # variant name) once a signing config is applied. Match both so CI keeps working
66− # once the OPENCODE_STORE_* secrets are wired up.
67− - name: Upload release APK
68− uses: actions/upload-artifact@v4
69− with:
70− name: opencode-release.apk
71− path: app/build/outputs/apk/**/*.apk
72− if-no-files-found: error
.github/workflows/release.yml+53−36
@@ -1,17 +1,28 @@
11name: Release
22
3−# Build the production (release) APK and publish a GitHub Release for every
4−# commit that lands on master. The version -- and the git tag / release name --
5−# is derived from the commit's committer date in UTC, formatted as
6−# YYYY.MM.DD.HHMM (e.g. 2026.07.04.1430). It is passed to the Gradle build as
7−# `-PversionName=...` so it is stamped into the APK and surfaces in-app.
3+# Build a minified, signed release APK and publish it as a GitHub Release.
4+#
5+# Runs automatically on every push to `master` (e.g. a merged PR), on a pushed
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
17+# is passed to Gradle as `-PversionName/-PversionCode` and stamped into the APK.
818on:
919 push:
1020 branches: [master]
21+ tags: ["v*"]
22+ workflow_dispatch:
1123
12−# A release run should never be aborted mid-flight by a newer push (a
13−# half-published release with a missing artifact is worse than a slightly stale
14−# one), so the group is per-ref but cancel-in-progress is left off.
24+# Never abort a release mid-flight — a half-published release with a missing
25+# artifact is worse than a slightly delayed one.
1526concurrency:
1627 group: ${{ github.workflow }}-${{ github.ref }}
1728 cancel-in-progress: false
@@ -20,9 +31,14 @@ jobs:
2031 release:
2132 runs-on: ubuntu-latest
2233 permissions:
23− contents: write # required to push the tag and create the release
24− id-token: write # required for OIDC so GitHub can sign the attestation
25− attestations: write # required to publish the attestation record
34+ contents: write # push the tag and create the release
35+ id-token: write # OIDC so GitHub can sign the provenance attestation
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 }}
2642 steps:
2743 - uses: actions/checkout@v4
2844 with:
@@ -30,12 +46,23 @@ jobs:
3046 # accurate instead of collapsing to 1 on a shallow clone.
3147 fetch-depth: 0
3248
33− - name: Compute version from commit date
49+ - name: Compute version
3450 id: version
3551 run: |
36− VERSION="$(TZ=UTC git log -1 --format=%cd --date=format-local:%Y.%m.%d.%H%M)"
37− echo "version=$VERSION" >> "$GITHUB_OUTPUT"
38− echo "Version: $VERSION"
52+ if [ "${{ github.ref_type }}" = "tag" ]; then
53+ VERSION="${GITHUB_REF_NAME#v}"
54+ TAG="${GITHUB_REF_NAME}"
55+ else
56+ VERSION="$(TZ=UTC date +%Y.%m.%d.%H%M)"
57+ TAG="v${VERSION}"
58+ fi
59+ CODE="$(git rev-list --count HEAD)"
60+ {
61+ echo "version=$VERSION"
62+ echo "tag=$TAG"
63+ echo "code=$CODE"
64+ } >> "$GITHUB_OUTPUT"
65+ echo "Releasing $TAG (version $VERSION, code $CODE)"
3966
4067 - uses: actions/setup-java@v4
4168 with:
@@ -47,40 +74,30 @@ jobs:
4774 - uses: gradle/actions/setup-gradle@v4
4875
4976 # The keystore ships as base64 in a secret so it never touches the repo.
50− # When the secret isn't configured the Gradle build falls back to an
51− # unsigned APK (the same behavior as a local build), so this workflow is
52− # green even before signing is wired up.
77+ # Job-level env makes OPENCODE_STORE_BASE64 available to this `if`.
5378 - name: Decode signing keystore
5479 if: env.OPENCODE_STORE_BASE64 != ''
55− env:
56− OPENCODE_STORE_BASE64: ${{ secrets.OPENCODE_STORE_BASE64 }}
5780 run: |
5881 STORE_FILE="$RUNNER_TEMP/release.keystore"
5982 printf '%s' "$OPENCODE_STORE_BASE64" | base64 -d > "$STORE_FILE"
6083 echo "OPENCODE_STORE_FILE=$STORE_FILE" >> "$GITHUB_ENV"
6184
6285 - name: Build release APK
63− env:
64− OPENCODE_STORE_FILE: ${{ env.OPENCODE_STORE_FILE }}
65− OPENCODE_STORE_PASSWORD: ${{ secrets.OPENCODE_STORE_PASSWORD }}
66− OPENCODE_KEY_ALIAS: ${{ secrets.OPENCODE_KEY_ALIAS }}
67− OPENCODE_KEY_PASSWORD: ${{ secrets.OPENCODE_KEY_PASSWORD }}
68− run: ./gradlew assembleRelease -PversionName="${{ steps.version.outputs.version }}" --no-daemon
86+ run: |
87+ ./gradlew assembleRelease \
88+ -PversionName="${{ steps.version.outputs.version }}" \
89+ -PversionCode="${{ steps.version.outputs.code }}" \
90+ --no-daemon
6991
70− # Rename to a stable, version-tagged filename so the release attachment is
71− # recognizable regardless of the release/ vs release-signed/ output dir.
92+ # Rename to a stable, version-tagged filename for the release attachment.
7293 - name: Stage APK
7394 run: |
7495 mkdir -p staging
75− APK="$(find app/build/outputs/apk -name '*.apk' | head -n1)"
96+ APK="$(find app/build/outputs/apk/release -name '*.apk' | head -n1)"
7697 cp "$APK" "staging/opencode-${{ steps.version.outputs.version }}.apk"
7798
78− # Generate a signed build-provenance attestation for the staged APK and
79− # store it in GitHub's artifact attestation store, keyed by the file's
80− # digest. Anyone can later verify the APK's origin/provenance with
81− # `gh attestation verify` -- its repository & workflow. Run *after*
82− # staging and *before* the release is published so the attested subject
83− # is byte-identical to the artifact attached to the release.
99+ # Signed build-provenance attestation for the exact artifact being
100+ # published; later verifiable with `gh attestation verify <apk>`.
84101 - name: Attest build provenance
85102 uses: actions/attest-build-provenance@v2
86103 with:
@@ -89,7 +106,7 @@ jobs:
89106 - name: Create release
90107 uses: softprops/action-gh-release@v2
91108 with:
92− tag_name: ${{ steps.version.outputs.version }}
109+ tag_name: ${{ steps.version.outputs.tag }}
93110 name: ${{ steps.version.outputs.version }}
94111 make_latest: true
95112 generate_release_notes: true
.gitignore+20
@@ -1,6 +1,8 @@
11# Gradle
22.gradle/
33build/
4+*.apk
5+*.aab
46
57# Kotlin
68.kotlin/
@@ -29,3 +31,21 @@ Thumbs.db
2931
3032# Nix
3133result
34+result-*
35+.direnv/
36+
37+# Local tooling / editor state (not part of the project)
38+.crush/
39+.crush.db
40+*.log
41+
42+# Rust
43+shared/target/
44+/target/
45+
46+# The `generated/` shared type sources ARE committed (regenerable via
47+# `cargo run --features typegen --bin codegen`); only the built JNI .so
48+# artifacts are ignored.
49+generated/jniLibs/
50+
51+# Gradle wrapper jar is committed so CI can run ./gradlew
AGENTS.mddeleted−197
@@ -1,197 +0,0 @@
1−# AGENTS.md
2−
3−Guidance for AI coding agents (and humans) working in this repository.
4−
5−## Project
6−
7−opencode-android is a native Android client (Kotlin + Jetpack Compose) for the
8−[`opencode serve`](https://opencode.ai/docs/server/) HTTP API. It talks to a
9−remote opencode server over REST plus a long-lived Server-Sent Events stream,
10−and renders conversations (markdown, diffs, tool calls, reasoning, images) with
11−an adaptive single-pane / two-pane Material 3 UI.
12−
13−- Application id / namespace: `soy.iko.opencode`
14−- Package root: `app/src/main/java/soy/iko/opencode`
15−- minSdk 26, compileSdk/targetSdk 37, JDK 17, Kotlin 2.2.x, AGP 9.2.x
16−- Single Gradle module (`:app`); no dynamic feature modules.
17−
18−## Build & environment
19−
20−A Nix flake provides the exact toolchain (JDK 17, Gradle, Android SDK 37, and a
21−Nix-built `aapt2` override because Gradle's bundled aapt2 segfaults on NixOS).
22−
23−```bash
24−nix develop # enter the dev shell (sets ANDROID_HOME, JAVA_HOME, GRADLE_OPTS)
25−./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
26−./gradlew assembleRelease # R8-minified + resource-shrunk; signed only when OPENCODE_STORE_* env vars are set
27−```
28−
29−Outside Nix, you need JDK 17 and the Android SDK (platform 37, build-tools
30−37.0.0) installed manually; `ANDROID_HOME` / `ANDROID_SDK_ROOT` must point at it.
31−
32−Install on a connected device/emulator:
33−
34−```bash
35−adb install -r app/build/outputs/apk/debug/app-debug.apk
36−adb shell am start -n soy.iko.opencode/.MainActivity
37−```
38−
39−## Test, lint, and static analysis
40−
41−```bash
42−./gradlew testDebugUnitTest # JVM unit tests (JSON/reducer/ViewModel logic)
43−./gradlew detekt # static analysis; config: config/detekt/detekt.yml, baseline: app/detekt-baseline.xml
44−./gradlew lintDebug # Android Lint (abortOnError = true)
45−./gradlew connectedAndroidTest # instrumented tests; needs a running AVD or device
46−```
47−
48−- Unit tests live in `app/src/test/...` and run on the JVM. They use fakes from
49− `app/src/test/java/soy/iko/opencode/ui/testing/TestFakes.kt` (Fake* subclasses
50− that override the `open` members of the real stores/clients). JUnit 4 +
51− `kotlinx-coroutines-test`; no Robolectric — `testOptions.unitTests.isReturnDefaultValues = true`
52− stubs Android framework calls so tests brushing `Log.d` etc. don't need it.
53−- Instrumented tests live in `app/src/androidTest/...` and need a device.
54−- detekt runs with a baseline (`app/detekt-baseline.xml`) so only **new**
55− findings block CI; existing ones are grandfathered.
56−- CI (`.github/workflows/build.yml`) runs: `testDebugUnitTest` → `detekt` →
57− `lintDebug` → `assembleDebug` → `assembleRelease`, then uploads both APKs.
58−
59−## Running a server to develop against
60−
61−```bash
62−opencode serve --hostname 0.0.0.0 --port 4096
63−```
64−
65−Connect the app over LAN (`http://<host-ip>:4096`) or USB
66−(`adb reverse tcp:4096 tcp:4096` then `http://127.0.0.1:4096`). Auth is optional
67−(`OPENCODE_SERVER_PASSWORD`; username defaults to `opencode`). See the README's
68−"Set up a server and connect to it" section for full details.
69−
70−## Architecture
71−
72−Unidirectional data flow with manual DI, no annotation processing (no Hilt/KSP).
73−
74−```
75−OpencodeApp (Application)
76− └─ AppContainer (service locator: profile/settings/draft stores, active connection,
77− unread tracker, auto-reconnect, pending share / open-session signals)
78− └─ OpencodeConnection (one per active server profile)
79− ├─ HttpClient (Ktor + OkHttp, base URL + Basic auth + JSON + SSE)
80− ├─ OpencodeApiClient (REST: sessions, messages, files, providers, agents, commands, permissions)
81− ├─ EventStreamClient (long-lived GET /event SSE -> hot SharedFlow<BusEvent>)
82− └─ SessionRepository (reduces BusEvents + REST seeds -> Flow<List<MessageWithParts>>)
83− └─ MessageStore (in-memory reducer; internal, unit-tested)
84−
85−ViewModels (ui/<feature>/<Feature>ViewModel.kt)
86− └─ expose StateFlow; Compose collects with collectAsStateWithLifecycle
87− └─ built via ui/VmFactory.kt (viewModelFactory { initializer { ... } }) from the AppContainer
88−```
89−
90−Key invariants:
91−
92−- **Subscribe before you prompt.** `SessionRepository.observeMessages` collects
93− the SSE stream *before* the initial REST load and before any prompt POST, so
94− early streamed parts aren't missed. Preserve this ordering if you touch it.
95−- **Resilient decoding.** `OpencodeJson` registers `polymorphicDefaultDeserializer`
96− for `Part`, `BusEvent`, `MessageInfo`, and `ToolState`, so an unknown
97− discriminator decodes to an `Unknown*` / `ToolUnknown` variant instead of
98− throwing. Never add a `when (event)` that isn't exhaustive or that crashes on
99− `UnknownEvent` — the whole point is that a new server release can't break the
100− client. Add new modeled variants alongside the `Unknown` fallback.
101−- **Conflated message stream.** `observeMessages` is `.conflate()`d so a burst of
102− per-token snapshots doesn't back-pressure the reducer. Don't remove this.
103−- **Re-seed on SSE reconnect.** When `EventStreamClient.state` returns to
104− `Connected` after a prior connection, the repository re-fetches messages from
105− REST and merges (without pruning) under a generation counter so a stale fetch
106− can't clobber a newer one. See `SessionRepository.kt` for the contract.
107−- **One Ktor client per profile.** `HttpClientFactory.create(profile)` carries
108− the base URL, JSON negotiation, SSE plugin, and auth. Basic auth is sent
109− eagerly (no 401 challenge round-trip) and only installed for HTTPS profiles;
110− for HTTP profiles the `Authorization` header is set proactively in
111− `defaultRequest` instead, and the reactive Auth plugin is deliberately NOT
112− installed so credentials can't be re-sent silently on a cleartext 401.
113−- **Process lifetime.** `OpencodeApp` installs a `CrashLogger`, builds the
114− `AppContainer`, and registers a JVM shutdown hook (since `onTerminate()` isn't
115− called on real devices) that cancels the app scope and closes the active
116− connection. `AppContainer.shutdown()` is guarded against double-invocation.
117−
118−## Source map
119−
120−```
121−data/model Wire models (kotlinx.serialization, sealed polymorphism, @Immutable)
122−data/network Ktor: HttpClientFactory, OpencodeApiClient (REST), EventStreamClient (SSE),
123− OpencodeJson (shared Json), NetworkConfig (all tuning constants)
124−data/repo SessionRepository + MessageStore (reducer), ProfileStore (DataStore +
125− EncryptedSharedPreferences), SettingsStore (theme/dynamic color),
126− DraftStore (per-session draft persistence), CrashLogger, ErrorKind
127−di AppContainer (service locator) + OpencodeConnection (per-server bundle)
128−notification NotificationChannels, RunForegroundService (holds process priority
129− during a run), SessionNotifications (completion notifications)
130−ui OpencodeApp (NavHost), Routes, VmFactory, theme/
131−ui/chat ChatScreen + ChatViewModel, message bubbles, part rendering,
132− agent/model/command picker sheets, permission dialog, export
133−ui/session SessionListScreen + ViewModel, TwoPaneSessionChat (≥840dp)
134−ui/server ServerListScreen + ServerEditScreen (+ ViewModels)
135−ui/file FileBrowserScreen + FileViewScreen (+ ViewModels)
136−ui/settings SettingsScreen, DiagnosticsScreen (crash reports)
137−util Coroutines.kt (runCatchingCancellable, safeExceptionSummary)
138−```
139−
140−## Conventions
141−
142−- **No comments unless asked** — existing code has extensive `//` comments
143− explaining *why* (invariants, race conditions, security rationale). When you
144− add code, match that style only for genuinely non-obvious invariants; don't
145− narrate *what* the code does.
146−- **`runCatchingCancellable`** (`util/Coroutines.kt`) instead of `runCatching`
147− inside coroutines — plain `runCatching` swallows `CancellationException` and
148− breaks structured concurrency. Use it for any try/catch in a suspend context.
149−- **`safeExceptionSummary`** for logging Ktor exceptions — `ClientRequestException`
150− messages embed the full request URL (may contain auth/paths); never log the
151− raw exception from an HTTP call. Crash reports scrub URLs via a regex too.
152−- **`open` classes with protected no-arg test constructors.** Stores, the API
153− client, `EventStreamClient`, `OpencodeConnection`, and `AppContainer` are
154− `open` and have a `protected constructor()` so tests can subclass and override
155− individual members without instantiating Android frameworks. Keep this pattern
156− when adding new injectable components.
157−- **`NetworkConfig`** holds all tuning constants (timeouts, backoffs, buffer
158− sizes, layout thresholds, debounce delays). Add new magic numbers here rather
159− than scattering literals.
160−- **REST path encoding.** `OpencodeApiClient` URL-encodes path segments via
161− `encode()` (e.g. `session/${encode(id)}`). Deep-link session ids are validated
162− against `[A-Za-z0-9_-]+` in `MainActivity` to prevent path traversal.
163−- **Idempotency keys.** `sendPrompt` and `runCommand` generate the
164− `Idempotency-Key` header *before* `withRetry` so all retry attempts share it.
165− Preserve this when adding mutating endpoints.
166−- **`withRetry`** wraps all REST reads and the permission response. Transient
167− failures back off with jitter; see `NetworkConfig` for the parameters.
168−- **Compose:** `collectAsStateWithLifecycle` everywhere; `WhileSubscribed` with a
169− 5s grace period (`stateFlowSubscriptionTimeoutMs`). `@Composable` functions
170− use PascalCase (detekt `FunctionNaming` disabled for this reason). Long
171− composables and long parameter lists are accepted (detekt `LongMethod` /
172− `LongParameterList` disabled).
173−- **Manifest:** cleartext HTTP is permitted via `network_security_config.xml`
174− (opencode serves plain `http://`). `enableOnBackInvokedCallback="true"` for
175− Android 14 predictive back. Deep link scheme `opencode://session/{id}`.
176−- **`@Immutable`** on data models exposed to Compose so they skip recomposition
177− correctly.
178−- **Kotlin code style: `official`** (see `gradle.properties`).
179−
180−## Things to avoid
181−
182−- Don't add Hilt/Dagger/KSP — DI is intentionally hand-written (`AppContainer`).
183−- Don't add Robolectric — JVM tests use `isReturnDefaultValues = true` stubs and
184− fakes; only device-dependent code goes in `androidTest`.
185−- Don't run `nix flake check` manually (CI only — per repo convention).
186−- Don't read or query `/nix/store` (extremely large — per repo convention).
187−- Don't introduce new detekt findings; the baseline only grandfathers existing
188− ones. Run `./gradlew detekt` before considering work done.
189−- Don't log raw Ktor/OkHttp exceptions — use `safeExceptionSummary`.
190−- Don't make a `when (BusEvent)` / `when (Part)` non-exhaustive; the `Unknown*`
191− variants exist for forward compatibility and must remain reachable.
192−
193−## Renovate
194−
195−`renovate.json` keeps dependencies current: Kotlin+AGP and Compose are grouped;
196−Ktor is grouped; AndroidX majors are held for manual review (pinned to
197−compileSdk 37). Dependency upgrades land via Renovate PRs, not manual bumps.
CLAUDE.mdmode 120000 → 100644+40−1
@@ -1 +0,0 @@
1−AGENTS.md
@@ -0,0 +1,40 @@
1+# opencode-android
2+
3+Native Android client for the opencode server, built with Crux (Rust core), Kotlin, and Jetpack Compose.
4+
5+## Architecture
6+
7+- **shared/** — Rust Crux core (canonical spec, unit-tested with `cargo test`)
8+- **app/** — Android shell with Kotlin port of the reducer (`OpencodeCore`)
9+- All app logic in `OpencodeCore.kt`; UI is a thin Compose shell
10+- Three screens: Connect → Sessions → Chat
11+
12+## Key Files
13+
14+- `app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt` — reducer, all state management
15+- `app/src/main/java/soy/iko/opencode/core/ViewModel.kt` — UiState, Event, data classes
16+- `app/src/main/java/soy/iko/opencode/core/Protocol.kt` — wire types, SSE event parser
17+- `app/src/main/java/soy/iko/opencode/core/HttpClient.kt` — OkHttp wrapper
18+- `app/src/main/java/soy/iko/opencode/core/SseClient.kt` — SSE stream client
19+- `app/src/main/java/soy/iko/opencode/ui/screens/` — ConnectScreen, SessionsScreen, ChatScreen
20+- `app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt` — message rendering
21+
22+## Build
23+
24+```sh
25+source .buildenv.sh
26+nix develop -c ./gradlew assembleDebug
27+```
28+
29+## Code Conventions
30+
31+- Kotlin + Jetpack Compose (Material 3)
32+- State flows through `MutableStateFlow<UiState>` → `collectAsStateWithLifecycle`
33+- All state mutations on main dispatcher (viewModelScope)
34+- Network I/O on `Dispatchers.IO` inside HttpClient/SseClient
35+- Keep the Rust core and Kotlin port behaviourally identical
36+
37+## Version Control
38+
39+- Uses `jj` (jujutsu) colocated with git
40+- Push to master: `jj git push --change @` to create a bookmark, or commit then push
README.md+126−64
@@ -1,91 +1,153 @@
11# opencode-android
22
3−A native Android client (Kotlin + Jetpack Compose) for the [`opencode serve`](https://opencode.ai/docs/server/) HTTP API.
3+A native Android client for the [**opencode**](https://opencode.ai) server (the
4+`sst/opencode` AI coding agent), built with **Crux** (a Rust core), **Kotlin**,
5+and **Jetpack Compose**.
46
5−Application id: `soy.iko.opencode`
7+Connect to a running `opencode serve`, browse and create sessions, and chat with
8+the agent — assistant replies (text, reasoning, and tool calls) stream in live
9+over the server's SSE event stream.
610
7−## Set up a server and connect to it
11+<p align="center"><em>Connect → Sessions → Chat, with token-by-token streaming.</em></p>
812
9−This app is a client for the [`opencode serve`](https://opencode.ai/docs/server/) HTTP API, so you
10−need an opencode server running somewhere reachable from your device.
11−
12−### 1. Start the server
13+## Architecture
1314
14−On the host that has your project and opencode installed:
15+The app follows the Crux pattern: **all application logic lives in a pure,
16+platform-agnostic core; the platform is a thin shell** that renders the core's
17+view model, sends it events, and performs the side effects it requests.
1518
16−```bash
17−opencode serve --hostname 0.0.0.0 --port 4096
19+```
20+┌─────────────────────────── shared/ (Rust) ───────────────────────────┐
21+│ Crux core — the single source of truth │
22+│ • Model / Event / Effect / ViewModel │
23+│ • update(): connect+auth, sessions, chat, SSE stream application │
24+│ • crux_http for HTTP effects; unit-tested with `cargo test` │
25+└───────────────────────────────────────────────────────────────────────┘
26+ ▲ mirrored, behaviour-for-behaviour
27+┌─────────────────────────── app/ (Kotlin) ────────────────────────────┐
28+│ Jetpack Compose shell │
29+│ • OpencodeCore — Kotlin port of the reducer (same ViewModel) │
30+│ • HttpClient (OkHttp) + SseClient (okhttp-sse) — the effects │
31+│ • Compose UI: Connect / Sessions / Chat │
32+└───────────────────────────────────────────────────────────────────────┘
1833```
1934
20−Useful flags:
35+### Why a Kotlin port instead of a JNI `.so`?
2136
22−| Flag | Default | Description |
23−| --- | --- | --- |
24−| `--port` | `4096` | Port to listen on |
25−| `--hostname` | `127.0.0.1` | Hostname/interface to bind (`0.0.0.0` exposes it on your LAN) |
26−| `--mdns` | `false` | Enable mDNS discovery |
27−| `--cors` | `[]` | Extra browser origins to allow (repeatable) |
37+Crux normally compiles the Rust core to a native library and the shell talks to
38+it over an FFI bridge. That requires an Android cross-compilation toolchain
39+(NDK + a Rust `std` for the `*-linux-android` targets). This project's dev
40+environment intentionally ships **without** an NDK, so instead:
2841
29−The server publishes an OpenAPI 3.1 spec at `http://<hostname>:<port>/doc`.
42+- The **Rust core is the canonical specification** of behaviour and is fully
43+ unit-tested (`cd shared && cargo test`).
44+- The **Android shell runs `OpencodeCore`**, a faithful Kotlin port of the same
45+ reducer, driving an identical `UiState`/`ViewModel`.
3046
31−### 2. (Optional) Add authentication
47+The FFI boundary is kept clean, so the day an NDK is available the Kotlin port
48+can be swapped for the compiled `.so` behind the same seam. The crate already
49+builds as a `cdylib`/`staticlib` and a `codegen` binary is wired for Crux
50+type-generation.
3251
33−opencode has no auth by default. To protect the server with HTTP Basic auth:
52+## Project layout
3453
35−```bash
36−OPENCODE_SERVER_PASSWORD=your-password opencode serve --hostname 0.0.0.0 --port 4096
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
3766```
3867
39−The username defaults to `opencode` (override with `OPENCODE_SERVER_USERNAME`). Enter these in the
40−app's add-server dialog.
41−
42−### 3. Connect from the app
68+## Getting started
4369
44−**Over Wi-Fi / LAN** — add a server with base URL `http://<host-LAN-ip>:4096`.
70+### Dev shell
4571
46−**Over USB only** — forward the port to the device and point the app at localhost:
72+Everything you need is provided by the Nix flake:
4773
48−```bash
49−adb reverse tcp:4096 tcp:4096
74+```sh
75+nix develop # or: direnv allow (an .envrc with `use flake` is included)
5076```
5177
52−Then use base URL `http://127.0.0.1:4096` in the app.
78+This puts JDK 17, Gradle, `rustc`/`cargo`, and the Android SDK (platform 35,
79+build-tools 35.0.0) on your `PATH`.
5380
54−> The app permits cleartext HTTP because opencode serves plain `http://`. If you terminate TLS with
55−> a reverse proxy, use an `https://` base URL instead.
81+### Build & test
5682
57−## Architecture
83+```sh
84+# Rust core — logic + streaming unit tests
85+cd shared && cargo test
86+
87+# Android app — debug APK
88+./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
89+
90+# Android unit tests + lint
91+./gradlew testDebugUnitTest lintDebug
92+```
93+
94+### Run against a server
95+
96+Start opencode's server on your machine or LAN:
5897
59−- **Ktor 3 (OkHttp engine)** for REST + the long-lived `GET /event` SSE stream.
60−- **kotlinx.serialization** with sealed polymorphism for opencode's discriminated unions
61− (`Part`/`type`, `MessageInfo`/`role`, `ToolState`/`status`, `BusEvent`/`type`). Unknown
62− discriminator values fall back to `Unknown*` variants (`OpencodeJson`) so a new server release
63− can't break decoding.
64−- **Manual DI** (`AppContainer` on the `Application`) — no Hilt/KSP.
65−- **Unidirectional state**: `EventStreamClient` exposes the SSE stream as a hot `SharedFlow`;
66− `SessionRepository` reduces events into per-session message state; ViewModels expose `StateFlow`;
67− Compose collects with `collectAsStateWithLifecycle`.
68−- The repository subscribes to `/event` **before** the prompt POST so no early streamed part is missed.
69−
70−Source map: `data/network` (Ktor, SSE, JSON), `data/model` (wire models), `data/repo`
71−(reducer + profile persistence), `di` (container/connection), `ui/<feature>` (Compose screens).
72−
73−## Build
74−
75−```bash
76−nix develop # JDK 17, Gradle 9.6.1, Android SDK 37, aapt2 override
77−./gradlew assembleDebug # -> app/build/outputs/apk/debug/app-debug.apk
78−./gradlew assembleRelease # R8-minified + resource-shrunk release APK
79−./gradlew testDebugUnitTest # JVM tests for the JSON/serialization layer
80−./gradlew detekt # static analysis (config: config/detekt/detekt.yml)
81−./gradlew lintDebug # Android Lint
82−./gradlew connectedAndroidTest # device/emulator tests (needs an AVD)
98+```sh
99+opencode serve --port 4096 # optionally behind OPENCODE_SERVER_PASSWORD
83100```
84101
85−## Install & run
102+Install the APK, launch the app, and enter the server URL (e.g.
103+`http://192.168.1.10:4096`). If the server was started with a password the app
104+detects the `401`, shows credential fields, and connects with HTTP Basic auth.
105+
106+> Cleartext HTTP is enabled so you can reach a `http://` server on your LAN.
107+
108+## The opencode API this client speaks
109+
110+- **Connect / auth** — `GET /global/health` probes reachability; a `401` triggers
111+ HTTP Basic auth.
112+- **Sessions** — `GET /session`, `POST /session`, `DELETE /session/{id}`.
113+- **Messages** — `GET /session/{id}/message` (each item is `{ info, parts }`).
114+- **Send** — `POST /session/{id}/prompt_async` (returns immediately; the reply
115+ streams over SSE).
116+- **Cancel** — `POST /session/{id}/abort`.
117+- **Stream** — `GET /event` (SSE). The client applies `message.updated`,
118+ `message.part.updated` (text/reasoning/tool, with deltas), `message.removed`,
119+ `session.idle` (clears the "generating" state), `session.error`, and
120+ `session.{created,updated,deleted}` incrementally. Unknown event types are
121+ ignored so new server versions don't break the stream.
122+
123+## Continuous integration & releases
124+
125+- **CI** (`.github/workflows/build.yml`) runs on pushes to `master` and PRs: it
126+ unit-tests the Crux core (`cargo test`), runs the Android unit tests + lint,
127+ and builds the debug APK (uploaded as an artifact).
128+- **Releases** (`.github/workflows/release.yml`): push a version tag to cut a
129+ release — it builds a minified, signed release APK and publishes a GitHub
130+ Release with the APK attached and a signed build-provenance attestation.
131+
132+ ```sh
133+ git tag v1.0.0 && git push origin v1.0.0 # or run the workflow manually
134+ ```
135+
136+ The tag name becomes the version (a manual run uses a `YYYY.MM.DD.HHMM`
137+ timestamp), stamped into the APK via `-PversionName/-PversionCode`.
138+
139+ **Signing:** set the repo secrets `OPENCODE_STORE_BASE64` (base64 of your
140+ keystore), `OPENCODE_STORE_PASSWORD`, `OPENCODE_KEY_ALIAS`, and
141+ `OPENCODE_KEY_PASSWORD` to sign with your own key. Without them the release
142+ build falls back to the debug key, so the APK is still installable.
143+
144+## Notes & limitations
145+
146+- Rendering covers text, reasoning, and tool-call parts. Interactive tool
147+ **permission** prompts (`permission.updated`) are not yet surfaced.
148+- Model/agent selection uses the server's configured default (no picker yet).
149+- No `.so` is built in this environment (see *Architecture* above).
150+
151+## License
86152
87−```bash
88−adb install -r app/build/outputs/apk/debug/app-debug.apk
89−adb shell am start -n soy.iko.opencode/.MainActivity
90−adb logcat --pid=$(adb shell pidof soy.iko.opencode)
91−```
153+Apache-2.0.
app/build.gradle.kts+46−117
@@ -1,66 +1,59 @@
11plugins {
22 alias(libs.plugins.android.application)
3− alias(libs.plugins.kotlin.serialization)
3+ alias(libs.plugins.kotlin.android)
44 alias(libs.plugins.kotlin.compose)
5− alias(libs.plugins.detekt)
5+ alias(libs.plugins.kotlin.serialization)
66}
77
8−/**
9− * Monotonically increasing versionCode: the git commit count on HEAD, so each release
10− * ships a strictly higher code (never a "downgrade" block) without manual bookkeeping.
11− * Falls back to 1 when git or the history isn't available (e.g. a plain source export).
12− */
13−val gitCommitCount: Int = runCatching {
14− providers.exec {
15− commandLine("git", "rev-list", "--count", "HEAD")
16− }.standardOutput.asText.get().trim().toInt()
17−}.getOrDefault(1)
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
1812
19−// Optional versionName override supplied via `-PversionName=...` (used by the
20−// release workflow to stamp the commit-date version into the APK). Falls back to
21−// the hard-coded version when absent so local builds are unaffected.
22−val versionNameOverride: String? = providers.gradleProperty("versionName").orNull
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()
2319
2420android {
2521 namespace = "soy.iko.opencode"
26− compileSdk = 37
27− buildToolsVersion = "37.0.0"
22+ compileSdk = 35
2823
2924 defaultConfig {
3025 applicationId = "soy.iko.opencode"
3126 minSdk = 26
32− targetSdk = 37
33− // Monotonically increasing across builds: derived from the git commit count so
34− // each release ships a strictly higher versionCode without manual bookkeeping
35− // (and never triggers a "downgrade" install block). Falls back to 1 when the
36− // .git history isn't available (e.g. a plain source export).
37− versionCode = gitCommitCount
38− versionName = versionNameOverride ?: "0.1.0"
27+ targetSdk = 35
28+ versionCode = appVersionCode
29+ versionName = appVersionName
30+
3931 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
4032 }
4133
42− // Release builds are signed when keystore credentials are supplied via env vars
43− // (so CI can publish an installable APK). When the env vars are absent, the
44− // release build falls back to unsigned — same behavior as before — so local
45− // builds keep working without any keystore setup.
46− val releaseSigning = providers.environmentVariable("OPENCODE_STORE_FILE").orNull?.let { path ->
47− signingConfigs.create("release") {
48− storeFile = file(path)
49− storePassword = providers.environmentVariable("OPENCODE_STORE_PASSWORD").orNull
50− keyAlias = providers.environmentVariable("OPENCODE_KEY_ALIAS").orNull
51− keyPassword = providers.environmentVariable("OPENCODE_KEY_PASSWORD").orNull
34+ signingConfigs {
35+ if (hasReleaseKeystore) {
36+ create("release") {
37+ storeFile = file(releaseStorePath!!)
38+ storePassword = System.getenv("OPENCODE_STORE_PASSWORD")
39+ keyAlias = System.getenv("OPENCODE_KEY_ALIAS")
40+ keyPassword = System.getenv("OPENCODE_KEY_PASSWORD")
41+ }
5242 }
5343 }
5444
5545 buildTypes {
5646 release {
5747 isMinifyEnabled = true
58− isShrinkResources = true
5948 proguardFiles(
6049 getDefaultProguardFile("proguard-android-optimize.txt"),
6150 "proguard-rules.pro",
6251 )
63− releaseSigning?.let { signingConfig = it }
52+ signingConfig = if (hasReleaseKeystore) {
53+ signingConfigs.getByName("release")
54+ } else {
55+ signingConfigs.getByName("debug")
56+ }
6457 }
6558 }
6659
@@ -69,106 +62,42 @@ android {
6962 targetCompatibility = JavaVersion.VERSION_17
7063 }
7164
72− // Use the kotlin { compilerOptions {} } block (the kotlinOptions DSL is deprecated
73− // in favor of the type-safe extension exposed by the Kotlin Gradle plugin).
74− kotlin {
75− compilerOptions {
76− jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
77− }
65+ kotlinOptions {
66+ jvmTarget = "17"
7867 }
7968
8069 buildFeatures {
8170 compose = true
8271 }
8372
84− lint {
85− // Fail CI on real errors. Warnings are reported but don't break the build so
86− // minor/style issues don't gate development.
87− abortOnError = true
88− // Dependency upgrades are tracked by Renovate, so don't lint for them here.
89− // ProduceStateDoesNotAssignValue false-positives on valid produceState calls that
90− // assign `value` via a conditional/`withContext` expression (see FileViewScreen's
91− // match-index scan), so it's disabled rather than worked around at each call site.
92− // InvalidFragmentVersionForActivityResult false-positives on FragmentActivity
93− // (the app doesn't use fragments, but BiometricPrompt requires FragmentActivity).
94− // LocalContextGetResourceValueCall flags context.getString() inside LaunchedEffect /
95− // remember lambdas where stringResource() can't be called (not a @Composable scope);
96− // the check is overly aggressive for valid non-composable coroutine contexts.
97− disable += setOf(
98− "GradleDependency",
99− "AndroidGradlePluginVersion",
100− "ProduceStateDoesNotAssignValue",
101− "InvalidFragmentVersionForActivityResult",
102− "LocalContextGetResourceValueCall",
103− )
104− }
105−
10673 packaging {
10774 resources {
10875 excludes += "/META-INF/{AL2.0,LGPL2.1}"
10976 }
11077 }
111−
112− testOptions {
113− unitTests {
114− // Return default values for Android framework stubs (e.g. Log.d, Context.getString)
115− // instead of throwing "not mocked" exceptions, so JVM unit tests that brush
116− // against Android APIs don't need Robolectric.
117− isReturnDefaultValues = true
118− isIncludeAndroidResources = true
119− }
120− }
12178}
12279
12380dependencies {
12481 implementation(libs.androidx.core.ktx)
125− implementation(libs.androidx.core.splashscreen)
126− implementation(libs.androidx.window)
127− implementation(libs.androidx.activity.compose)
128− implementation(libs.androidx.lifecycle.viewmodel.compose)
82+ implementation(libs.androidx.lifecycle.runtime.ktx)
12983 implementation(libs.androidx.lifecycle.runtime.compose)
130− implementation(libs.androidx.navigation.compose)
131−
132− implementation(platform(libs.compose.bom))
133− implementation(libs.compose.ui)
134− implementation(libs.compose.ui.graphics)
135− implementation(libs.compose.ui.tooling.preview)
136− implementation(libs.compose.material3)
137− implementation(libs.compose.material.icons.extended)
138− debugImplementation(libs.compose.ui.tooling)
84+ implementation(libs.androidx.lifecycle.viewmodel.ktx)
85+ implementation(libs.androidx.lifecycle.viewmodel.compose)
86+ implementation(libs.androidx.activity.compose)
13987
140− implementation(libs.ktor.client.core)
141− implementation(libs.ktor.client.okhttp)
142− implementation(libs.ktor.client.content.negotiation)
143− implementation(libs.ktor.serialization.kotlinx.json)
144− implementation(libs.ktor.client.auth)
88+ implementation(platform(libs.androidx.compose.bom))
89+ implementation(libs.androidx.compose.ui)
90+ implementation(libs.androidx.compose.ui.graphics)
91+ implementation(libs.androidx.compose.ui.tooling.preview)
92+ implementation(libs.androidx.compose.material3)
93+ implementation(libs.androidx.compose.material.icons.extended)
94+ debugImplementation(libs.androidx.compose.ui.tooling)
14595
146− implementation(libs.kotlinx.serialization.json)
14796 implementation(libs.kotlinx.coroutines.android)
148−
149− implementation(libs.androidx.datastore.preferences)
150− implementation(libs.androidx.security.crypto)
151− implementation(libs.androidx.biometric)
152− implementation(libs.coil.compose)
153− implementation(libs.coil.network.okhttp)
154− implementation(libs.markdown.renderer)
155− implementation(libs.markdown.renderer.m3)
156− implementation(libs.zxing.core)
97+ implementation(libs.kotlinx.serialization.json)
98+ implementation(libs.okhttp)
99+ implementation(libs.okhttp.sse)
157100
158101 testImplementation(libs.junit)
159102 testImplementation(libs.kotlinx.coroutines.test)
160− testImplementation(libs.ktor.client.mock)
161−
162− androidTestImplementation(libs.androidx.test.ext.junit)
163− androidTestImplementation(libs.androidx.test.runner)
164− androidTestImplementation(libs.androidx.test.core)
165− androidTestImplementation(libs.kotlinx.coroutines.test)
166−}
167−
168−detekt {
169− buildUponDefaultConfig = true
170− // Carry forward the current baseline so CI only fails on *new* findings;
171− // existing issues are grandfathered rather than blocking the migration.
172− baseline = file("detekt-baseline.xml")
173− config.setFrom("$rootDir/config/detekt/detekt.yml")
174103}
app/detekt-baseline.xmldeleted−34
@@ -1,34 +0,0 @@
1−<?xml version="1.0" ?>
2−<SmellBaseline>
3− <ManuallySuppressedIssues/>
4− <CurrentIssues>
5− <ID>ComplexCondition:ChatScreen.kt$searchActive &amp;&amp; searchQuery.isNotEmpty() &amp;&amp; searchMessages.isEmpty() &amp;&amp; messages.isNotEmpty()</ID>
6− <ID>ComplexCondition:PartRenderer.kt$part.isImage &amp;&amp; imageContext != null &amp;&amp; (part.source != null || !part.url.isNullOrBlank())</ID>
7− <ID>ComplexCondition:SessionListViewModel.kt$SessionListState$q.isEmpty() &amp;&amp; pinnedIds.isEmpty() &amp;&amp; noArchivedHidden &amp;&amp; directoryFilter == null</ID>
8− <ID>CyclomaticComplexMethod:AppContainer.kt$AppContainer$@OptIn(ExperimentalCoroutinesApi::class) private fun observeMessageActivity()</ID>
9− <ID>CyclomaticComplexMethod:ChatScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( container: AppContainer, sessionId: String, onBack: () -&gt; Unit, onOpenFile: ((String) -&gt; Unit)? = null, onOpenSession: ((String) -&gt; Unit)? = null, focusMessageId: String? = null, onEditProfile: ((String) -&gt; Unit)? = null, )</ID>
10− <ID>CyclomaticComplexMethod:ChatViewModel.kt$ChatViewModel$private fun send(text: String, includeAttachments: Boolean, idempotencyKey: String? = null): Boolean</ID>
11− <ID>CyclomaticComplexMethod:CodeHighlighter.kt$fun highlightLine(line: String, syntax: FileSyntax, palette: HighlightPalette, state: BlockCommentState): AnnotatedString</ID>
12− <ID>CyclomaticComplexMethod:CodeHighlighter.kt$private fun findNumberEnd(line: String, start: Int): Int</ID>
13− <ID>CyclomaticComplexMethod:ConversationExport.kt$fun buildConversationMarkdown(messages: List&lt;MessageWithParts&gt;, title: String?): String</ID>
14− <ID>CyclomaticComplexMethod:DiagnosticsScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun DiagnosticsScreen(onBack: () -&gt; Unit)</ID>
15− <ID>CyclomaticComplexMethod:EventStreamClient.kt$EventStreamClient$private fun stream(): Flow&lt;BusEvent&gt;</ID>
16− <ID>CyclomaticComplexMethod:FileViewScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun FileViewScreen( container: AppContainer, path: String, onBack: () -&gt; Unit, initialLine: Int? = null, )</ID>
17− <ID>CyclomaticComplexMethod:GlobalSearchScreen.kt$@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun GlobalSearchScreen( container: AppContainer, onOpenSession: (String, String?) -&gt; Unit, onBack: () -&gt; Unit, )</ID>
18− <ID>CyclomaticComplexMethod:MainActivity.kt$MainActivity$private fun handleIntent(intent: Intent?)</ID>
19− <ID>CyclomaticComplexMethod:OpencodeApp.kt$@Composable fun OpencodeApp(container: AppContainer)</ID>
20− <ID>CyclomaticComplexMethod:ServerListScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ServerListScreen( container: AppContainer, onConnected: () -&gt; Unit, onAddProfile: () -&gt; Unit, onEditProfile: (String) -&gt; Unit, onDuplicateProfile: (String) -&gt; Unit, )</ID>
21− <ID>CyclomaticComplexMethod:SessionListScreen.kt$@OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable fun SessionListScreen( container: AppContainer, onOpenSession: (String) -&gt; Unit, onDisconnect: () -&gt; Unit, onOpenFiles: () -&gt; Unit, onOpenSettings: () -&gt; Unit, onAddServer: () -&gt; Unit, onOpenSearch: () -&gt; Unit = {}, onEditProfile: ((String) -&gt; Unit)? = null, // Incremented by a host (the two-pane empty-detail pane) to open the new-session // directory picker, so that pane shares this screen's dialog instead of bypassing it. externalNewSessionTrigger: Int = 0, selectedSessionId: String? = null, )</ID>
22− <ID>CyclomaticComplexMethod:SettingsScreen.kt$@OptIn(ExperimentalMaterial3Api::class, ExperimentalCoroutinesApi::class) @Composable fun SettingsScreen( container: AppContainer, onBack: () -&gt; Unit, onManageServers: () -&gt; Unit, onOpenDiagnostics: () -&gt; Unit, onOpenUsage: () -&gt; Unit = {}, onOpenMcp: () -&gt; Unit = {}, onEditProfile: ((String) -&gt; Unit)? = null, )</ID>
23− <ID>LargeClass:AppContainer.kt$AppContainer</ID>
24− <ID>LargeClass:SessionListViewModel.kt$SessionListViewModel : ViewModel</ID>
25− <ID>MatchingDeclarationName:DiffView.kt$DiffLine</ID>
26− <ID>MatchingDeclarationName:RemoteImage.kt$ImageLoadContext</ID>
27− <ID>TooManyFunctions:AppContainer.kt$AppContainer</ID>
28− <ID>TooManyFunctions:ChatViewModel.kt$ChatViewModel : ViewModel</ID>
29− <ID>TooManyFunctions:CrashLogger.kt$CrashLogger</ID>
30− <ID>TooManyFunctions:MessageBubble.kt$soy.iko.opencode.ui.chat.MessageBubble.kt</ID>
31− <ID>TooManyFunctions:OpencodeApiClient.kt$OpencodeApiClient</ID>
32− <ID>TooManyFunctions:SessionNotifications.kt$SessionNotifications</ID>
33− </CurrentIssues>
34−</SmellBaseline>
app/proguard-rules.pro+13−44
@@ -1,47 +1,16 @@
1−# --- kotlinx.serialization ---
2−# The plugin generates serializers; keep them and the $$serializer companion members.
3−-keepattributes *Annotation*, InnerClasses, Signature, Exceptions
1+# kotlinx.serialization — keep generated serializers and @Serializable metadata.
2+-keepattributes *Annotation*, InnerClasses
43-dontnote kotlinx.serialization.**
5−-keepclassmembers class soy.iko.opencode.** {
6− *** Companion;
7−}
8−-keepclasseswithmembers class soy.iko.opencode.** {
9− kotlinx.serialization.KSerializer serializer(...);
10−}
11−# Keep @Serializable classes themselves so their generated serializers can reference them.
12−-keep,includedescriptorclasses class soy.iko.opencode.**$$serializer { *; }
13−-keepclassmembers class soy.iko.opencode.** {
14− *** Companion;
15−}
16−# Keep the serializable model classes (reflection-free serializer lookup needs the class).
17−-keep @kotlinx.serialization.Serializable class soy.iko.opencode.data.model.** { *; }
184
19−# --- Ktor / OkHttp (HTTP client + SSE) ---
20−# Don't warn about missing optional dependencies; keep only the classes that are
21−# accessed via reflection (Ktor engine registration, OkHttp internals that R8
22−# would otherwise strip). Narrow keeps instead of `-keep class io.ktor.** { *; }`
23−# so R8 can still eliminate dead code and shrink the APK.
24−-dontwarn io.ktor.**
25−-dontwarn okhttp3.**
26−-dontwarn okio.**
27−-dontwarn org.slf4j.**
28−-dontwarn org.jetbrains.annotations.**
29−# Ktor loads engines and plugins via ServiceLoader — keep the service files.
30−-keep class io.ktor.client.engine.** { *; }
31−-keep class io.ktor.client.plugins.** { *; }
32−-keep class io.ktor.serialization.** { *; }
33−-keep class io.ktor.http.** { *; }
34−# OkHttp uses reflection for platform detection and internal classes.
35−-keep class okhttp3.internal.platform.** { *; }
36−-keep class okhttp3.** { *; }
37−-keep class okio.** { *; }
38−
39−# --- Coil (image loading) ---
40−# Coil uses reflection for loadable decoders and the Compose integration.
41−-keep class coil.** { *; }
42−-keep class coil3.** { *; }
43−-dontwarn coil.**
5+-keepclassmembers class **$$serializer { *; }
6+-keepclasseswithmembers class * {
7+ @kotlinx.serialization.Serializable <methods>;
8+}
9+-if @kotlinx.serialization.Serializable class **
10+-keep, allowobfuscation, allowshrinking class <1>
4411
45−# --- androidx.security.crypto pulls in Tink, which references compile-only
46−# com.google.errorprone annotations. They aren't on the runtime classpath.
47−-dontwarn com.google.errorprone.annotations.**
12+# OkHttp / okio — platform-specific bits referenced reflectively.
13+-dontwarn okhttp3.internal.platform.**
14+-dontwarn org.conscrypt.**
15+-dontwarn org.bouncycastle.**
16+-dontwarn org.openjsse.**
app/src/androidTest/java/soy/iko/opencode/ApplicationBootstrapTest.ktdeleted−36
@@ -1,36 +0,0 @@
1−package soy.iko.opencode
2−
3−import androidx.test.core.app.ApplicationProvider
4−import androidx.test.ext.junit.runners.AndroidJUnit4
5−import org.junit.Assert.assertNotNull
6−import org.junit.Assert.assertTrue
7−import org.junit.Test
8−import org.junit.runner.RunWith
9−
10−/**
11− * Smoke test for the [OpencodeApp] Application bootstrap: the container and crash logger
12− * are initialized on startup, and the notification channels are created.
13− */
14−@RunWith(AndroidJUnit4::class)
15−class ApplicationBootstrapTest {
16−
17− @Test
18− fun containerIsInitialized() {
19− val app = ApplicationProvider.getApplicationContext<OpencodeApp>()
20− assertNotNull(app.container)
21− assertNotNull(app.container.settingsStore)
22− }
23−
24− @Test
25− fun notificationChannelsExist() {
26− if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) return
27− val context = ApplicationProvider.getApplicationContext<android.content.Context>()
28− // Touching the app instance runs Application.onCreate, which creates the channels.
29− ApplicationProvider.getApplicationContext<OpencodeApp>()
30− val nm = context.getSystemService(android.content.Context.NOTIFICATION_SERVICE)
31− as android.app.NotificationManager
32− val ids = nm.notificationChannels.map { it.id }
33− assertTrue("status channel should exist, got $ids", ids.contains("run_status"))
34− assertTrue("completed channel should exist, got $ids", ids.contains("session_completed"))
35− }
36−}
app/src/androidTest/java/soy/iko/opencode/data/repo/CrashLoggerTest.ktdeleted−67
@@ -1,67 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import androidx.test.core.app.ApplicationProvider
4−import androidx.test.ext.junit.runners.AndroidJUnit4
5−import org.junit.Assert.assertEquals
6−import org.junit.Assert.assertNotNull
7−import org.junit.Assert.assertNull
8−import org.junit.Assert.assertTrue
9−import org.junit.Test
10−import org.junit.runner.RunWith
11−
12−/**
13− * Instrumented test for [CrashLogger]. Runs on a device/emulator so it can exercise the
14− * real app-private filesystem: a simulated crash is written, then read back, listed, and
15− * deleted through the public API.
16− */
17−@RunWith(AndroidJUnit4::class)
18−class CrashLoggerTest {
19−
20− private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
21− private val logger = CrashLogger.get(context)
22−
23− @Test
24− fun writeReadDeleteRoundTrip() {
25− logger.clearAll()
26−
27− // Simulate an uncaught exception by invoking the report path directly.
28− val report = writeFakeReport()
29−
30− logger.refresh()
31− assertEquals(1, logger.reportCount())
32−
33− val content = logger.readReport(report)
34− assertNotNull(content)
35− assertTrue("report should contain the stack trace", content!!.contains("IllegalStateException"))
36− assertTrue("report should contain device metadata", content.contains("Android:"))
37−
38− logger.deleteReport(report)
39− assertEquals(0, logger.reportCount())
40− assertNull(logger.readReport(report))
41− }
42−
43− @Test
44− fun clearAllRemovesEveryReport() {
45− writeFakeReport("a")
46− writeFakeReport("b")
47− logger.refresh()
48− assertTrue(logger.reportCount() >= 2)
49−
50− logger.clearAll()
51− assertEquals(0, logger.reportCount())
52− }
53−
54− private fun writeFakeReport(tag: String = "test"): String {
55− val dir = java.io.File(context.filesDir, "crashes").apply { mkdirs() }
56− val name = "crash-test-${tag}-${System.nanoTime()}.txt"
57− java.io.File(dir, name).writeText(
58− """
59− opencode-android crash report
60− Android: test
61− java.lang.IllegalStateException: boom $tag
62− at Crasher.crash(Crasher.kt:1)
63− """.trimIndent(),
64− )
65− return name
66− }
67−}
app/src/androidTest/java/soy/iko/opencode/data/repo/DraftStoreTest.ktdeleted−51
@@ -1,51 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import androidx.test.core.app.ApplicationProvider
4−import androidx.test.ext.junit.runners.AndroidJUnit4
5−import kotlinx.coroutines.CoroutineScope
6−import kotlinx.coroutines.Dispatchers
7−import kotlinx.coroutines.SupervisorJob
8−import kotlinx.coroutines.cancel
9−import kotlinx.coroutines.runBlocking
10−import org.junit.Assert.assertEquals
11−import org.junit.Test
12−import org.junit.runner.RunWith
13−
14−@RunWith(AndroidJUnit4::class)
15−class DraftStoreTest {
16−
17− private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
18−
19− @Test
20− fun setGetRemoveRoundTrip() = runBlocking {
21− val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined)
22− val store = DraftStore(context, scope)
23−
24− // Use a unique session ID so it doesn't collide with other tests.
25− val sid = "test-${System.nanoTime()}"
26−
27− store.set(sid, "hello world")
28− assertEquals("hello world", store.get(sid))
29−
30− // Overwrite
31− store.set(sid, "updated")
32− assertEquals("updated", store.get(sid))
33−
34− // Blank clears the entry
35− store.set(sid, " ")
36− assertEquals("", store.get(sid))
37−
38− // Explicit remove
39− store.set(sid, "text")
40− store.remove(sid)
41− assertEquals("", store.get(sid))
42−
43− scope.cancel()
44− }
45−
46− @Test
47− fun getReturnsEmptyForUnknownSession() {
48− val store = DraftStore(context, CoroutineScope(SupervisorJob()))
49− assertEquals("", store.get("never-set-${System.nanoTime()}"))
50− }
51−}
app/src/main/AndroidManifest.xml+6−110
@@ -1,130 +1,26 @@
11<?xml version="1.0" encoding="utf-8"?>
2−<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3− xmlns:tools="http://schemas.android.com/tools">
2+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
43
54 <uses-permission android:name="android.permission.INTERNET" />
65 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
7− <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
8− <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
9− <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
10−
11− <!-- Camera is used opportunistically for attachment capture via the system camera app
12− (ACTION_IMAGE_CAPTURE), so it's optional — devices without a camera still install. -->
13− <uses-feature android:name="android.hardware.camera.any" android:required="false" />
146
157 <application
16− android:name=".OpencodeApp"
17− android:allowBackup="false"
18− android:dataExtractionRules="@xml/data_extraction_rules"
19− android:fullBackupContent="false"
20− android:icon="@mipmap/ic_launcher"
8+ android:allowBackup="true"
9+ android:icon="@android:drawable/sym_def_app_icon"
2110 android:label="@string/app_name"
22− android:networkSecurityConfig="@xml/network_security_config"
2311 android:supportsRtl="true"
24− android:theme="@style/Theme.OpencodeAndroid">
12+ android:theme="@style/Theme.OpencodeAndroid"
13+ android:usesCleartextTraffic="true">
2514
2615 <activity
2716 android:name=".MainActivity"
2817 android:exported="true"
29− android:launchMode="singleTop"
30− android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|uiMode|navigation"
31− android:enableOnBackInvokedCallback="true"
3218 android:windowSoftInputMode="adjustResize"
33− tools:targetApi="33"
34− android:theme="@style/Theme.OpencodeAndroid.Splash">
19+ android:theme="@style/Theme.OpencodeAndroid">
3520 <intent-filter>
3621 <action android:name="android.intent.action.MAIN" />
3722 <category android:name="android.intent.category.LAUNCHER" />
3823 </intent-filter>
39− <intent-filter>
40− <action android:name="android.intent.action.SEND" />
41− <category android:name="android.intent.category.DEFAULT" />
42− <data android:mimeType="text/plain" />
43− </intent-filter>
44− <!-- Receive images shared from other apps (single or multiple) to attach to a prompt. -->
45− <intent-filter>
46− <action android:name="android.intent.action.SEND" />
47− <category android:name="android.intent.category.DEFAULT" />
48− <data android:mimeType="image/*" />
49− </intent-filter>
50− <intent-filter>
51− <action android:name="android.intent.action.SEND_MULTIPLE" />
52− <category android:name="android.intent.category.DEFAULT" />
53− <data android:mimeType="image/*" />
54− </intent-filter>
55− <!-- Deep link to a session: opencode://session/{sessionId} -->
56− <intent-filter>
57− <action android:name="android.intent.action.VIEW" />
58− <category android:name="android.intent.category.DEFAULT" />
59− <category android:name="android.intent.category.BROWSABLE" />
60− <data android:scheme="opencode" android:host="session" />
61− </intent-filter>
62− <!-- Deep links: opencode://file/{path} and opencode://new -->
63− <intent-filter>
64− <action android:name="android.intent.action.VIEW" />
65− <category android:name="android.intent.category.DEFAULT" />
66− <category android:name="android.intent.category.BROWSABLE" />
67− <data android:scheme="opencode" android:host="file" />
68− </intent-filter>
69− <intent-filter>
70− <action android:name="android.intent.action.VIEW" />
71− <category android:name="android.intent.category.DEFAULT" />
72− <category android:name="android.intent.category.BROWSABLE" />
73− <data android:scheme="opencode" android:host="new" />
74− </intent-filter>
7524 </activity>
76−
77− <service
78− android:name=".notification.RunForegroundService"
79− android:exported="false"
80− android:foregroundServiceType="dataSync" />
81−
82− <!-- Handles notification action buttons (permission responses, inline reply). Not
83− exported: only the app's own PendingIntents target it. -->
84− <receiver
85− android:name=".notification.NotificationActionReceiver"
86− android:exported="false" />
87−
88− <!-- Home-screen widget listing recent sessions. -->
89− <receiver
90− android:name=".platform.SessionsWidgetProvider"
91− android:exported="true">
92− <intent-filter>
93− <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
94− </intent-filter>
95− <meta-data
96− android:name="android.appwidget.provider"
97− android:resource="@xml/sessions_widget_info" />
98− </receiver>
99−
100− <!-- Serves the widget's session list rows. Bound by the system with BIND_REMOTEVIEWS. -->
101− <service
102− android:name=".platform.SessionsWidgetService"
103− android:permission="android.permission.BIND_REMOTEVIEWS"
104− android:exported="false" />
105−
106− <!-- Quick-settings tile: start a new session. Bound by the system. -->
107− <service
108− android:name=".platform.NewSessionTileService"
109− android:icon="@drawable/ic_launcher_foreground"
110− android:label="@string/tile_new_session"
111− android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
112− android:exported="true">
113− <intent-filter>
114− <action android:name="android.service.quicksettings.action.QS_TILE" />
115− </intent-filter>
116− </service>
117−
118− <!-- Serves camera-capture temp files (cache/captures) to the system camera app. -->
119− <provider
120− android:name="androidx.core.content.FileProvider"
121− android:authorities="${applicationId}.fileprovider"
122− android:exported="false"
123− android:grantUriPermissions="true">
124− <meta-data
125− android:name="android.support.FILE_PROVIDER_PATHS"
126− android:resource="@xml/file_paths" />
127− </provider>
12825 </application>
129−
13026</manifest>
app/src/main/java/soy/iko/opencode/CoreViewModel.ktnew file+66
@@ -0,0 +1,66 @@
1+package soy.iko.opencode
2+
3+import android.app.Application
4+import android.content.Context
5+import androidx.core.content.edit
6+import androidx.lifecycle.AndroidViewModel
7+import androidx.lifecycle.viewModelScope
8+import kotlinx.coroutines.flow.distinctUntilChangedBy
9+import kotlinx.coroutines.launch
10+import soy.iko.opencode.core.Event
11+import soy.iko.opencode.core.OpencodeCore
12+
13+/**
14+ * Lifecycle-scoped host for the [OpencodeCore] so a single core (and its SSE
15+ * connection) survives configuration changes. It also persists the last server
16+ * URL / username so reconnecting is one tap.
17+ */
18+class CoreViewModel(app: Application) : AndroidViewModel(app) {
19+ private val prefs = app.getSharedPreferences("opencode", Context.MODE_PRIVATE)
20+
21+ val core = OpencodeCore(viewModelScope)
22+
23+ init {
24+ prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
25+ prefs.getString(KEY_USER, null)?.let { core.dispatch(Event.UsernameChanged(it)) }
26+ // The password is stored in plain text in SharedPreferences — a deliberate
27+ // convenience trade-off for a local dev tool so reconnecting is one tap.
28+ prefs.getString(KEY_PASSWORD, null)?.let { core.dispatch(Event.PasswordChanged(it)) }
29+
30+ // On a fresh process after a configuration change, resume the SSE stream if
31+ // the core is already connected (no-op otherwise — it guards on `connected`).
32+ core.resumeStreamingIfConnected()
33+
34+ // Returning users shouldn't have to tap Connect: if a URL was restored and we
35+ // aren't already connected, kick off the connection attempt on launch. The core
36+ // handles an empty/invalid URL, so this only fires when there's something to try.
37+ core.view.value.let { restored ->
38+ if (restored.serverUrl.isNotEmpty() && !restored.connected) {
39+ core.dispatch(Event.Connect)
40+ }
41+ }
42+
43+ // Persist connection details once a connection succeeds.
44+ viewModelScope.launch {
45+ core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
46+ if (state.connected) {
47+ prefs.edit {
48+ putString(KEY_URL, state.serverUrl)
49+ putString(KEY_USER, state.username)
50+ putString(KEY_PASSWORD, state.password)
51+ }
52+ }
53+ }
54+ }
55+ }
56+
57+ override fun onCleared() {
58+ core.shutdown()
59+ }
60+
61+ private companion object {
62+ const val KEY_URL = "serverUrl"
63+ const val KEY_USER = "username"
64+ const val KEY_PASSWORD = "password"
65+ }
66+}
app/src/main/java/soy/iko/opencode/MainActivity.kt+15−398
@@ -1,414 +1,31 @@
11package soy.iko.opencode
22
3−import android.Manifest
4−import android.content.Intent
5−import android.content.pm.PackageManager
6−import android.net.Uri
7−import android.os.Build
83import android.os.Bundle
9−import android.view.WindowManager
10−import androidx.core.content.IntentCompat
11−import soy.iko.opencode.data.network.NetworkConfig
12−import soy.iko.opencode.notification.NotificationActionReceiver
4+import androidx.activity.ComponentActivity
5+import androidx.activity.SystemBarStyle
136import androidx.activity.compose.setContent
147import androidx.activity.enableEdgeToEdge
15−import androidx.activity.result.contract.ActivityResultContracts
16−import androidx.compose.foundation.isSystemInDarkTheme
17−import androidx.compose.material3.AlertDialog
18−import androidx.compose.material3.Text
19−import androidx.compose.material3.TextButton
20−import androidx.compose.runtime.LaunchedEffect
218import androidx.compose.runtime.getValue
22−import androidx.compose.runtime.mutableStateOf
23−import androidx.compose.runtime.remember
24−import androidx.compose.runtime.setValue
25−import androidx.compose.ui.res.stringResource
26−import kotlinx.coroutines.flow.combine
27−import androidx.core.content.ContextCompat
28−import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
29−import androidx.fragment.app.FragmentActivity
309import androidx.lifecycle.compose.collectAsStateWithLifecycle
31−import soy.iko.opencode.data.repo.SettingsStore
32−import soy.iko.opencode.data.repo.ThemeMode
33−import soy.iko.opencode.ui.AppLockGate
34−import soy.iko.opencode.ui.OpencodeApp as OpencodeAppUi
10+import androidx.lifecycle.viewmodel.compose.viewModel
11+import soy.iko.opencode.ui.OpencodeApp
3512import soy.iko.opencode.ui.theme.OpencodeTheme
3613
37−// FragmentActivity (not ComponentActivity) so androidx.biometric BiometricPrompt can attach
38−// for the app-lock gate; FragmentActivity extends ComponentActivity, so Compose/edge-to-edge
39−// /activity-result APIs are unaffected.
40−class MainActivity : FragmentActivity() {
41−
42− private val requestNotificationPermission = registerForActivityResult(
43− ActivityResultContracts.RequestPermission(),
44− ) { /* Result is best-effort; notifications are silently skipped if denied. */ }
45−
46− private var shareIntentHandled = false
47− private var openSessionHandled = false
48− private var newSessionHandled = false
49− private var openFileHandled = false
50− // Set when a deep link was present but failed validation (malformed id/path). Surfaced
51− // as a toast from onResume so the user knows the link was rejected, not silently ignored.
52− private var showInvalidLinkToast = false
53− // Cold-start prompts (crash report, notification rationale) rendered as Compose M3
54− // dialogs. Hoisted as Activity-level mutableState so the non-composable trigger logic
55− // (onCreate/onResume) can flip them and the Compose tree (inside OpencodeTheme) reads
56− // them and renders an M3 AlertDialog that picks up the app palette. The triggers
57− // themselves are idempotent per instance (crashes are acknowledged on first fire;
58− // notificationPermissionRequested is restored from saved state), so a plain
59− // mutableStateOf (not saveable) preserves the original dismissal semantics across
60− // config-change recreation: the prompt simply doesn't re-fire after a rotate.
61− private var showCrashPrompt by mutableStateOf(false)
62− private var showNotifRationale by mutableStateOf(false)
63− // Track whether the notification-permission prompt has been shown for this Activity
64− // instance. onCreate only requests when savedInstanceState == null (a fresh process),
65− // but an Activity recreated by a config change NOT listed in the manifest's configChanges
66− // (e.g. a locale change) has a non-null savedInstanceState and would otherwise skip the
67− // prompt forever. onResume re-requests once per instance when still ungranted so the user
68− // is never silently left without notifications after such a recreation.
69− private var notificationPermissionRequested = false
70−
14+class MainActivity : ComponentActivity() {
7115 override fun onCreate(savedInstanceState: Bundle?) {
72− val splash = installSplashScreen()
16+ enableEdgeToEdge(
17+ statusBarStyle = SystemBarStyle.auto(
18+ lightScrim = 0xFF0F1115.toInt(),
19+ darkScrim = 0xFF0F1115.toInt(),
20+ ),
21+ )
7322 super.onCreate(savedInstanceState)
74− enableEdgeToEdge()
75− savedInstanceState?.let {
76− shareIntentHandled = it.getBoolean(KEY_SHARE_HANDLED, false)
77− openSessionHandled = it.getBoolean(KEY_OPEN_SESSION_HANDLED, false)
78− newSessionHandled = it.getBoolean(KEY_NEW_SESSION_HANDLED, false)
79− openFileHandled = it.getBoolean(KEY_OPEN_FILE_HANDLED, false)
80− }
81− val container = (application as OpencodeApp).container
82− handleIntent(intent)
83− if (savedInstanceState == null) {
84− maybeRequestNotificationPermission()
85− } else {
86− // Restored instance: the permission may have been requested pre-recreation, but
87− // we can't know the result from here. onResume will re-check and request if still
88− // ungranted (once per Activity instance).
89− notificationPermissionRequested = savedInstanceState.getBoolean(KEY_NOTIF_PERM_REQUESTED, false)
90− }
91− // Hold the splash until the persisted theme and app-lock settings load, so we never
92− // paint a frame with the defaults (dynamicColor=false / SYSTEM, app lock off) that then
93− // snap to the user's real choice — including a brief unlocked, un-FLAG_SECURE'd frame
94− // before app lock resolves. Mirrors the SettingsScreen's null-gate.
95− var settingsLoaded = false
96− splash.setKeepOnScreenCondition { !settingsLoaded }
97− // Custom splash exit: a quick fade-out instead of the system default's slide, so the
98− // hand-off to Compose reads as a branded dissolve. The listener must call
99− // splashScreenViewProvider.remove() to release the splash view; otherwise the system
100− // keeps it on screen for its default duration. Reduced-motion is respected via the
101− // animator's duration scale (the system zeroes it under reduced motion).
102− splash.setOnExitAnimationListener { splashScreenViewProvider ->
103− val view = splashScreenViewProvider.view
104− val fade = android.view.animation.AlphaAnimation(1f, 0f).apply {
105− duration = 180
106− fillAfter = true
107− }
108− fade.setAnimationListener(object : android.view.animation.Animation.AnimationListener {
109− override fun onAnimationStart(animation: android.view.animation.Animation?) {}
110− override fun onAnimationEnd(animation: android.view.animation.Animation?) {
111− splashScreenViewProvider.remove()
112− }
113− override fun onAnimationRepeat(animation: android.view.animation.Animation?) {}
114− })
115− view.startAnimation(fade)
116− }
11723 setContent {
118− val theme by remember(container) {
119− container.settingsStore.themeMode
120− .combine(container.settingsStore.dynamicColor, ::Pair)
121− }.collectAsStateWithLifecycle(initialValue = null)
122− val appLock by container.settingsStore.appLock.collectAsStateWithLifecycle(initialValue = null)
123− val appLockReLockSeconds by container.settingsStore.appLockReLockSeconds
124− .collectAsStateWithLifecycle(initialValue = SettingsStore.DEFAULT_APP_LOCK_RELOCK_SECONDS)
125− LaunchedEffect(theme, appLock) { if (theme != null && appLock != null) settingsLoaded = true }
126− // Hide the app's content from screenshots / the recents thumbnail while app lock is
127− // enabled — and while its value is still unknown (null) at cold start, so a protected
128− // launch can't flash into the recents thumbnail before the setting resolves.
129− LaunchedEffect(appLock) {
130− if (appLock != false) window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
131− else window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
132− }
133− val themePair = theme
134− val locked = appLock
135− if (themePair != null && locked != null) {
136− val (themeMode, dynamicColor) = themePair
137− val amoled = themeMode == ThemeMode.AMOLED
138− val dark = when (themeMode) {
139− ThemeMode.SYSTEM -> isSystemInDarkTheme()
140− ThemeMode.LIGHT -> false
141− ThemeMode.DARK -> true
142− ThemeMode.AMOLED -> true
143− }
144− OpencodeTheme(darkTheme = dark, dynamicColor = dynamicColor, amoled = amoled) {
145− AppLockGate(enabled = locked, reLockDelaySeconds = appLockReLockSeconds) {
146− OpencodeAppUi(container = container)
147− }
148− // First-launch prompts as Compose M3 dialogs (siblings of AppLockGate so they
149− // still surface over the lock screen, matching the prior framework-dialog
150− // behavior) and inside OpencodeTheme so they use the app palette.
151− if (showCrashPrompt) {
152− AlertDialog(
153− onDismissRequest = { showCrashPrompt = false },
154− title = { Text(stringResource(R.string.crash_last_run_title)) },
155− text = { Text(stringResource(R.string.crash_last_run_text)) },
156− confirmButton = {
157− TextButton(onClick = {
158− showCrashPrompt = false
159− container.requestDiagnostics()
160− }) { Text(stringResource(R.string.crash_last_run_view)) }
161− },
162− dismissButton = {
163− TextButton(onClick = { showCrashPrompt = false }) {
164− Text(stringResource(R.string.crash_last_run_dismiss))
165− }
166− },
167− )
168− }
169− if (showNotifRationale) {
170− AlertDialog(
171− // Mirrors the original setCancelable(false): not dismissible by
172− // back/outside tap, only by the buttons below.
173− onDismissRequest = { },
174− title = { Text(stringResource(R.string.notif_rationale_title)) },
175− text = { Text(stringResource(R.string.notif_rationale_text)) },
176− confirmButton = {
177− TextButton(onClick = {
178− showNotifRationale = false
179− runCatching { requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS) }
180− }) { Text(stringResource(R.string.notif_rationale_allow)) }
181− },
182− dismissButton = {
183− TextButton(onClick = { showNotifRationale = false }) {
184− Text(stringResource(R.string.notif_rationale_skip))
185− }
186− },
187− )
188− }
189− }
24+ OpencodeTheme {
25+ val vm: CoreViewModel = viewModel()
26+ val state by vm.core.view.collectAsStateWithLifecycle()
27+ OpencodeApp(state = state, dispatch = vm.core::dispatch)
19028 }
19129 }
192− // Surface a "crashed last time" prompt if a crash report from a previous run
193− // hasn't been acknowledged. Acknowledges immediately so it doesn't re-fire on
194− // every rotation/resume; the user can always find reports in Settings → Diagnostics.
195− maybeShowCrashPrompt()
196− }
197−
198− private fun maybeShowCrashPrompt() {
199− val crashLogger = soy.iko.opencode.data.repo.CrashLogger.get(this)
200− if (!crashLogger.hasUnacknowledgedCrash()) return
201− crashLogger.acknowledgeCrashes()
202− showCrashPrompt = true
203− }
204−
205− override fun onNewIntent(intent: Intent) {
206− super.onNewIntent(intent)
207− setIntent(intent)
208− shareIntentHandled = false
209− openSessionHandled = false
210− newSessionHandled = false
211− openFileHandled = false
212− handleIntent(intent)
213− }
214−
215− // Track real foreground state so background notifications (permission requests,
216− // completions, errors) still fire for a session the user "has open" but has walked
217− // away from — the chat screen isn't disposed when the phone is locked, so
218− // container.currentSession stays set and can't be used as a foreground signal.
219− override fun onStart() {
220− super.onStart()
221− (application as OpencodeApp).container.setForeground(true)
222− }
223−
224− override fun onStop() {
225− super.onStop()
226− (application as OpencodeApp).container.setForeground(false)
227− }
228−
229− override fun onResume() {
230− super.onResume()
231− // Re-check on resume: an Activity recreated by a config change not in configChanges
232− // (e.g. locale) has savedInstanceState != null, so onCreate skipped the request. This
233− // ensures the user is prompted once per Activity instance when still ungranted rather
234− // than silently losing all notifications.
235− maybeRequestNotificationPermission()
236− // Surface a rejected deep link once, so a malformed opencode:// link doesn't appear
237− // to be silently ignored. Cleared after firing so a rotation doesn't re-toast.
238− if (showInvalidLinkToast) {
239− showInvalidLinkToast = false
240− android.widget.Toast.makeText(this, R.string.deep_link_invalid, android.widget.Toast.LENGTH_SHORT).show()
241− }
242− }
243−
244− /** Capture text shared from another app so it can be prefilled into a session draft,
245− * and session ids from notification taps / deep links so we can open them. */
246− private fun handleIntent(intent: Intent?) {
247− val container = (application as OpencodeApp).container
248− val action = intent?.action
249− // "New session" from a launcher shortcut or the quick-settings tile. Guarded so a
250− // process-death restore (which re-delivers the intent) doesn't spawn a second session.
251− if (action == ACTION_NEW_SESSION && !newSessionHandled) {
252− container.requestNewSession()
253− newSessionHandled = true
254− }
255− if ((action == Intent.ACTION_SEND || action == Intent.ACTION_SEND_MULTIPLE) && !shareIntentHandled) {
256− val type = intent.type.orEmpty()
257− if (action == Intent.ACTION_SEND && type.startsWith("image/")) {
258− // A single shared image → stage as an attachment in the next opened session.
259− val uri = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)
260− if (uri != null) {
261− container.setPendingSharedMedia(listOf(uri.toString()))
262− shareIntentHandled = true
263− }
264− } else if (action == Intent.ACTION_SEND_MULTIPLE && type.startsWith("image/")) {
265− val uris = IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)
266− ?.take(NetworkConfig.maxAttachments)
267− .orEmpty()
268− if (uris.isNotEmpty()) {
269− container.setPendingSharedMedia(uris.map { it.toString() })
270− shareIntentHandled = true
271− }
272− } else if (action == Intent.ACTION_SEND) {
273− // A non-image file (e.g. a PDF or text file shared from another app): stage it
274− // as an attachment too, so the user can send it to the agent. The attachment
275− // pipeline handles non-image mimes with a generic file icon. Falls back to
276− // EXTRA_TEXT when no stream is present (a plain text share).
277− val uri = IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)
278− if (uri != null) {
279− container.setPendingSharedMedia(listOf(uri.toString()))
280− shareIntentHandled = true
281− } else {
282− val text = intent.getStringExtra(Intent.EXTRA_TEXT)
283− ?.takeIf { it.isNotBlank() }
284− ?.take(10_000) // cap to prevent unbounded memory usage from malicious shares
285− if (text != null) {
286− container.setPendingShare(text)
287− shareIntentHandled = true
288− }
289− }
290− } else {
291− val text = intent.getStringExtra(Intent.EXTRA_TEXT)
292− ?.takeIf { it.isNotBlank() }
293− ?.take(10_000) // cap to prevent unbounded memory usage from malicious shares
294− if (text != null) {
295− container.setPendingShare(text)
296− shareIntentHandled = true
297− }
298− }
299− }
300− // Deep links under the opencode:// scheme. The manifest exposes several hosts:
301− // session/{id} → open (and switch to) that conversation
302− // file/{path} → open the file viewer at that workspace path
303− // new → start a fresh session
304− // The file path is percent-encoded by the link source; decode it here and validate the
305− // segment to keep path-traversal out of the REST path (mirroring the session guard).
306− val data = intent?.takeIf { it.action == Intent.ACTION_VIEW }?.data
307− when (data?.host) {
308− "session" -> {
309− val seg = data.lastPathSegment
310− if (!openSessionHandled) {
311− seg?.takeIf { it.isNotBlank() && it.matches(VALID_SESSION_ID) }?.let {
312− val profileId = intent.getStringExtra(NotificationActionReceiver.EXTRA_PROFILE_ID)
313− ?.takeIf { it.isNotBlank() }
314− container.requestOpenSession(it, profileId)
315− openSessionHandled = true
316− } ?: run {
317− // The link carried a session host but no valid id (or a blank/traversal
318− // attempt). Surface a toast so the user knows the link was rejected,
319− // rather than silently no-op'ing (which reads as "the app did nothing").
320− if (!seg.isNullOrBlank()) showInvalidLinkToast = true
321− }
322− }
323− }
324− "file" -> {
325− // Reconstruct the path from the path segments after "file", preserving internal
326− // slashes. Decoded + validated against traversal/control characters.
327− val rawPath = data.path?.removePrefix("/file/")?.let { android.net.Uri.decode(it) }
328− if (!openFileHandled) {
329− rawPath?.takeIf { it.isNotBlank() && VALID_FILE_PATH.matches(it) && !it.contains("..") }
330− ?.let { container.requestOpenFile(it); openFileHandled = true } ?: run {
331− if (!rawPath.isNullOrBlank()) showInvalidLinkToast = true
332− }
333− }
334− }
335− "new" -> {
336− if (!newSessionHandled) {
337− container.requestNewSession()
338− newSessionHandled = true
339− }
340− }
341− }
342− // Fall back to the EXTRA_SESSION_ID extra (notifications / widget) when no deep link matched.
343− if (!openSessionHandled) {
344− intent?.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() && it.matches(VALID_SESSION_ID) }?.let {
345− val profileId = intent.getStringExtra(NotificationActionReceiver.EXTRA_PROFILE_ID)
346− ?.takeIf { it.isNotBlank() }
347− container.requestOpenSession(it, profileId)
348− openSessionHandled = true
349− }
350− }
351− }
352−
353− companion object {
354− /** Intent extra carrying a session id to open (notifications / deep links / widget). */
355− const val EXTRA_SESSION_ID = "soy.iko.opencode.extra.SESSION_ID"
356−
357− /** Action for the "New session" launcher shortcut and quick-settings tile. */
358− const val ACTION_NEW_SESSION = "soy.iko.opencode.action.NEW_SESSION"
359−
360− /** Session ids are alphanumeric with dashes/underscores. Reject path traversal. */
361− private val VALID_SESSION_ID = Regex("[A-Za-z0-9_-]+")
362−
363− /** A file path must be made of path-ish characters and not carry traversal. Used to
364− * sanity-check the file deep link before handing it to the viewer. */
365− private val VALID_FILE_PATH = Regex("[A-Za-z0-9_\\-./ ]+")
366−
367− private const val KEY_SHARE_HANDLED = "shareIntentHandled"
368− private const val KEY_OPEN_SESSION_HANDLED = "openSessionHandled"
369− private const val KEY_NEW_SESSION_HANDLED = "newSessionHandled"
370− private const val KEY_OPEN_FILE_HANDLED = "openFileHandled"
371− private const val KEY_NOTIF_PERM_REQUESTED = "notificationPermissionRequested"
372− }
373−
374− override fun onSaveInstanceState(outState: Bundle) {
375− super.onSaveInstanceState(outState)
376− val container = (application as OpencodeApp).container
377− // Persist each intent-handled flag as "consumed", not merely "dispatched". The pending
378− // signals live only in the in-memory AppContainer, which is recreated EMPTY on process
379− // death. Persisting a plain "dispatched = true" would, after a kill *before* the UI
380− // consumed the signal, restore the flag as true so the fresh container never receives it —
381− // the deep-linked / new / shared session would silently never open. So AND each flag with
382− // "the container no longer holds the signal": still-pending at save time → persist false so
383− // the re-delivered intent re-dispatches it into the new container on restore; already
384− // consumed → persist true so we don't re-open it unexpectedly on every later restore.
385− val openConsumed = container.pendingOpenSession.value == null
386− val newConsumed = container.pendingNewSession.value == 0
387− val shareConsumed = container.pendingShare.value == null && container.pendingSharedMedia.value.isEmpty()
388− val fileConsumed = container.pendingOpenFile.value == null
389− outState.putBoolean(KEY_SHARE_HANDLED, shareIntentHandled && shareConsumed)
390− outState.putBoolean(KEY_OPEN_SESSION_HANDLED, openSessionHandled && openConsumed)
391− outState.putBoolean(KEY_NEW_SESSION_HANDLED, newSessionHandled && newConsumed)
392− outState.putBoolean(KEY_OPEN_FILE_HANDLED, openFileHandled && fileConsumed)
393− outState.putBoolean(KEY_NOTIF_PERM_REQUESTED, notificationPermissionRequested)
394− }
395−
396− /** Ask for POST_NOTIFICATIONS on Android 13+ so run/completion notifications show.
397− * Idempotent per Activity instance via [notificationPermissionRequested].
398− * Shows a rationale dialog first (explaining what the user gains) before the system
399− * permission prompt, so a user who denies understands what they're missing. */
400− private fun maybeRequestNotificationPermission() {
401− if (notificationPermissionRequested) return
402− if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
403− val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
404− PackageManager.PERMISSION_GRANTED
405− if (!granted) {
406− notificationPermissionRequested = true
407− showNotificationRationaleDialog()
408− }
409− }
410−
411− private fun showNotificationRationaleDialog() {
412− showNotifRationale = true
41330 }
41431}
app/src/main/java/soy/iko/opencode/OpencodeApp.ktdeleted−130
@@ -1,130 +0,0 @@
1−package soy.iko.opencode
2−
3−import android.app.Application
4−import android.content.Context
5−import coil3.ImageLoader
6−import coil3.SingletonImageLoader
7−import coil3.disk.DiskCache
8−import coil3.memory.MemoryCache
9−import coil3.network.okhttp.OkHttpNetworkFetcherFactory
10−import okhttp3.Call
11−import okhttp3.CertificatePinner
12−import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
13−import okhttp3.OkHttpClient
14−import okhttp3.Request
15−import okio.Path.Companion.toOkioPath
16−import soy.iko.opencode.data.model.ServerProfile
17−import soy.iko.opencode.data.network.CertPinUtil
18−import soy.iko.opencode.data.repo.CrashLogger
19−import soy.iko.opencode.di.AppContainer
20−import java.util.concurrent.atomic.AtomicBoolean
21−
22−class OpencodeApp : Application(), SingletonImageLoader.Factory {
23− lateinit var container: AppContainer
24− private set
25−
26− private val shutdownCalled = AtomicBoolean(false)
27−
28− override fun onCreate() {
29− super.onCreate()
30− CrashLogger.get(this).install()
31− container = AppContainer(this)
32− // onTerminate() is only called in emulated process environments, not on real
33− // devices. Register a JVM shutdown hook so cleanup (network callback unregister,
34− // scope cancellation, connection close) runs when the process is actually killed.
35− Runtime.getRuntime().addShutdownHook(Thread {
36− shutdown()
37− })
38− }
39−
40− // Process-wide Coil singleton. The defaults are sane; the explicit factory adds a
41− // disk cache so scrolling back to an image-bearing message doesn't re-fetch it over
42− // the (auth-protected) network every time. Data-URI (base64) images skip the disk
43− // cache automatically; only resolved HTTP/S URLs are cached, keyed by URL.
44− //
45− // Route fetches through a Call.Factory that applies the SAME per-profile certificate
46− // pinning as the REST/SSE client (see HttpClientFactory). Server-hosted images carry the
47− // server's HTTP Basic auth header (see RemoteImage), so without this they would travel over
48− // an UNPINNED TLS connection, silently defeating the pin the user opted into for that host.
49− override fun newImageLoader(context: Context): ImageLoader = ImageLoader.Builder(context)
50− .memoryCache {
51− MemoryCache.Builder()
52− .maxSizePercent(context, 0.25)
53− .build()
54− }
55− .diskCache {
56− DiskCache.Builder()
57− .directory(cacheDir.resolve("image_cache").toOkioPath())
58− .maxSizeBytes(50L * 1024 * 1024)
59− .build()
60− }
61− .components {
62− // Route fetches through a Call.Factory that applies the SAME per-profile certificate
63− // pinning as the REST/SSE client (see HttpClientFactory). Server-hosted images carry
64− // the server's HTTP Basic auth header (see RemoteImage), so without this they would
65− // travel over an UNPINNED TLS connection, silently defeating the pin the user opted
66− // into for that host.
67− add(OkHttpNetworkFetcherFactory(callFactory = { PinnedImageCallFactory(container) }))
68− }
69− .build()
70−
71− override fun onTerminate() {
72− super.onTerminate()
73− shutdown()
74− }
75−
76− private fun shutdown() {
77− // Guard against double shutdown — onTerminate and the shutdown hook can both
78− // fire in emulated environments.
79− if (!shutdownCalled.compareAndSet(false, true)) return
80− container.shutdown()
81− }
82−}
83−
84−/**
85− * A Coil [Call.Factory] that pins image loads exactly like [HttpClientFactory] pins the
86− * REST/SSE channel. The [ImageLoader] is a process singleton built once, but the active
87− * [ServerProfile] — and therefore its pins — changes when the user switches servers, so the
88− * certificate pinner is resolved *per request* from [AppContainer.activeConnection] rather than
89− * baked in at build time. This fails closed: a profile that configures pins always gets a pinned
90− * connection for its images (an unparseable pinned host throws, matching HttpClientFactory), so
91− * image loads for a pinned host are never silently downgraded to an unpinned channel — and a
92− * later server switch is picked up immediately instead of retaining the first profile's pins.
93− */
94−private class PinnedImageCallFactory(private val container: AppContainer) : Call.Factory {
95− // A single shared base client; each derived pinned client reuses this one's connection pool
96− // and dispatcher via newBuilder(), so per-profile pinning doesn't spin up parallel resources.
97− private val base = OkHttpClient()
98−
99− // Cache the last derived client keyed by (host, pins) so we don't rebuild it on every request;
100− // a server switch changes the signature and triggers a rebuild. Guarded because Coil invokes
101− // newCall from arbitrary background threads, possibly concurrently.
102− private val lock = Any()
103− private var cachedSignature: String? = null
104− private var cachedClient: OkHttpClient = base
105−
106− override fun newCall(request: Request): Call =
107− clientFor(container.activeConnection.value?.profile).newCall(request)
108−
109− private fun clientFor(profile: ServerProfile?): OkHttpClient {
110− val pins = CertPinUtil.parseCertPins(profile?.certPin)
111− if (pins.isEmpty()) return base
112− // effectiveBaseUrl upgrades http->https when pinning is on, so the pinned host matches the
113− // https origin RemoteImage resolves image URLs against. Fail closed on an unparseable host
114− // (never fall back to an unpinned client), mirroring HttpClientFactory.create().
115− val effectiveUrl = CertPinUtil.effectiveBaseUrl(profile!!)
116− val host = effectiveUrl.toHttpUrlOrNull()?.host
117− ?: throw IllegalStateException(
118− "Certificate pinning is configured but the server host could not be parsed from $effectiveUrl",
119− )
120− val signature = "$host\n${pins.sorted().joinToString(" ")}"
121− synchronized(lock) {
122− if (signature != cachedSignature) {
123− val pinner = CertificatePinner.Builder().apply { pins.forEach { add(host, it) } }.build()
124− cachedClient = base.newBuilder().certificatePinner(pinner).build()
125− cachedSignature = signature
126− }
127− return cachedClient
128− }
129− }
130−}
app/src/main/java/soy/iko/opencode/core/HttpClient.ktnew file+75
@@ -0,0 +1,75 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.coroutines.Dispatchers
4+import kotlinx.coroutines.suspendCancellableCoroutine
5+import kotlinx.coroutines.withContext
6+import okhttp3.Call
7+import okhttp3.Callback
8+import okhttp3.MediaType.Companion.toMediaType
9+import okhttp3.OkHttpClient
10+import okhttp3.Request
11+import okhttp3.RequestBody.Companion.toRequestBody
12+import okhttp3.Response
13+import java.io.IOException
14+import java.util.concurrent.TimeUnit
15+import kotlin.coroutines.resume
16+import kotlin.coroutines.resumeWithException
17+
18+/** A completed HTTP response (any status code — non-2xx is not an error here). */
19+data class HttpResp(val code: Int, val body: String)
20+
21+/**
22+ * Thin OkHttp wrapper for the opencode REST calls. Transport failures surface as
23+ * [Result.failure]; every actual HTTP response (including 4xx/5xx) is a success
24+ * carrying its status code, matching the Rust core's `HttpResult` handling.
25+ */
26+class HttpClient(
27+ val okhttp: OkHttpClient = OkHttpClient.Builder()
28+ .connectTimeout(15, TimeUnit.SECONDS)
29+ .readTimeout(30, TimeUnit.SECONDS)
30+ .build(),
31+) {
32+ private val jsonMedia = "application/json".toMediaType()
33+
34+ suspend fun get(url: String, auth: String?): Result<HttpResp> =
35+ exec(url, auth) { get() }
36+
37+ suspend fun postJson(url: String, body: String, auth: String?): Result<HttpResp> =
38+ exec(url, auth) { post(body.toRequestBody(jsonMedia)) }
39+
40+ suspend fun delete(url: String, auth: String?): Result<HttpResp> =
41+ exec(url, auth) { delete() }
42+
43+ // Build and run the request off the main thread. Building it — parsing [url]
44+ // in particular — can throw (e.g. a URL with no scheme), so that happens
45+ // inside [runCatching] too: a bad URL then surfaces as [Result.failure]
46+ // instead of crashing the caller's coroutine.
47+ private suspend fun exec(
48+ url: String,
49+ auth: String?,
50+ method: Request.Builder.() -> Request.Builder,
51+ ): Result<HttpResp> = withContext(Dispatchers.IO) {
52+ runCatching {
53+ val builder = Request.Builder().url(url).method()
54+ builder.header("User-Agent", "opencode-android/1.0")
55+ if (auth != null) builder.header("Authorization", auth)
56+ await(okhttp.newCall(builder.build()))
57+ }
58+ }
59+
60+ private suspend fun await(call: Call): HttpResp = suspendCancellableCoroutine { cont ->
61+ cont.invokeOnCancellation { runCatching { call.cancel() } }
62+ call.enqueue(object : Callback {
63+ override fun onFailure(call: Call, e: IOException) {
64+ if (cont.isActive) cont.resumeWithException(e)
65+ }
66+
67+ override fun onResponse(call: Call, response: Response) {
68+ response.use {
69+ val body = runCatching { it.body?.string() }.getOrNull().orEmpty()
70+ if (cont.isActive) cont.resume(HttpResp(it.code, body))
71+ }
72+ }
73+ })
74+ }
75+}
app/src/main/java/soy/iko/opencode/core/OpencodeCore.ktnew file+668
@@ -0,0 +1,668 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.coroutines.CoroutineScope
4+import kotlinx.coroutines.Job
5+import kotlinx.coroutines.delay
6+import kotlinx.coroutines.flow.MutableStateFlow
7+import kotlinx.coroutines.flow.StateFlow
8+import kotlinx.coroutines.flow.asStateFlow
9+import kotlinx.coroutines.launch
10+import java.util.Base64
11+
12+/**
13+ * The application core: a Kotlin port of the Rust Crux core (`shared/`).
14+ *
15+ * It owns all state, turns [Event]s into state changes + effects, and exposes an
16+ * observable [view]. Effects are executed here in the shell: REST calls through
17+ * [HttpClient] and the long-lived `/event` stream through [SseClient]. Every
18+ * server-sent event is fed back in and applied incrementally, so assistant
19+ * replies stream in token-by-token.
20+ *
21+ * All state mutation happens on [scope]'s (main) dispatcher; only the blocking
22+ * network I/O hops to a background thread inside the clients.
23+ */
24+class OpencodeCore(
25+ private val scope: CoroutineScope,
26+ private val http: HttpClient = HttpClient(),
27+) {
28+ // ── Model ────────────────────────────────────────────────────────────────
29+ private var serverUrl = ""
30+ private var username = ""
31+ private var password = ""
32+ private var authRequired = false
33+ private var connected = false
34+ private var loading = false
35+ private var error: String? = null
36+ private var screen = Screen.Connect
37+ private val sessions = mutableListOf<SessionView>()
38+ private var currentSessionId: String? = null
39+ private var currentSessionTitle = ""
40+ private val messages = mutableListOf<MsgState>()
41+ private var draft = ""
42+ private var generating = false
43+ private var sseConnected = true
44+ private var localSeq = 0L
45+
46+ private val _view = MutableStateFlow(snapshot())
47+ val view: StateFlow<UiState> = _view.asStateFlow()
48+
49+ private var sse: SseClient? = null
50+ private var sseClosedIntentionally = false
51+ private var reconnectAttempts = 0
52+ private var reconnectJob: Job? = null
53+
54+ // Guards against overlapping session refreshes: rapid taps launch multiple
55+ // loadSessions coroutines and the slowest-to-return would otherwise win.
56+ private var loadSessionsJob: Job? = null
57+ // Tracks the in-flight createSession coroutine so navigating away can cancel it
58+ // before it dispatches SelectSession into a screen the user already left.
59+ private var createSessionJob: Job? = null
60+ // Tracks the in-flight loadMessages coroutine. Rapidly switching sessions launches
61+ // several; cancel the prior one so only the newest fetch runs (saves needless requests).
62+ private var loadMessagesJob: Job? = null
63+ // Tracks the in-flight probeHealth coroutine. Rapid double-taps on Connect would
64+ // otherwise launch two concurrent health probes; cancel the prior one first.
65+ private var connectJob: Job? = null
66+ // Tracks the in-flight DeleteSession coroutine so navigating away can cancel it
67+ // before its response handler mutates the sessions list / screen the user already left.
68+ private var deleteSessionJob: Job? = null
69+ // Tracks the in-flight sendMessage coroutine so navigating away or switching sessions
70+ // can cancel it before its response handler touches stale message state.
71+ private var sendMessageJob: Job? = null
72+ // Tracks the in-flight abort coroutine (CancelGeneration) so rapid cancel taps don't
73+ // fire multiple abort requests, and navigating away can cancel it.
74+ private var abortJob: Job? = null
75+ // Message IDs removed via SSE; a late MessageUpdated for one must not resurrect it.
76+ private val removedMessageIds = mutableSetOf<String>()
77+
78+ // ── Event entry point ──────────────────────────────────────────────────────
79+ fun dispatch(event: Event) {
80+ when (event) {
81+ // Store the field verbatim while typing; normalizing here would fight
82+ // the user's edits (e.g. eat the "://" as they type it). The URL is
83+ // normalized once, on Connect.
84+ // Clear any prior error as soon as the user edits a field, so a stale
85+ // message (e.g. "Invalid credentials") doesn't linger while they correct it.
86+ is Event.ServerUrlChanged -> { serverUrl = event.url; if (error != null) error = null; emit() }
87+ is Event.UsernameChanged -> { username = event.value; if (error != null) error = null; emit() }
88+ is Event.PasswordChanged -> { password = event.value; if (error != null) error = null; emit() }
89+
90+ Event.Connect -> {
91+ serverUrl = normalizeUrl(serverUrl)
92+ if (serverUrl.isEmpty()) { error = "Enter a server URL"; emit(); return }
93+ // The auth fields are showing but empty — sending the request now
94+ // would just 401 again in a loop. Prompt for credentials instead.
95+ if (authRequired && !hasCredentials()) { error = "Enter username and password"; emit(); return }
96+ // Leave authRequired as-is; probeHealth sets it from the response (true on
97+ // 401, false on success). Resetting it here just flickers the auth fields.
98+ loading = true; error = null; emit()
99+ connectJob?.cancel()
100+ connectJob = scope.launch { probeHealth() }
101+ }
102+
103+ Event.LoadSessions -> {
104+ if (!connected) { error = "Not connected"; emit(); return }
105+ loading = true; emit()
106+ loadSessionsJob?.cancel()
107+ loadSessionsJob = scope.launch { loadSessions() }
108+ }
109+
110+ is Event.SelectSession -> {
111+ // The session may have been deleted (e.g. via SSE) while the list was on
112+ // screen; opening it would only 404 on loadMessages. Bail with an error.
113+ val session = sessions.firstOrNull { it.id == event.id }
114+ if (session == null) { error = "Session no longer exists"; emit(); return }
115+ currentSessionTitle = session.title
116+ currentSessionId = event.id
117+ messages.clear()
118+ removedMessageIds.clear()
119+ screen = Screen.Chat
120+ loading = true
121+ generating = false
122+ error = null
123+ emit()
124+ connectJob?.cancel()
125+ abortJob?.cancel()
126+ sendMessageJob?.cancel()
127+ deleteSessionJob?.cancel()
128+ loadMessagesJob?.cancel()
129+ loadMessagesJob = scope.launch { loadMessages(event.id) }
130+ }
131+
132+ Event.CreateSession -> {
133+ if (!connected) { error = "Not connected"; emit(); return }
134+ loading = true; error = null; emit()
135+ createSessionJob?.cancel()
136+ createSessionJob = scope.launch { createSession() }
137+ }
138+
139+ is Event.DeleteSession -> {
140+ if (!connected) { error = "Not connected"; emit(); return }
141+ val id = event.id
142+ // Delete on the server first; only drop it from the UI once that
143+ // succeeds, so a failed request leaves the session recoverable.
144+ loading = true; error = null; emit()
145+ deleteSessionJob?.cancel()
146+ deleteSessionJob = scope.launch {
147+ http.delete("$serverUrl/session/$id", authHeader()).fold(
148+ onSuccess = { resp ->
149+ if (resp.code in 200..299) {
150+ sessions.removeAll { it.id == id }
151+ if (isCurrent(id)) {
152+ currentSessionId = null
153+ messages.clear()
154+ screen = Screen.Sessions
155+ }
156+ } else {
157+ error = "Failed to delete session"
158+ }
159+ loading = false
160+ },
161+ onFailure = {
162+ error = "Failed to delete session"
163+ loading = false
164+ },
165+ )
166+ emit()
167+ }
168+ }
169+
170+ is Event.DraftChanged -> { draft = event.text; emit() }
171+
172+ is Event.SendMessage -> sendMessage(event.text)
173+
174+ Event.CancelGeneration -> {
175+ generating = false
176+ messages.forEach { it.streaming = false }
177+ emit()
178+ val id = currentSessionId ?: return
179+ // Debounce rapid cancel taps: cancel any in-flight abort before firing
180+ // another so we don't stack duplicate abort requests.
181+ abortJob?.cancel()
182+ abortJob = scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
183+ }
184+
185+ Event.NavigateToSessions -> {
186+ screen = Screen.Sessions
187+ currentSessionId = null
188+ messages.clear()
189+ removedMessageIds.clear()
190+ draft = ""
191+ generating = false
192+ // Clear any error from the chat (e.g. a failed send) so it doesn't
193+ // linger on the sessions list after the user navigates back.
194+ error = null
195+ loading = true
196+ emit()
197+ connectJob?.cancel()
198+ abortJob?.cancel()
199+ createSessionJob?.cancel()
200+ deleteSessionJob?.cancel()
201+ sendMessageJob?.cancel()
202+ loadMessagesJob?.cancel()
203+ loadSessionsJob?.cancel()
204+ loadSessionsJob = scope.launch { loadSessions() }
205+ }
206+
207+ Event.NavigateToConnect -> {
208+ screen = Screen.Connect
209+ connected = false
210+ loading = false
211+ generating = false
212+ sessions.clear()
213+ messages.clear()
214+ removedMessageIds.clear()
215+ currentSessionId = null
216+ draft = ""
217+ // Reset to the default so a late-firing close callback from the old
218+ // SSE connection can't flash the reconnecting banner on the next connect.
219+ sseConnected = true
220+ connectJob?.cancel()
221+ abortJob?.cancel()
222+ createSessionJob?.cancel()
223+ deleteSessionJob?.cancel()
224+ sendMessageJob?.cancel()
225+ loadMessagesJob?.cancel()
226+ closeSse()
227+ emit()
228+ }
229+
230+ Event.DismissError -> { error = null; emit() }
231+ }
232+ }
233+
234+ /** Reconnect the stream on a fresh process (e.g. after rotation) if already connected. */
235+ fun resumeStreamingIfConnected() {
236+ if (connected && sse == null) startSse()
237+ }
238+
239+ fun shutdown() {
240+ // Cancel every tracked coroutine before tearing down the stream so none can
241+ // emit into a cancelled scope after the ViewModel is cleared.
242+ connectJob?.cancel()
243+ loadSessionsJob?.cancel()
244+ createSessionJob?.cancel()
245+ loadMessagesJob?.cancel()
246+ deleteSessionJob?.cancel()
247+ sendMessageJob?.cancel()
248+ abortJob?.cancel()
249+ closeSse()
250+ }
251+
252+ // ── Effects ────────────────────────────────────────────────────────────────
253+ private fun sendMessage(raw: String) {
254+ val text = raw.trim()
255+ val session = currentSessionId ?: return
256+ if (text.isEmpty()) return
257+ // Debounce rapid double-taps on send: a send is already in flight, so a second
258+ // tap would create a duplicate user message and fire a duplicate request.
259+ if (generating) return
260+ localSeq += 1
261+ val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
262+ status = MessageStatus.Pending
263+ textParts["local"] = text
264+ }
265+ messages.add(user)
266+ // Keep the draft text so we can restore it if the send fails; otherwise the
267+ // user's message is lost and they'd have to retype it.
268+ val savedDraft = draft
269+ draft = ""
270+ generating = true
271+ error = null
272+ emit()
273+
274+ val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
275+ sendMessageJob?.cancel()
276+ sendMessageJob = scope.launch {
277+ val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
278+ result.fold(
279+ onSuccess = { resp ->
280+ if (resp.code in 200..299) {
281+ messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Sent
282+ } else {
283+ messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
284+ generating = false
285+ messages.forEach { it.streaming = false }
286+ draft = savedDraft
287+ error = "Server returned status ${resp.code}"
288+ }
289+ },
290+ onFailure = { e ->
291+ messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
292+ generating = false
293+ messages.forEach { it.streaming = false }
294+ draft = savedDraft
295+ error = "Request failed: ${e.message}"
296+ },
297+ )
298+ emit()
299+ }
300+ }
301+
302+ private suspend fun probeHealth() {
303+ val hasCreds = hasCredentials()
304+ http.get("$serverUrl/global/health", authHeader()).fold(
305+ onSuccess = { resp ->
306+ when {
307+ resp.code == 401 -> {
308+ loading = false
309+ // A prior connection may have succeeded (connected = true); a
310+ // re-probe returning 401 (e.g. expired credentials) means we're
311+ // no longer authenticated, so drop the connected flag.
312+ connected = false
313+ // Always reveal the auth fields so the user can see/edit
314+ // their credentials — even when the ones supplied were wrong.
315+ authRequired = true
316+ if (hasCreds) error = "Invalid credentials"
317+ emit()
318+ }
319+ resp.code in 200..299 -> {
320+ connected = true
321+ authRequired = false
322+ error = null
323+ screen = Screen.Sessions
324+ loading = true
325+ emit()
326+ startSse()
327+ // Route through loadSessionsJob so a prior in-flight loadSessions
328+ // (e.g. from a rapid double-connect) is cancelled first.
329+ loadSessionsJob?.cancel()
330+ loadSessionsJob = scope.launch { loadSessions() }
331+ }
332+ else -> {
333+ loading = false
334+ connected = false
335+ error = "Server returned status ${resp.code}"
336+ emit()
337+ }
338+ }
339+ },
340+ onFailure = { e ->
341+ loading = false
342+ connected = false
343+ error = "Connection failed: ${e.message}"
344+ emit()
345+ },
346+ )
347+ }
348+
349+ private suspend fun loadSessions() {
350+ http.get("$serverUrl/session", authHeader()).fold(
351+ onSuccess = { resp ->
352+ if (resp.code in 200..299) {
353+ sessions.clear()
354+ sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
355+ // Impose a stable alphabetical order so the list doesn't shuffle with
356+ // whatever order the server happens to return sessions in.
357+ sessions.sortBy { it.title.lowercase() }
358+ } else {
359+ error = "Server returned status ${resp.code}"
360+ }
361+ },
362+ onFailure = { e -> error = "Request failed: ${e.message}" },
363+ )
364+ loading = false
365+ emit()
366+ }
367+
368+ private suspend fun createSession() {
369+ http.postJson("$serverUrl/session", "{}", authHeader()).fold(
370+ onSuccess = { resp ->
371+ val session = if (resp.code in 200..299) Protocol.parseSession(resp.body) else null
372+ if (session != null) {
373+ if (sessions.none { it.id == session.id }) {
374+ sessions.add(0, SessionView(session.id, displayTitle(session.title)))
375+ // Restore the alphabetical order immediately (matching loadSessions /
376+ // SessionUpserted) so the new session doesn't sit out-of-order at the
377+ // top until the SSE SessionUpserted event arrives to re-sort.
378+ sessions.sortBy { it.title.lowercase() }
379+ }
380+ emit()
381+ // SelectSession takes over the loading state (loads messages).
382+ dispatch(Event.SelectSession(session.id))
383+ return
384+ }
385+ error = "Server returned status ${resp.code}"
386+ },
387+ onFailure = { e -> error = "Request failed: ${e.message}" },
388+ )
389+ loading = false
390+ emit()
391+ }
392+
393+ private suspend fun loadMessages(sessionId: String) {
394+ http.get("$serverUrl/session/$sessionId/message", authHeader()).fold(
395+ onSuccess = { resp ->
396+ if (!isCurrent(sessionId)) { loading = false; return } // user navigated away while loading
397+ loading = false
398+ if (resp.code in 200..299) {
399+ messages.clear()
400+ removedMessageIds.clear()
401+ messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
402+ generating = messages.any { it.streaming }
403+ } else {
404+ error = "Server returned status ${resp.code}"
405+ }
406+ emit()
407+ },
408+ onFailure = { e ->
409+ if (!isCurrent(sessionId)) { loading = false; return }
410+ loading = false
411+ generating = false
412+ error = "Request failed: ${e.message}"
413+ emit()
414+ },
415+ )
416+ }
417+
418+ // ── SSE ─────────────────────────────────────────────────────────────────────
419+ private fun startSse() {
420+ closeSse()
421+ sseClosedIntentionally = false
422+ val client = SseClient(
423+ url = "$serverUrl/event",
424+ auth = authHeader(),
425+ onEvent = { json -> scope.launch { handleServerEvent(json) } },
426+ onStateChange = { open ->
427+ scope.launch {
428+ sseConnected = open
429+ if (open) reconnectAttempts = 0 else scheduleReconnect()
430+ emit()
431+ }
432+ },
433+ )
434+ sse = client
435+ client.connect()
436+ }
437+
438+ private fun closeSse() {
439+ sseClosedIntentionally = true
440+ reconnectJob?.cancel()
441+ reconnectJob = null
442+ sse?.close()
443+ sse = null
444+ }
445+
446+ private fun scheduleReconnect() {
447+ if (sseClosedIntentionally || !connected) return
448+ // Exponential backoff: 2s, 4s, 8s, 16s, capped at 30s. Reset to 0 once the
449+ // stream reconnects (onStateChange(true)) so a healthy server starts fresh.
450+ val delayMs = (2000L * (1L shl reconnectAttempts)).coerceAtMost(30_000L)
451+ if (delayMs < 30_000L) reconnectAttempts += 1
452+ // Cancel any pending reconnect so rapid network flapping can't stack multiple
453+ // coroutines that each open a new SSE connection.
454+ reconnectJob?.cancel()
455+ reconnectJob = scope.launch {
456+ delay(delayMs)
457+ if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
458+ }
459+ }
460+
461+ private fun handleServerEvent(json: String) {
462+ val event = Protocol.parseEvent(json) ?: return
463+ // Only re-render if the event actually changed our state; applyEvent returns
464+ // false for events that don't apply (other session, unknown message, …).
465+ if (applyEvent(event)) emit()
466+ }
467+
468+ /** Apply a server event to the model. Returns true iff any state actually changed. */
469+ private fun applyEvent(event: Protocol.Event): Boolean {
470+ when (event) {
471+ is Protocol.Event.MessageUpdated -> {
472+ val info = event.info
473+ if (info.role != "assistant" || !isCurrent(info.sessionId)) return false
474+ // A MessageRemoved may have arrived before this (late/out-of-order) update;
475+ // don't re-create a message the server has already deleted.
476+ if (info.id in removedMessageIds) return false
477+ val streaming = info.time.completed == null && info.error == null
478+ val existing = messages.firstOrNull { it.id == info.id }
479+ if (existing != null) {
480+ existing.streaming = streaming
481+ if (existing.time == 0L) existing.time = info.time.created
482+ } else {
483+ messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
484+ }
485+ info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
486+ return true
487+ }
488+
489+ is Protocol.Event.PartUpdated -> {
490+ val part = event.part
491+ val msg = messages.firstOrNull { it.id == part.messageId } ?: return false
492+ // Synthetic text parts are intentionally skipped; report no change so we
493+ // don't trigger a needless re-render/emit for them.
494+ return when (part) {
495+ is Protocol.Part.Text -> if (part.synthetic) {
496+ false
497+ } else {
498+ msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
499+ true
500+ }
501+ is Protocol.Part.Reasoning -> {
502+ msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
503+ true
504+ }
505+ is Protocol.Part.Tool -> {
506+ msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
507+ true
508+ }
509+ }
510+ }
511+
512+ is Protocol.Event.PartRemoved -> {
513+ val msg = messages.firstOrNull { it.id == event.messageId } ?: return false
514+ msg.remove(event.partId)
515+ return true
516+ }
517+
518+ is Protocol.Event.MessageRemoved -> {
519+ // Remember the ID so a late MessageUpdated can't resurrect the message.
520+ removedMessageIds.add(event.messageId)
521+ return messages.removeAll { it.id == event.messageId }
522+ }
523+
524+ is Protocol.Event.SessionIdle -> {
525+ if (!isCurrent(event.sessionId)) return false
526+ generating = false
527+ messages.forEach { it.streaming = false }
528+ return true
529+ }
530+
531+ is Protocol.Event.SessionError -> {
532+ val scoped = event.sessionId == null || isCurrent(event.sessionId)
533+ if (!scoped) return false
534+ event.error?.let { error = it.message() }
535+ generating = false
536+ messages.forEach { it.streaming = false }
537+ return true
538+ }
539+
540+ is Protocol.Event.SessionUpserted -> {
541+ val title = displayTitle(event.info.title)
542+ val existing = sessions.firstOrNull { it.id == event.info.id }
543+ if (existing != null) {
544+ sessions[sessions.indexOf(existing)] = SessionView(event.info.id, title)
545+ } else {
546+ sessions.add(0, SessionView(event.info.id, title))
547+ }
548+ // Keep the list alphabetically sorted (matching loadSessions) so an
549+ // upserted session doesn't jump to the top and break the ordering.
550+ sessions.sortBy { it.title.lowercase() }
551+ if (isCurrent(event.info.id)) currentSessionTitle = title
552+ return true
553+ }
554+
555+ is Protocol.Event.SessionDeleted -> {
556+ val id = event.sessionId ?: return false
557+ val removed = sessions.removeAll { it.id == id }
558+ if (isCurrent(id)) {
559+ currentSessionId = null
560+ messages.clear()
561+ screen = Screen.Sessions
562+ return true
563+ }
564+ return removed
565+ }
566+
567+ Protocol.Event.Other -> return false
568+ }
569+ }
570+
571+ // ── View / helpers ──────────────────────────────────────────────────────────
572+ private fun snapshot() = UiState(
573+ screen = screen,
574+ serverUrl = serverUrl,
575+ username = username,
576+ password = password,
577+ authRequired = authRequired,
578+ connected = connected,
579+ loading = loading,
580+ error = error,
581+ sessions = sessions.toList(),
582+ currentSessionId = currentSessionId,
583+ currentSessionTitle = currentSessionTitle,
584+ messages = messages.map { it.toView() },
585+ draft = draft,
586+ generating = generating,
587+ sseConnected = sseConnected,
588+ )
589+
590+ private fun emit() { _view.value = snapshot() }
591+
592+ private fun isCurrent(sessionId: String?) = sessionId != null && currentSessionId == sessionId
593+ private fun hasCredentials() = username.isNotEmpty() || password.isNotEmpty()
594+
595+ private fun authHeader(): String? {
596+ if (!hasCredentials()) return null
597+ val encoded = Base64.getEncoder().encodeToString("$username:$password".toByteArray())
598+ return "Basic $encoded"
599+ }
600+}
601+
602+// ── Internal message state (parts tracked by id for streaming) ─────────────────
603+private class MsgState(val id: String, val role: String, var time: Long) {
604+ var status = MessageStatus.Sent
605+ var streaming = false
606+ val textParts = LinkedHashMap<String, String>()
607+ val reasoningParts = LinkedHashMap<String, String>()
608+ val toolParts = LinkedHashMap<String, ToolView>()
609+
610+ fun remove(partId: String) {
611+ textParts.remove(partId)
612+ reasoningParts.remove(partId)
613+ toolParts.remove(partId)
614+ }
615+
616+ fun toView(): MessageView {
617+ val reasoning = reasoningParts.values.joinToString("")
618+ return MessageView(
619+ id = id,
620+ role = role,
621+ text = textParts.values.joinToString(""),
622+ reasoning = reasoning.ifEmpty { null },
623+ tools = toolParts.values.toList(),
624+ time = time,
625+ status = status,
626+ streaming = streaming,
627+ )
628+ }
629+}
630+
631+private fun messageFromWire(env: Protocol.WireMessageEnvelope): MsgState {
632+ val info = env.info
633+ val msg = MsgState(info.id, info.role, info.time.created)
634+ msg.streaming = info.role == "assistant" && info.time.completed == null && info.error == null
635+ for (raw in env.parts) {
636+ val obj = (raw as? kotlinx.serialization.json.JsonObject) ?: continue
637+ when (val part = Protocol.parsePart(obj)) {
638+ is Protocol.Part.Text -> if (!part.synthetic) msg.textParts[part.id] = part.text
639+ is Protocol.Part.Reasoning -> msg.reasoningParts[part.id] = part.text
640+ is Protocol.Part.Tool -> msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
641+ null -> Unit
642+ }
643+ }
644+ return msg
645+}
646+
647+private fun pickText(text: String, delta: String?, prior: String?): String =
648+ if (text.isNotEmpty()) text else (prior.orEmpty() + (delta ?: ""))
649+
650+private fun normalizeUrl(url: String): String {
651+ val trimmed = url.trim().trimEnd('/')
652+ // Default to http:// when the user didn't type a scheme (e.g. "192.168.1.10:4096").
653+ // Without a scheme OkHttp's URL parser throws and the connect attempt crashes.
654+ return when {
655+ trimmed.isEmpty() -> ""
656+ "://" in trimmed -> trimmed
657+ else -> "http://$trimmed"
658+ }
659+}
660+
661+private fun displayTitle(title: String): String = title.trim().ifEmpty { "Untitled" }
662+
663+// ── Prompt request body (POST /session/{id}/prompt_async) ──────────────────────
664+@kotlinx.serialization.Serializable
665+private data class PromptBody(val parts: List<TextInput>)
666+
667+@kotlinx.serialization.Serializable
668+private data class TextInput(val type: String = "text", val text: String)
app/src/main/java/soy/iko/opencode/core/Protocol.ktnew file+148
@@ -0,0 +1,148 @@
1+package soy.iko.opencode.core
2+
3+import kotlinx.serialization.SerialName
4+import kotlinx.serialization.Serializable
5+import kotlinx.serialization.json.Json
6+import kotlinx.serialization.json.JsonElement
7+import kotlinx.serialization.json.JsonObject
8+import kotlinx.serialization.json.JsonPrimitive
9+import kotlinx.serialization.json.booleanOrNull
10+import kotlinx.serialization.json.contentOrNull
11+import kotlinx.serialization.json.decodeFromJsonElement
12+import kotlinx.serialization.json.jsonObject
13+
14+/**
15+ * Wire types for the opencode HTTP + SSE API, and lenient parsers for them.
16+ *
17+ * This is the Kotlin counterpart of the Rust core's `protocol.rs`. It is
18+ * deliberately forgiving: unknown JSON fields are ignored and every union has a
19+ * catch-all so new server versions never break the stream parser.
20+ */
21+object Protocol {
22+ val json = Json {
23+ ignoreUnknownKeys = true
24+ isLenient = true
25+ coerceInputValues = true
26+ }
27+
28+ // ─── Sessions ────────────────────────────────────────────────────────────
29+
30+ @Serializable
31+ data class WireSession(val id: String, val title: String = "")
32+
33+ fun parseSessions(body: String): List<WireSession> =
34+ runCatching { json.decodeFromString<List<WireSession>>(body) }.getOrDefault(emptyList())
35+
36+ fun parseSession(body: String): WireSession? =
37+ runCatching { json.decodeFromString<WireSession>(body) }.getOrNull()
38+
39+ // ─── Messages ────────────────────────────────────────────────────────────
40+
41+ @Serializable
42+ data class WireTime(val created: Long = 0, val completed: Long? = null)
43+
44+ @Serializable
45+ data class WireError(val name: String = "", val data: JsonElement? = null) {
46+ fun message(): String {
47+ val msg = ((data as? JsonObject)?.get("message") as? JsonPrimitive)?.contentOrNull
48+ return when {
49+ !msg.isNullOrEmpty() -> msg
50+ name.isNotEmpty() -> name
51+ else -> "Unknown error"
52+ }
53+ }
54+ }
55+
56+ @Serializable
57+ data class WireMessageInfo(
58+ val id: String,
59+ val role: String = "",
60+ @SerialName("sessionID") val sessionId: String = "",
61+ val time: WireTime = WireTime(),
62+ val error: WireError? = null,
63+ )
64+
65+ @Serializable
66+ data class WireMessageEnvelope(
67+ val info: WireMessageInfo,
68+ val parts: List<JsonElement> = emptyList(),
69+ )
70+
71+ fun parseMessages(body: String): List<WireMessageEnvelope> =
72+ runCatching { json.decodeFromString<List<WireMessageEnvelope>>(body) }.getOrDefault(emptyList())
73+
74+ // ─── Parts (content union, parsed by hand for robustness) ─────────────────
75+
76+ sealed interface Part {
77+ val id: String
78+ val messageId: String
79+
80+ data class Text(override val id: String, override val messageId: String, val text: String, val synthetic: Boolean) : Part
81+ data class Reasoning(override val id: String, override val messageId: String, val text: String) : Part
82+ data class Tool(override val id: String, override val messageId: String, val tool: String, val status: String, val title: String?) : Part
83+ }
84+
85+ /** Parse a single part JSON object; returns null for kinds we don't render. */
86+ fun parsePart(obj: JsonObject): Part? {
87+ val id = obj.str("id")
88+ val messageId = obj.str("messageID")
89+ return when (obj.str("type")) {
90+ "text" -> Part.Text(id, messageId, obj.str("text"), obj.bool("synthetic"))
91+ "reasoning" -> Part.Reasoning(id, messageId, obj.str("text"))
92+ "tool" -> {
93+ val state = obj["state"] as? JsonObject
94+ val status = state?.str("status")?.ifEmpty { "pending" } ?: "pending"
95+ val title = state?.str("title")?.ifEmpty { null } ?: state?.str("error")?.ifEmpty { null }
96+ Part.Tool(id, messageId, obj.str("tool"), status, title)
97+ }
98+ else -> null
99+ }
100+ }
101+
102+ // ─── SSE `/event` stream ──────────────────────────────────────────────────
103+
104+ sealed interface Event {
105+ data class MessageUpdated(val info: WireMessageInfo) : Event
106+ data class PartUpdated(val part: Part, val delta: String?) : Event
107+ data class PartRemoved(val messageId: String, val partId: String) : Event
108+ data class MessageRemoved(val messageId: String) : Event
109+ data class SessionIdle(val sessionId: String) : Event
110+ data class SessionError(val sessionId: String?, val error: WireError?) : Event
111+ data class SessionUpserted(val info: WireSession) : Event
112+ data class SessionDeleted(val sessionId: String?) : Event
113+ data object Other : Event
114+ }
115+
116+ /** Parse one raw SSE `data:` payload into an [Event]; null if malformed. */
117+ fun parseEvent(raw: String): Event? {
118+ val root = runCatching { json.parseToJsonElement(raw).jsonObject }.getOrNull() ?: return null
119+ val props = root["properties"] as? JsonObject ?: JsonObject(emptyMap())
120+ return when (root.str("type")) {
121+ "message.updated" -> decode<WireMessageInfo>(props["info"])?.let { Event.MessageUpdated(it) }
122+ "message.part.updated" -> {
123+ val partObj = props["part"] as? JsonObject ?: return Event.Other
124+ parsePart(partObj)?.let { Event.PartUpdated(it, props.str("delta").ifEmpty { null }) } ?: Event.Other
125+ }
126+ "message.part.removed" -> Event.PartRemoved(props.str("messageID"), props.str("partID"))
127+ "message.removed" -> Event.MessageRemoved(props.str("messageID"))
128+ "session.idle" -> Event.SessionIdle(props.str("sessionID"))
129+ "session.error" -> Event.SessionError(props.str("sessionID").ifEmpty { null }, decode<WireError>(props["error"]))
130+ "session.created", "session.updated" -> decode<WireSession>(props["info"])?.let { Event.SessionUpserted(it) }
131+ "session.deleted" -> Event.SessionDeleted(
132+ props.str("sessionID").ifEmpty { null } ?: (props["info"] as? JsonObject)?.str("id")?.ifEmpty { null },
133+ )
134+ else -> Event.Other
135+ }
136+ }
137+
138+ private inline fun <reified T> decode(el: JsonElement?): T? =
139+ el?.let { runCatching { json.decodeFromJsonElement<T>(it) }.getOrNull() }
140+
141+ // ─── Small JSON helpers ───────────────────────────────────────────────────
142+
143+ private fun JsonObject.str(key: String): String =
144+ (this[key] as? JsonPrimitive)?.contentOrNull ?: ""
145+
146+ private fun JsonObject.bool(key: String): Boolean =
147+ (this[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.contentOrNull?.toBoolean() } ?: false
148+}
app/src/main/java/soy/iko/opencode/core/SseClient.ktnew file+63
@@ -0,0 +1,63 @@
1+package soy.iko.opencode.core
2+
3+import okhttp3.OkHttpClient
4+import okhttp3.Request
5+import okhttp3.Response
6+import okhttp3.sse.EventSource
7+import okhttp3.sse.EventSourceListener
8+import okhttp3.sse.EventSources
9+import java.util.concurrent.TimeUnit
10+
11+/**
12+ * Long-lived subscription to the opencode `/event` SSE stream.
13+ *
14+ * Crux only models request/response HTTP, so the streaming connection lives here
15+ * in the shell: each decoded event's `data` payload (a JSON object whose own
16+ * `type` field is the discriminant) is handed to [onEvent], which the core then
17+ * parses via [Protocol.parseEvent].
18+ */
19+class SseClient(
20+ private val url: String,
21+ private val auth: String?,
22+ private val onEvent: (String) -> Unit,
23+ private val onStateChange: (Boolean) -> Unit,
24+) {
25+ // A dedicated client with no read timeout — the stream is meant to stay open.
26+ private val client = OkHttpClient.Builder()
27+ .connectTimeout(15, TimeUnit.SECONDS)
28+ .readTimeout(0, TimeUnit.SECONDS)
29+ .retryOnConnectionFailure(true)
30+ .build()
31+
32+ private var source: EventSource? = null
33+
34+ fun connect() {
35+ val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
36+ builder.header("User-Agent", "opencode-android/1.0")
37+ if (auth != null) builder.header("Authorization", auth)
38+ source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
39+ }
40+
41+ fun close() {
42+ source?.cancel()
43+ source = null
44+ }
45+
46+ private val listener = object : EventSourceListener() {
47+ override fun onOpen(eventSource: EventSource, response: Response) {
48+ onStateChange(true)
49+ }
50+
51+ override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
52+ if (data.isNotBlank()) onEvent(data)
53+ }
54+
55+ override fun onClosed(eventSource: EventSource) {
56+ onStateChange(false)
57+ }
58+
59+ override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
60+ onStateChange(false)
61+ }
62+ }
63+}
app/src/main/java/soy/iko/opencode/core/ViewModel.ktnew file+77
@@ -0,0 +1,77 @@
1+package soy.iko.opencode.core
2+
3+/**
4+ * Immutable snapshot the UI renders. Mirrors the Rust core's `ViewModel`, so
5+ * the two implementations stay behaviourally identical.
6+ */
7+
8+enum class Screen { Connect, Sessions, Chat }
9+
10+enum class MessageStatus { Sent, Pending, Failed }
11+
12+data class SessionView(
13+ val id: String,
14+ val title: String,
15+)
16+
17+data class ToolView(
18+ val name: String,
19+ val status: String,
20+ val title: String?,
21+)
22+
23+data class MessageView(
24+ val id: String,
25+ val role: String,
26+ val text: String,
27+ val reasoning: String?,
28+ val tools: List<ToolView>,
29+ val time: Long,
30+ val status: MessageStatus,
31+ val streaming: Boolean,
32+) {
33+ val isUser: Boolean get() = role == "user"
34+}
35+
36+data class UiState(
37+ val screen: Screen = Screen.Connect,
38+ val serverUrl: String = "",
39+ val username: String = "",
40+ val password: String = "",
41+ val authRequired: Boolean = false,
42+ val connected: Boolean = false,
43+ val loading: Boolean = false,
44+ val error: String? = null,
45+ val sessions: List<SessionView> = emptyList(),
46+ val currentSessionId: String? = null,
47+ val currentSessionTitle: String = "",
48+ val messages: List<MessageView> = emptyList(),
49+ val draft: String = "",
50+ val generating: Boolean = false,
51+ val sseConnected: Boolean = true,
52+)
53+
54+/**
55+ * Everything the shell can ask the core to do. Internal HTTP results are not
56+ * events here (unlike the Rust core, which routes them through `then_send`);
57+ * the Kotlin driver awaits them inline in coroutines instead.
58+ */
59+sealed interface Event {
60+ data class ServerUrlChanged(val url: String) : Event
61+ data class UsernameChanged(val value: String) : Event
62+ data class PasswordChanged(val value: String) : Event
63+ data object Connect : Event
64+
65+ data object LoadSessions : Event
66+ data class SelectSession(val id: String) : Event
67+ data object CreateSession : Event
68+ data class DeleteSession(val id: String) : Event
69+
70+ data class DraftChanged(val text: String) : Event
71+ data class SendMessage(val text: String) : Event
72+ data object CancelGeneration : Event
73+
74+ data object NavigateToSessions : Event
75+ data object NavigateToConnect : Event
76+ data object DismissError : Event
77+}
app/src/main/java/soy/iko/opencode/data/model/Agent.ktdeleted−37
@@ -1,37 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** Entry from `GET /agent`. */
7−@Immutable
8−@Serializable
9−data class Agent(
10− // Defaulted so one name-less element in GET /agent doesn't fail the whole list decode
11− // (emptying the agent picker) — matches the resilient-decoding philosophy. A blank name is
12− // degraded but recoverable; a thrown decode is not.
13− val name: String = "",
14− val description: String? = null,
15− val mode: String? = null,
16− val builtIn: Boolean = false,
17− val prompt: String? = null,
18−) {
19− val isPrimary: Boolean get() = mode == "primary"
20− val displayDescription: String get() = description?.takeIf { it.isNotBlank() } ?: "Custom agent"
21−}
22−
23−/** Entry from `GET /command`. */
24−@Immutable
25−@Serializable
26−data class Command(
27− // Defaulted so one name-less element in GET /command doesn't fail the whole list decode
28− // (emptying the command picker) — matches the resilient-decoding philosophy.
29− val name: String = "",
30− val description: String? = null,
31− val agent: String? = null,
32− val model: String? = null,
33− val template: String = "",
34− val subtask: Boolean = false,
35−) {
36− val displayDescription: String get() = description?.takeIf { it.isNotBlank() } ?: template.take(80)
37−}
app/src/main/java/soy/iko/opencode/data/model/BusEvent.ktdeleted−109
@@ -1,109 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import kotlinx.serialization.SerialName
4−import kotlinx.serialization.Serializable
5−
6−/**
7− * The SSE envelope from `GET /event`: `{ "type": "<event>", "properties": { ... } }`.
8− * Discriminated on `type` (the global discriminator). Unknown events decode to
9− * [UnknownEvent] so the stream never dies on a new event type.
10− *
11− * Property shapes are kept lenient (nullable fields + ignoreUnknownKeys) because they
12− * drift across opencode versions; the reducer only reads the fields it needs.
13− */
14−@Serializable
15−sealed interface BusEvent
16−
17−@Serializable
18−@SerialName("server.connected")
19−data object ServerConnected : BusEvent
20−
21−@Serializable
22−@SerialName("message.updated")
23−data class MessageUpdated(val properties: Props) : BusEvent {
24− @Serializable
25− data class Props(val info: MessageInfo)
26−}
27−
28−@Serializable
29−@SerialName("message.part.updated")
30−data class MessagePartUpdated(val properties: Props) : BusEvent {
31− @Serializable
32− data class Props(
33− val part: Part,
34− val sessionID: String? = null,
35− val messageID: String? = null,
36− )
37−}
38−
39−@Serializable
40−@SerialName("message.part.removed")
41−data class MessagePartRemoved(val properties: Props) : BusEvent {
42− @Serializable
43− data class Props(
44− val sessionID: String? = null,
45− val messageID: String? = null,
46− val partID: String? = null,
47− )
48−}
49−
50−@Serializable
51−@SerialName("message.removed")
52−data class MessageRemoved(val properties: Props) : BusEvent {
53− @Serializable
54− data class Props(
55− val sessionID: String? = null,
56− val messageID: String? = null,
57− )
58−}
59−
60−@Serializable
61−@SerialName("session.idle")
62−data class SessionIdle(val properties: Props) : BusEvent {
63− @Serializable
64− data class Props(val sessionID: String? = null)
65−}
66−
67−@Serializable
68−@SerialName("session.error")
69−data class SessionError(val properties: Props) : BusEvent {
70− @Serializable
71− data class Props(
72− val sessionID: String? = null,
73− val error: kotlinx.serialization.json.JsonElement? = null,
74− )
75−}
76−
77−@Serializable
78−@SerialName("session.updated")
79−data class SessionUpdated(val properties: Props) : BusEvent {
80− @Serializable
81− data class Props(val info: Session)
82−}
83−
84−@Serializable
85−@SerialName("session.deleted")
86−data class SessionDeleted(val properties: Props) : BusEvent {
87− @Serializable
88− data class Props(val info: Session? = null, val sessionID: String? = null)
89−}
90−
91−@Serializable
92−@SerialName("permission.updated")
93−data class PermissionUpdated(val properties: Permission) : BusEvent
94−
95−@Serializable
96−@SerialName("permission.replied")
97−data class PermissionReplied(val properties: Props) : BusEvent {
98− @Serializable
99− data class Props(
100− val sessionID: String? = null,
101− val permissionID: String? = null,
102− val response: String? = null,
103− )
104−}
105−
106−/** Fallback for any event type we don't model. */
107−@Serializable
108−@SerialName("__unknown")
109−data object UnknownEvent : BusEvent
app/src/main/java/soy/iko/opencode/data/model/Common.ktdeleted−41
@@ -1,41 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−@Immutable
7−@Serializable
8−data class TimeInfo(
9− val created: Long? = null,
10− val updated: Long? = null,
11− val completed: Long? = null,
12−)
13−
14−/** Timing carried by message parts and tool states. The opencode server sends `time: { start,
15− * end?, compacted? }` for these (unlike Session/MessageInfo/Permission, which use the
16− * created/updated/completed shape of [TimeInfo]). With `ignoreUnknownKeys`, modelling these
17− * fields with [TimeInfo] would silently discard start/end/compacted — every part/tool time
18− * would decode to all-nulls — so this separate shape exists for them. */
19−@Immutable
20−@Serializable
21−data class PartTimeInfo(
22− val start: Long? = null,
23− val end: Long? = null,
24− val compacted: Long? = null,
25−)
26−
27−@Immutable
28−@Serializable
29−data class Tokens(
30− val input: Long = 0,
31− val output: Long = 0,
32− val reasoning: Long = 0,
33− val cache: Cache = Cache(),
34−) {
35− @Serializable
36− @Immutable
37− data class Cache(
38− val read: Long = 0,
39− val write: Long = 0,
40− )
41−}
app/src/main/java/soy/iko/opencode/data/model/Files.ktdeleted−44
@@ -1,44 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** Entry from `GET /file?path=` (directory listing). */
7−@Immutable
8−@Serializable
9−data class FileNode(
10− val name: String = "",
11− val path: String = "",
12− val type: String? = null,
13− // Size in bytes and last-modified epoch-ms. The server doesn't currently emit these, so
14− // they default to null and the browser renders nothing extra; optional + defaulted keeps
15− // the client forward-compatible (resilient decoding) so the moment the server adds them
16− // the listing shows size/date with no client change.
17− val size: Long? = null,
18− val mtime: Long? = null,
19−) {
20− val isDirectory: Boolean get() = type == "directory"
21−}
22−
23−/** Response of `GET /file/content?path=`. */
24−@Immutable
25−@Serializable
26−data class FileContent(
27− val type: String? = null, // "text" | "binary"
28− val content: String = "",
29− val diff: String? = null,
30− val mimeType: String? = null,
31− val encoding: String? = null,
32−) {
33− val isBinary: Boolean get() = type == "binary" || encoding == "base64"
34−}
35−
36−/** Entry from `GET /file/status` (VCS status). */
37−@Immutable
38−@Serializable
39−data class FileStatusEntry(
40− val path: String = "",
41− val added: Int = 0,
42− val removed: Int = 0,
43− val status: String? = null, // "added" | "deleted" | "modified"
44−)
app/src/main/java/soy/iko/opencode/data/model/Message.ktdeleted−69
@@ -1,69 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−import kotlinx.serialization.json.JsonElement
7−import kotlinx.serialization.json.JsonClassDiscriminator
8−
9−/**
10− * The `info` object of a message. Discriminated on `role`, which differs from the
11− * global `type` discriminator used by [Part], so this hierarchy overrides it.
12− */
13−@OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)
14−@Serializable
15−@JsonClassDiscriminator("role")
16−sealed interface MessageInfo {
17− val id: String
18− val sessionID: String
19− val time: TimeInfo?
20−}
21−
22−@Immutable
23−@Serializable
24−@SerialName("user")
25−data class UserMessage(
26− override val id: String = "",
27− override val sessionID: String = "",
28− override val time: TimeInfo? = null,
29−) : MessageInfo
30−
31−@Immutable
32−@Serializable
33−@SerialName("assistant")
34−data class AssistantMessage(
35− override val id: String = "",
36− override val sessionID: String = "",
37− val parentID: String? = null,
38− val providerID: String? = null,
39− val modelID: String? = null,
40− val cost: Double? = null,
41− val tokens: Tokens? = null,
42− // JsonElement (not JsonObject) so a server that sends `error` as a bare string/array — or any
43− // non-object shape — decodes instead of throwing mid-AssistantMessage (the MessageInfo
44− // polymorphic fallback can't catch that, since `role` already matched). Mirrors
45− // SessionError.error. Not currently read by the UI, but kept tolerant for forward-compat.
46− val error: JsonElement? = null,
47− override val time: TimeInfo? = null,
48−) : MessageInfo {
49− /** A run is complete once the server stamps a completion time. */
50− val isComplete: Boolean get() = time?.completed != null
51−}
52−
53−/** Fallback for an unrecognized `role`, so new server roles never crash decoding. */
54−@Immutable
55−@Serializable
56−@SerialName("__unknown")
57−data class UnknownMessage(
58− override val id: String = "",
59− override val sessionID: String = "",
60− override val time: TimeInfo? = null,
61−) : MessageInfo
62−
63−/** A message together with its parts — the shape returned by message endpoints and the prompt response. */
64−@Immutable
65−@Serializable
66−data class MessageWithParts(
67− val info: MessageInfo,
68− val parts: List<Part> = emptyList(),
69−)
app/src/main/java/soy/iko/opencode/data/model/Part.ktdeleted−127
@@ -1,127 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−import kotlinx.serialization.json.JsonElement
7−import kotlinx.serialization.json.JsonObject
8−import kotlinx.serialization.json.JsonPrimitive
9−
10−/**
11− * A message part — a discriminated union on `type` (the global class discriminator).
12− * Unknown types decode to [UnknownPart] via the registered polymorphic default,
13− * so the stream survives server additions.
14− *
15− * Every part carries [id] plus its parent [messageID]/[sessionID], which the reducer
16− * uses to attach streamed parts to the right message.
17− */
18−@Serializable
19−sealed interface Part {
20− val id: String
21− val messageID: String?
22− val sessionID: String?
23−}
24−
25−@Immutable
26−@Serializable
27−@SerialName("text")
28−data class TextPart(
29− override val id: String = "",
30− override val messageID: String? = null,
31− override val sessionID: String? = null,
32− val text: String = "",
33− val synthetic: Boolean = false,
34− val ignored: Boolean = false,
35− val time: PartTimeInfo? = null,
36−) : Part
37−
38−@Immutable
39−@Serializable
40−@SerialName("reasoning")
41−data class ReasoningPart(
42− override val id: String = "",
43− override val messageID: String? = null,
44− override val sessionID: String? = null,
45− val text: String = "",
46− val time: PartTimeInfo? = null,
47−) : Part
48−
49−@Immutable
50−@Serializable
51−@SerialName("tool")
52−data class ToolPart(
53− override val id: String = "",
54− override val messageID: String? = null,
55− override val sessionID: String? = null,
56− val callID: String = "",
57− val tool: String = "",
58− val state: ToolState = ToolPending,
59−) : Part
60−
61−@Immutable
62−@Serializable
63−@SerialName("file")
64−data class FilePart(
65− override val id: String = "",
66− override val messageID: String? = null,
67− override val sessionID: String? = null,
68− val mime: String? = null,
69− val filename: String? = null,
70− val url: String? = null,
71− // opencode's message-v2 schema sends `source` as a structured FilePartSource OBJECT
72− // ({ type, path, text, ... }), not a string, for @-file mentions. Typing it as String
73− // threw a SerializationException on decode — which the SSE path silently swallows, so the
74− // whole part vanished. Keep it as a tolerant JsonElement (mirroring Permission.pattern) and
75− // read the path via [sourcePath]; a bare-string source is still tolerated.
76− val source: JsonElement? = null,
77−) : Part
78−
79−/** The file path referenced by a [FilePart.source]. opencode sends `source` as a FilePartSource
80− * object whose `path` field holds the file path; older/other shapes may send a bare string.
81− * Returns null when there's no usable path. */
82−val FilePart.sourcePath: String?
83− get() = when (val s = source) {
84− is JsonPrimitive -> if (s.isString) s.content else null
85− is JsonObject -> (s["path"] as? JsonPrimitive)?.let { if (it.isString) it.content else null }
86− else -> null
87− }
88−
89−@Immutable
90−@Serializable
91−@SerialName("step-start")
92−data class StepStartPart(
93− override val id: String = "",
94− override val messageID: String? = null,
95− override val sessionID: String? = null,
96−) : Part
97−
98−@Immutable
99−@Serializable
100−@SerialName("agent")
101−data class AgentPart(
102− override val id: String = "",
103− override val messageID: String? = null,
104− override val sessionID: String? = null,
105− val name: String = "",
106−) : Part
107−
108−@Immutable
109−@Serializable
110−@SerialName("step-finish")
111−data class StepFinishPart(
112− override val id: String = "",
113− override val messageID: String? = null,
114− override val sessionID: String? = null,
115− val cost: Double? = null,
116− val tokens: Tokens? = null,
117−) : Part
118−
119−/** Fallback for an unrecognized `type`. */
120−@Immutable
121−@Serializable
122−@SerialName("__unknown")
123−data class UnknownPart(
124− override val id: String = "",
125− override val messageID: String? = null,
126− override val sessionID: String? = null,
127−) : Part
app/src/main/java/soy/iko/opencode/data/model/Permission.ktdeleted−58
@@ -1,58 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−import kotlinx.serialization.json.JsonElement
6−import kotlinx.serialization.json.JsonArray
7−import kotlinx.serialization.json.JsonPrimitive
8−
9−/**
10− * A permission request from `permission.updated`. The tool detail lives in [type] +
11− * [pattern] + [metadata]; [pattern] is a string or array of strings on the wire, so
12− * it's kept as a [JsonElement] and flattened for display.
13− */
14−@Immutable
15−@Serializable
16−data class Permission(
17− val id: String = "",
18− val sessionID: String = "",
19− val type: String? = null,
20− val pattern: JsonElement? = null,
21− val messageID: String? = null,
22− val callID: String? = null,
23− val title: String? = null,
24− // JsonElement (not JsonObject) so a non-object `metadata` shape decodes instead of throwing,
25− // matching [pattern]. Not read by the UI today, but kept tolerant for forward-compat.
26− val metadata: JsonElement? = null,
27− val time: TimeInfo? = null,
28−) {
29− val patternText: String?
30− get() = when (val p = pattern) {
31− null -> null
32− is JsonPrimitive -> p.content
33− // Only a JSON array is flattened; any other shape (e.g. an object) would make
34− // the previous unguarded `p.jsonArray` throw during composition, so treat it
35− // as "no displayable pattern" instead.
36− is JsonArray -> p.mapNotNull { (it as? JsonPrimitive)?.content }.joinToString(", ").ifEmpty { null }
37− else -> null
38− }
39−}
40−
41−/** Allowed values for the permission response body.
42− *
43− * [SESSION] is a client-side scope: it auto-responds [ONCE] to subsequent permission requests
44− * whose (type, pattern) match a remembered set, without showing the dialog. The set lives in
45− * [soy.iko.opencode.ui.chat.ChatViewModel] and is cleared on connection change. It is NOT sent
46− * to the server (the server only knows `once`/`always`/`reject`); the VM maps it to [ONCE] on
47− * the wire and tracks the grant locally. This gives users a middle ground between "allow once"
48− * (re-prompts on every file read) and "always" (persists in the server config outliving the app). */
49−enum class PermissionResponse(val wire: String) {
50− ONCE("once"),
51− ALWAYS("always"),
52− REJECT("reject"),
53− SESSION("once"),
54−}
55−
56−/** Body for `POST /session/:id/permissions/:permissionID`. */
57−@Serializable
58−data class PermissionReplyBody(val response: String)
app/src/main/java/soy/iko/opencode/data/model/Project.ktdeleted−32
@@ -1,32 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/**
7− * A project known to the server, from `GET /project`. A project corresponds to a git
8− * worktree root; [worktree] is the absolute path the agent can run in. Used to populate
9− * the directory picker when creating a session in a specific directory.
10− */
11−@Immutable
12−@Serializable
13−data class Project(
14− val id: String = "",
15− val worktree: String = "",
16− val vcs: String? = null,
17− val time: TimeInfo? = null,
18−)
19−
20−/**
21− * The server's current path info, from `GET /path`. [directory] is the working directory
22− * a request with no `directory` override resolves to (the server's launch cwd), shown in
23− * the picker as the "server default" option.
24− */
25−@Immutable
26−@Serializable
27−data class PathInfo(
28− val directory: String? = null,
29− val worktree: String? = null,
30− val state: String? = null,
31− val config: String? = null,
32−)
app/src/main/java/soy/iko/opencode/data/model/Prompt.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import kotlinx.serialization.SerialName
4−import kotlinx.serialization.Serializable
5−
6−/** Body for `POST /session/:id/message`. */
7−@Serializable
8−data class PromptRequest(
9− val parts: List<PromptPart>,
10− val model: ModelRef? = null,
11− val agent: String? = null,
12−)
13−
14−/**
15− * An input part for a prompt — a discriminated union on `type` (the global class
16− * discriminator). We compose text and file (image/document attachment) parts; the server
17− * models more (agent, subtask) that this client doesn't send.
18− */
19−@Serializable
20−sealed interface PromptPart
21−
22−@Serializable
23−@SerialName("text")
24−data class TextPromptPart(val text: String) : PromptPart
25−
26−/**
27− * A file/image attachment. [url] must be a data URL carrying the base64 payload —
28− * `data:<mime>;base64,<bytes>` — which is how the server embeds media for the model to
29− * see (see opencode's message-v2.ts). [mime] must match the payload; the server forwards
30− * it as the model's mediaType.
31− */
32−@Serializable
33−@SerialName("file")
34−data class FilePromptPart(
35− val mime: String,
36− val url: String,
37− val filename: String? = null,
38−) : PromptPart
39−
40−/** Body for `POST /session/:id/command`. */
41−@Serializable
42−data class CommandRequest(
43− val command: String,
44− val arguments: String = "",
45− val agent: String? = null,
46−)
47−
48−/** Body for `POST /session/:id/revert`. */
49−@Serializable
50−data class RevertRequest(
51− val messageID: String,
52− val partID: String? = null,
53−)
54−
55−/** Body for `POST /session/:id/summarize`. */
56−@Serializable
57−data class SummarizeRequest(
58− val providerID: String,
59− val modelID: String,
60−)
61−
62−/** Body for `POST /session/:id/shell`. */
63−@Serializable
64−data class ShellRequest(
65− val agent: String,
66− val command: String,
67− val model: ModelRef? = null,
68−)
app/src/main/java/soy/iko/opencode/data/model/Provider.ktdeleted−84
@@ -1,84 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** Response of `GET /config/providers`. */
7−@Immutable
8−@Serializable
9−data class ProvidersResponse(
10− val providers: List<Provider> = emptyList(),
11− val default: Map<String, String> = emptyMap(),
12−)
13−
14−@Immutable
15−@Serializable
16−data class Provider(
17− // Defaulted so one id-less element in GET /config/providers doesn't fail the whole list decode
18− // (emptying the model picker) — matches MessageInfo's defaulted id and the resilient-decoding
19− // philosophy. A blank id is degraded but recoverable; a thrown decode is not.
20− val id: String = "",
21− val name: String? = null,
22− val models: Map<String, ModelInfo> = emptyMap(),
23−) {
24− val displayName: String get() = name?.takeIf { it.isNotBlank() } ?: id
25−}
26−
27−@Immutable
28−@Serializable
29−data class ModelInfo(
30− val id: String? = null,
31− val name: String? = null,
32−) {
33− fun displayName(modelKey: String): String =
34− name?.takeIf { it.isNotBlank() } ?: id ?: modelKey
35−}
36−
37−/** A flattened provider/model selection used by the prompt body and the model picker. */
38−@Immutable
39−@Serializable
40−data class ModelRef(
41− val providerID: String,
42− val modelID: String,
43−)
44−
45−/** A single selectable entry in the model picker, flattened from [ProvidersResponse]. */
46−@Immutable
47−data class ModelOption(
48− val providerID: String,
49− val modelID: String,
50− val providerLabel: String,
51− val modelLabel: String,
52−) {
53− val ref: ModelRef get() = ModelRef(providerID, modelID)
54−}
55−
56−/** Flatten providers into a sorted list of pickable options. */
57−fun ProvidersResponse.toOptions(): List<ModelOption> =
58− providers.flatMap { provider ->
59− provider.models.map { (modelKey, info) ->
60− ModelOption(
61− providerID = provider.id,
62− modelID = info.id ?: modelKey,
63− providerLabel = provider.displayName,
64− modelLabel = info.displayName(modelKey),
65− )
66− }
67− }.sortedWith(
68− // CASE_INSENSITIVE_ORDER compares in place; compareBy { it.x.lowercase() } would
69− // allocate a fresh lowercased string on every comparison (O(N log N) allocations).
70− compareBy<ModelOption, String>(String.CASE_INSENSITIVE_ORDER) { it.providerLabel }
71− .thenBy(String.CASE_INSENSITIVE_ORDER) { it.modelLabel },
72− )
73−
74−/** The default option to preselect: the server's default for some provider, else the first model. */
75−fun ProvidersResponse.defaultOption(options: List<ModelOption> = toOptions()): ModelOption? {
76− // Try each configured provider default in turn and take the first whose model actually
77− // survives in `options` (the list may be filtered). Checking only the first `default` entry
78− // would mispreselect an arbitrary first option whenever that one provider's default model
79− // isn't present, ignoring the other configured defaults.
80− for ((providerID, modelID) in default) {
81− options.firstOrNull { it.providerID == providerID && it.modelID == modelID }?.let { return it }
82− }
83− return options.firstOrNull()
84−}
app/src/main/java/soy/iko/opencode/data/model/Search.ktdeleted−101
@@ -1,101 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−
7−/**
8− * One ripgrep match from `GET /find?pattern=` (content search). [path] and [lines] are
9− * wrapped `{ text }` objects on the wire; [submatches] carry the column offsets of each
10− * hit within the line so the UI can highlight them.
11− */
12−@Immutable
13−@Serializable
14−data class FindMatch(
15− val path: TextField = TextField(),
16− val lines: TextField = TextField(),
17− @SerialName("line_number") val lineNumber: Int = 0,
18− @SerialName("absolute_offset") val absoluteOffset: Long = 0,
19− val submatches: List<SubMatch> = emptyList(),
20−) {
21− @Immutable
22− @Serializable
23− data class TextField(val text: String = "")
24−
25− @Immutable
26− @Serializable
27− data class SubMatch(
28− val start: Int = 0,
29− val end: Int = 0,
30− )
31−
32− /** The matched file's path (relative to the search root). */
33− val filePath: String get() = path.text
34−
35− /** The matching line's text, trimmed of a trailing newline for display. */
36− val lineText: String get() = lines.text.trimEnd('\n', '\r')
37−}
38−
39−/**
40− * One workspace symbol from `GET /find/symbol?query=`. [kind] is the LSP `SymbolKind`
41− * integer; [location.uri] is a file URI and [location.range] the symbol's span.
42− */
43−@Immutable
44−@Serializable
45−data class SymbolResult(
46− val name: String = "",
47− val kind: Int = 0,
48− val location: Location = Location(),
49−) {
50− @Immutable
51− @Serializable
52− data class Location(
53− val uri: String = "",
54− val range: Range = Range(),
55− )
56−
57− @Immutable
58− @Serializable
59− data class Range(
60− val start: Pos = Pos(),
61− val end: Pos = Pos(),
62− )
63−
64− @Immutable
65− @Serializable
66− data class Pos(
67− val line: Int = 0,
68− val character: Int = 0,
69− )
70−
71− /** The file path portion of [Location.uri], stripping a `file://` scheme when present.
72− * Handles both empty-authority (`file:///abs/path`) and non-empty-authority
73− * (`file://host/abs/path`) URIs by parsing the URI and taking its path component,
74− * rather than a prefix strip that would leave the authority glued to the path. */
75− val filePath: String
76− get() {
77− val uri = location.uri
78− // Only parse file: URIs; for anything else, return as-is.
79− if (!uri.startsWith("file:")) return uri
80− return runCatching { java.net.URI(uri).path }
81− .getOrNull()
82− ?.takeIf { it.isNotBlank() }
83− ?: uri.removePrefix("file://").ifBlank { uri }
84− }
85−
86− /** 1-based line for display; the wire range is 0-based. */
87− val displayLine: Int get() = location.range.start.line + 1
88−}
89−
90−// LSP SymbolKind → label. A map lookup (rather than a large `when`) keeps the accessor
91−// trivial. Indices follow the LSP SymbolKind enum.
92−private val symbolKindLabels = mapOf(
93− 1 to "file", 2 to "module", 3 to "namespace", 4 to "package", 5 to "class",
94− 6 to "method", 7 to "property", 8 to "field", 9 to "constructor", 10 to "enum",
95− 11 to "interface", 12 to "function", 13 to "variable", 14 to "constant", 15 to "string",
96− 16 to "number", 17 to "boolean", 18 to "array", 19 to "object", 20 to "key",
97− 22 to "enum member", 23 to "struct", 26 to "type",
98−)
99−
100−/** Human-readable label for an LSP [SymbolResult.kind]. */
101−fun symbolKindLabel(kind: Int): String = symbolKindLabels[kind] ?: "symbol"
app/src/main/java/soy/iko/opencode/data/model/ServerProfile.ktdeleted−27
@@ -1,27 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−
5−/**
6− * A saved opencode server connection. The [password] for HTTP Basic auth is resolved
7− * separately from EncryptedSharedPreferences and is null when not loaded/needed.
8− */
9−@Immutable
10−data class ServerProfile(
11− val id: String,
12− val label: String,
13− val baseUrl: String,
14− val username: String? = null,
15− val password: String? = null,
16− val lastUsed: Long = 0,
17− // When true, the client upgrades a cleartext http:// URL to https:// so credentials and
18− // traffic are never sent over the wire in the clear for this server.
19− val requireHttps: Boolean = false,
20− // Optional OkHttp certificate pin(s) ("sha256/<base64>", whitespace/comma-separated for
21− // multiple) applied to this server's TLS connection for defense against a rogue CA.
22− val certPin: String? = null,
23−) {
24− val hasAuth: Boolean get() = !username.isNullOrBlank()
25−
26− val displayLabel: String get() = label.takeIf { it.isNotBlank() } ?: baseUrl
27−}
app/src/main/java/soy/iko/opencode/data/model/Session.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−
6−/** A session as returned by `GET /session` and `POST /session`. */
7−@Immutable
8−@Serializable
9−data class Session(
10− // Defaulted so one id-less element in GET /session doesn't fail the whole list decode
11− // (emptying the session list) — matches MessageInfo's defaulted id and the resilient-decoding
12− // philosophy. A blank id is degraded but recoverable; a thrown decode is not.
13− val id: String = "",
14− val parentID: String? = null,
15− val title: String? = null,
16− val version: String? = null,
17− val time: TimeInfo? = null,
18− // The absolute worktree/directory the agent runs in for this session. Set server-side
19− // from the `directory` query param at creation; persisted per session so the client
20− // needn't re-send it on follow-up calls (see OpencodeApiClient.createSession).
21− val directory: String? = null,
22− val projectID: String? = null,
23− // Present only while the session is shared (POST /session/:id/share); cleared on unshare.
24− val share: Share? = null,
25− // Present only while a revert checkpoint is active (POST /session/:id/revert); cleared on unrevert.
26− val revert: Revert? = null,
27−) {
28− val displayTitle: String get() = title?.takeIf { it.isNotBlank() } ?: "Untitled session"
29−
30− /** A compact form of [directory] for list/subtitle display: the last path segment,
31− * or the full path when it has no separators. Null/blank when no directory is set. */
32− val displayDirectory: String?
33− get() = directory?.takeIf { it.isNotBlank() }?.trimEnd('/')?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
34−
35− /** True while the session has an active public share link. */
36− val isShared: Boolean get() = !share?.url.isNullOrBlank()
37−
38− /** True while a revert checkpoint is active (messages after it are hidden server-side). */
39− val isReverted: Boolean get() = revert != null
40−
41− /** Public share link for the session, from `POST /session/:id/share`. */
42− @Immutable
43− @Serializable
44− data class Share(val url: String = "")
45−
46− /** The active revert checkpoint, from `POST /session/:id/revert`. */
47− @Immutable
48− @Serializable
49− data class Revert(
50− val messageID: String = "",
51− val partID: String? = null,
52− val snapshot: String? = null,
53− val diff: String? = null,
54− )
55−}
56−
57−/** Body for `POST /session`. */
58−@Serializable
59−data class CreateSessionRequest(
60− val parentID: String? = null,
61− val title: String? = null,
62−)
63−
64−/** Body for `PATCH /session/:id`. */
65−@Serializable
66−data class UpdateSessionRequest(
67− val title: String? = null,
68−)
app/src/main/java/soy/iko/opencode/data/model/Todo.ktdeleted−95
@@ -1,95 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.Serializable
5−import kotlinx.serialization.builtins.ListSerializer
6−import kotlinx.serialization.json.Json
7−import kotlinx.serialization.json.JsonElement
8−
9−/** The tool name opencode uses to write the agent's task plan. */
10−const val TODO_WRITE_TOOL = "todowrite"
11−
12−/**
13− * A single entry in an agent's task plan, as written by opencode's `todowrite` tool.
14− * Every field is defaulted and decoding ignores unknown keys (see [parseTodos]) so a
15− * change to the tool's payload shape degrades to a best-effort render instead of
16− * dropping the whole plan.
17− */
18−@Immutable
19−@Serializable
20−data class TodoItem(
21− val id: String = "",
22− val content: String = "",
23− val status: String = "pending",
24− val priority: String? = null,
25−)
26−
27−/** Normalized lifecycle of a [TodoItem]; [UNKNOWN] covers any status the client doesn't model. */
28−enum class TodoStatus { PENDING, IN_PROGRESS, COMPLETED, CANCELLED, UNKNOWN }
29−
30−/** Normalized priority of a [TodoItem]; [NONE] covers null/unmodelled priorities. The order
31− * matters: HIGH > MEDIUM > LOW, used by [TodoPlan] tinting and a11y labels. */
32−enum class TodoPriority { HIGH, MEDIUM, LOW, NONE }
33−
34−fun TodoItem.priorityEnum(): TodoPriority = when ((priority ?: "").trim().lowercase()) {
35− "high", "h", "1", "urgent", "critical" -> TodoPriority.HIGH
36− "medium", "med", "m", "normal", "2" -> TodoPriority.MEDIUM
37− "low", "l", "3", "minor", "backlog" -> TodoPriority.LOW
38− else -> TodoPriority.NONE
39−}
40−
41−fun TodoItem.statusEnum(): TodoStatus = when (status.trim().lowercase()) {
42− "pending", "todo", "" -> TodoStatus.PENDING
43− "in_progress", "in-progress", "inprogress", "running", "active" -> TodoStatus.IN_PROGRESS
44− "completed", "complete", "done" -> TodoStatus.COMPLETED
45− "cancelled", "canceled", "skipped" -> TodoStatus.CANCELLED
46− else -> TodoStatus.UNKNOWN
47−}
48−
49−@Serializable
50−private data class TodoWriteInput(val todos: List<TodoItem> = emptyList())
51−
52−// A lenient decoder mirroring OpencodeJson's resilience (unknown keys ignored, nulls
53−// coerced to defaults) without pulling the network layer into data/model.
54−private val todoJson = Json {
55− ignoreUnknownKeys = true
56− isLenient = true
57− coerceInputValues = true
58− explicitNulls = false
59−}
60−
61−/**
62− * Extract the todo list from a `todowrite` tool call's input JSON. The tool sends the
63− * full list on every write, so a single call's input is a complete plan snapshot.
64− * Accepts either the documented `{ "todos": [...] }` object or a bare array, and returns
65− * an empty list on anything unparseable.
66− */
67−fun parseTodos(input: JsonElement?): List<TodoItem> {
68− if (input == null) return emptyList()
69− return runCatching {
70− todoJson.decodeFromJsonElement(TodoWriteInput.serializer(), input).todos
71− }.recoverCatching {
72− todoJson.decodeFromJsonElement(ListSerializer(TodoItem.serializer()), input)
73− }.getOrDefault(emptyList())
74−}
75−
76−/**
77− * The current task plan for a conversation: the todos of the most recent `todowrite`
78− * tool call that carries a non-empty, parseable list. opencode rewrites the whole list
79− * on every write, so a single call is a complete snapshot; scanning newest-first and
80− * skipping empties avoids a mid-stream write (input not yet arrived) briefly blanking a
81− * plan that's still valid.
82− */
83−fun currentTodoPlan(messages: List<MessageWithParts>): List<TodoItem> {
84− for (mi in messages.indices.reversed()) {
85− val parts = messages[mi].parts
86− for (pi in parts.indices.reversed()) {
87− val part = parts[pi]
88− if (part is ToolPart && part.tool.equals(TODO_WRITE_TOOL, ignoreCase = true)) {
89− val todos = parseTodos(part.state.inputElement())
90− if (todos.isNotEmpty()) return todos
91− }
92− }
93− }
94− return emptyList()
95−}
app/src/main/java/soy/iko/opencode/data/model/ToolState.ktdeleted−62
@@ -1,62 +0,0 @@
1−package soy.iko.opencode.data.model
2−
3−import androidx.compose.runtime.Immutable
4−import kotlinx.serialization.SerialName
5−import kotlinx.serialization.Serializable
6−import kotlinx.serialization.json.JsonElement
7−import kotlinx.serialization.json.JsonClassDiscriminator
8−
9−/**
10− * The state machine of a tool call, discriminated on `status`.
11− * pending -> running -> completed | error
12− */
13−@OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)
14−@Serializable
15−@JsonClassDiscriminator("status")
16−sealed interface ToolState
17−
18−@Serializable
19−@SerialName("pending")
20−data object ToolPending : ToolState
21−
22−@Immutable
23−@Serializable
24−@SerialName("running")
25−data class ToolRunning(
26− val input: JsonElement? = null,
27− val title: String? = null,
28− val time: PartTimeInfo? = null,
29−) : ToolState
30−
31−@Immutable
32−@Serializable
33−@SerialName("completed")
34−data class ToolCompleted(
35− val input: JsonElement? = null,
36− val output: String? = null,
37− val title: String? = null,
38− val time: PartTimeInfo? = null,
39−) : ToolState
40−
41−@Immutable
42−@Serializable
43−@SerialName("error")
44−data class ToolError(
45− val input: JsonElement? = null,
46− val error: String? = null,
47− val time: PartTimeInfo? = null,
48−) : ToolState
49−
50−/** Fallback for an unrecognized `status`. */
51−@Serializable
52−@SerialName("__unknown")
53−data object ToolUnknown : ToolState
54−
55−/** The raw input arguments carried by a tool call, present on the running/completed/error
56− * states (pending/unknown carry none). */
57−fun ToolState.inputElement(): JsonElement? = when (this) {
58− is ToolRunning -> input
59− is ToolCompleted -> input
60− is ToolError -> input
61− else -> null
62−}
app/src/main/java/soy/iko/opencode/data/network/CertPinUtil.ktdeleted−35
@@ -1,35 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.ServerProfile
4−
5−/**
6− * Shared helpers for resolving a [ServerProfile]'s certificate-pin field and the
7− * http→https upgrade it implies. The logic is used in three places that must agree:
8− * [HttpClientFactory] (the REST/SSE channel), [soy.iko.opencode.OpencodeApp]'s
9− * PinnedImageCallFactory (the image-loading channel), and [soy.iko.opencode.ui.components.RemoteImage]
10− * (resolving image base URLs). Previously each call site carried its own private copy
11− * with a "must be kept in sync" comment; the helpers here are the single source of truth.
12− */
13−internal object CertPinUtil {
14−
15− /** Split a certificate-pin field into individual OkHttp pins. Accepts whitespace- or
16− * comma-separated "sha256/<base64>" entries; blank entries are dropped. */
17− fun parseCertPins(raw: String?): List<String> =
18− raw?.split(Regex("[\\s,]+"))?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()
19−
20− /** The base URL after applying [ServerProfile.requireHttps]: a cleartext http:// URL is
21− * upgraded to https:// so the "Require HTTPS" choice is enforced at the transport layer.
22− * A configured certificate pin also forces TLS: a pin is meaningless over cleartext and
23− * would otherwise be silently dropped, so we honor the opt-in security control by upgrading
24− * rather than connecting unpinned in the clear. Relies on [HttpClientFactory.normalizeBaseUrl]
25− * for scheme/trailing-slash normalization. */
26− fun effectiveBaseUrl(profile: ServerProfile): String {
27− val normalized = HttpClientFactory.normalizeBaseUrl(profile.baseUrl)
28− val forceHttps = profile.requireHttps || parseCertPins(profile.certPin).isNotEmpty()
29− return if (forceHttps && normalized.lowercase().startsWith("http://")) {
30− "https://" + normalized.substring("http://".length)
31− } else {
32− normalized
33− }
34− }
35−}
app/src/main/java/soy/iko/opencode/data/network/EventStreamClient.ktdeleted−335
@@ -1,335 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.BusEvent
4−import soy.iko.opencode.util.safeExceptionSummary
5−import android.util.Log
6−import io.ktor.client.HttpClient
7−import io.ktor.client.plugins.timeout
8−import io.ktor.client.plugins.sse.sse
9−import io.ktor.sse.ServerSentEvent
10−import kotlinx.coroutines.CancellationException
11−import kotlinx.coroutines.CoroutineScope
12−import kotlin.coroutines.EmptyCoroutineContext
13−import kotlinx.coroutines.channels.BufferOverflow
14−import kotlinx.coroutines.channels.Channel
15−import kotlinx.coroutines.channels.ChannelResult
16−import kotlinx.coroutines.flow.Flow
17−import kotlinx.coroutines.flow.MutableStateFlow
18−import kotlinx.coroutines.flow.SharedFlow
19−import kotlinx.coroutines.flow.StateFlow
20−import kotlinx.coroutines.flow.SharingStarted
21−import kotlinx.coroutines.flow.asStateFlow
22−import kotlinx.coroutines.flow.buffer
23−import kotlinx.coroutines.flow.channelFlow
24−import kotlinx.coroutines.flow.shareIn
25−import kotlinx.coroutines.isActive
26−import kotlinx.coroutines.launch
27−import kotlinx.coroutines.selects.onTimeout
28−import kotlinx.coroutines.selects.select
29−import java.io.IOException
30−import kotlin.random.Random
31−
32−/**
33− * Owns the single long-lived `GET /event` SSE subscription and exposes it as a hot
34− * [SharedFlow] of [BusEvent]. The connection is opened when the first collector
35− * subscribes (WhileSubscribed) and reconnects with backoff on drop.
36− *
37− * Ordering contract: callers that send a prompt must already be collecting [events]
38− * (directly or via the repository) so early `message.part.updated` deltas aren't missed.
39− */
40−@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
41−open class EventStreamClient(
42− private val client: HttpClient,
43− private val scope: CoroutineScope,
44− private val idleTimeoutMs: Long = NetworkConfig.sseIdleTimeoutMs,
45− private val initialBackoffMs: Long = NetworkConfig.sseInitialBackoffMs,
46− private val maxBackoffMs: Long = NetworkConfig.sseMaxBackoffMs,
47− private val bufferCapacity: Int = NetworkConfig.sseEventBufferCapacity,
48−) {
49− protected constructor() : this(
50− HttpClient(io.ktor.client.engine.okhttp.OkHttp) {},
51− CoroutineScope(EmptyCoroutineContext),
52− )
53− enum class ConnectionState { Disconnected, Connecting, Connected, Failed, AuthFailed }
54−
55− private val _state = MutableStateFlow(ConnectionState.Disconnected)
56− open val state: StateFlow<ConnectionState> = _state.asStateFlow()
57−
58− /** Number of reconnect attempts made since the last successful [ConnectionState.Connected]
59− * period. Incremented each time the stream loop begins a new connection attempt after a
60− * drop, and reset to 0 on a successful connect. Surfaced so the UI can show "Reconnecting
61− * (attempt N)…" during a sustained outage, giving the user confidence the system is
62− * actively retrying rather than stuck. */
63− private val _reconnectAttempts = MutableStateFlow(0)
64− open val reconnectAttempts: StateFlow<Int> = _reconnectAttempts.asStateFlow()
65−
66− open val events: SharedFlow<BusEvent> by lazy {
67− stream()
68− .buffer(bufferCapacity, BufferOverflow.DROP_OLDEST)
69− .shareIn(
70− scope = scope,
71− started = SharingStarted.WhileSubscribed(stopTimeoutMillis = NetworkConfig.stateFlowSubscriptionTimeoutMs),
72− replay = 0,
73− )
74− }
75−
76− /** Conflated channel used to cut the reconnect backoff short when network returns. */
77− private val reconnectSignal = Channel<Unit>(Channel.CONFLATED)
78−
79− /** Classifies a non-retryable SSE failure so the UI can show the right recovery hint:
80− * an auth failure (401/403) reads "check credentials", while other 4xx (400/404/405…)
81− * reads "check the server URL and version". Returns null for transient/retryable errors. */
82− private enum class SseFailureKind { Auth, Other }
83−
84− private fun classifyNonRetryableSseFailure(e: Throwable): SseFailureKind? =
85− generateSequence(e as Throwable?) { it.cause.takeIf { c -> c !== it } }
86− .take(16)
87− .mapNotNull { t ->
88− when (t) {
89− is io.ktor.client.plugins.sse.SSEClientException -> t.response?.status?.value
90− is io.ktor.client.plugins.ClientRequestException -> t.response.status.value
91− else -> null
92− }
93− }
94− // Non-408/429 4xx = permanent; 408 and 429 stay in the transient retry path.
95− .map { code -> when {
96− code in 400..499 && code != 408 && code != 429 ->
97− if (code == 401 || code == 403) SseFailureKind.Auth else SseFailureKind.Other
98− else -> null
99− } }
100− .firstOrNull { it != null }
101−
102− /** Request an immediate reconnect, skipping any in-progress backoff. */
103− open fun triggerReconnect() { reconnectSignal.trySend(Unit) }
104−
105− /**
106− * Read SSE events from [events], racing each read against an idle-timeout watchdog.
107− * Throws [IOException] on idle timeout so the outer reconnect loop fires; breaks on
108− * clean stream close or scope cancellation.
109− *
110− * If the idle watchdog tripped because a [triggerReconnect] signal was consumed
111− * (rather than a genuine idle timeout), [onReconnectConsumed] is invoked so the outer
112− * reconnect loop can reconnect immediately instead of waiting out the backoff — the
113− * signal is already consumed, so the backoff `select` couldn't be cut short.
114− */
115− private suspend fun readSseEvents(
116− scope: CoroutineScope,
117− events: kotlinx.coroutines.channels.ReceiveChannel<ServerSentEvent>,
118− onReconnectConsumed: () -> Unit,
119− send: suspend (BusEvent) -> Unit,
120− ) {
121− while (scope.isActive) {
122− // The OkHttp engine has readTimeout=0 (the SSE stream must never time out on
123− // read), so a socket the peer never closed would otherwise hang until OS TCP
124− // keepalive kicks in — minutes to hours on stock Linux. If nothing arrives
125− // within the idle timeout, treat the connection as half-open and drop it.
126− var consumedReconnectSignal = false
127− val result: ChannelResult<ServerSentEvent>? = select {
128− events.onReceiveCatching { it }
129− onTimeout(idleTimeoutMs) { null }
130− // A triggerReconnect() issued while a read is active must interrupt it now:
131− // return the same null sentinel as the idle timeout so a half-open socket
132− // (no TCP RST) is dropped and reconnected promptly instead of waiting out
133− // idleTimeoutMs (~90s).
134− reconnectSignal.onReceive { consumedReconnectSignal = true; null }
135− }
136− if (result == null) {
137− if (consumedReconnectSignal) onReconnectConsumed()
138− throw IOException("SSE read dropped (idle timeout or reconnect requested), reconnecting")
139− }
140− val sse = result.getOrNull()
141− if (sse == null) {
142− // The producer channel is closed. A non-null cause means `incoming`
143− // failed (e.g. a socket reset bridged from the producer) — rethrow it so
144− // the outer loop logs and retries with backoff. A clean close (null
145− // cause) just ends this attempt and lets the loop reconnect.
146− result.exceptionOrNull()?.let { throw it }
147− break
148− }
149− val data = sse.data
150− if (data == null) {
151− // A comment or keep-alive event (no data field) resets the idle watchdog
152− // — servers send `: ping` comments to keep the connection alive through
153− // proxies. Without this, a server that only sends comments would still
154− // hit the idle timeout and reconnect unnecessarily.
155− continue
156− }
157− val event = try {
158− OpencodeJson.decodeFromString(BusEvent.serializer(), data)
159− } catch (e: kotlinx.serialization.SerializationException) {
160− Log.d("EventStream", "Skipping unparseable SSE event", e)
161− continue
162− }
163− if (_state.value != ConnectionState.Connected) {
164− _state.value = ConnectionState.Connected
165− }
166− send(event)
167− }
168− }
169−
170− private fun stream(): Flow<BusEvent> = channelFlow {
171− val scope = this
172− // Drain any stale reconnect signal from a previous collection cycle so it
173− // doesn't spuriously reset the backoff on startup (WhileSubscribed may have
174− // stopped the upstream while triggerReconnect() queued a signal).
175− while (reconnectSignal.tryReceive().isSuccess) { /* drain */ }
176− var backoffMs = initialBackoffMs
177− // Tracks whether this is the first iteration (the initial connect) vs a reconnect,
178− // so the attempt counter is only incremented on reconnects (not the first connect).
179− var firstAttempt = true
180− while (isActive) {
181− // Increment the reconnect-attempt counter on every iteration except the initial
182− // connect, so the UI can show "Reconnecting (attempt N)…". Reset to 0 on success.
183− if (firstAttempt) firstAttempt = false else _reconnectAttempts.value++
184− _state.value = ConnectionState.Connecting
185− // Set by readSseEvents when a triggerReconnect() signal interrupted an active
186− // read. The signal is consumed to drop the socket, so the backoff select below
187− // can't also see it — without this flag the reconnect would wait the full
188− // backoff despite the caller asking for an immediate reconnect (network
189− // handoff, manual refresh, ...).
190− var reconnectConsumedDuringRead = false
191− try {
192− // The SSE stream is long-lived: disable the request-level and socket
193− // timeouts (the client default is 60s for REST) in the request config
194− // so the connection isn't killed mid-stream. The idle-timeout watchdog
195− // below handles half-open connections instead.
196− client.sse(
197− "event",
198− request = {
199− timeout {
200− requestTimeoutMillis = Long.MAX_VALUE
201− // Disable the socket (read) timeout entirely for the SSE stream.
202− // A finite value would kill the connection whenever the server
203− // is quiet for longer than that (idle sessions, slow agent runs),
204− // causing a reconnect storm. Half-open detection is handled by
205− // the idle-timeout watchdog below plus OkHttp's pingInterval on
206− // HTTP/2 connections.
207− socketTimeoutMillis = Long.MAX_VALUE
208− }
209− },
210− ) {
211− // The SSE block is open — the connection is established. Mark as
212− // Connected immediately so downstream re-seed logic fires even when
213− // the server only sends keep-alive comments (no data events).
214− if (_state.value != ConnectionState.Connected) {
215− _state.value = ConnectionState.Connected
216− }
217− // Clear any stale reconnect signal from a triggerReconnect() call
218− // made while the previous stream was healthy, so it doesn't suppress
219− // the next legitimate backoff.
220− while (reconnectSignal.tryReceive().isSuccess) { /* drain */ }
221− // Bridge ktor's `incoming` flow to a channel so each element can be
222− // raced against the idle-timeout watchdog via select. We collect it
223− // ourselves instead of `incoming.produceIn(scope)`: produceIn launches
224− // the collector as a child of this channelFlow, so when `incoming`
225− // throws on an abnormal socket close — a TCP reset, i.e. the common
226− // mobile case: Wi-Fi⇄cellular handoff, server or proxy RST — the child's
227− // failure cancels the whole channelFlow and bypasses the retry `catch`
228− // below. That killed reconnect outright and surfaced the IOException as
229− // an uncaught crash through the (handler-less) shareIn scope. Collecting
230− // into our own channel and closing it with the cause keeps the failure
231− // local: readSseEvents sees the closed channel, rethrows the cause, and
232− // the normal retry/backoff path handles it. (A clean EOF closes the
233− // channel with no cause → readSseEvents breaks and reconnects as before.)
234− val events = Channel<ServerSentEvent>(Channel.BUFFERED)
235− val producer = scope.launch {
236− try {
237− incoming.collect { events.send(it) }
238− events.close()
239− } catch (c: CancellationException) {
240− events.close(c)
241− throw c
242− } catch (t: Throwable) {
243− // Deliver the failure via the channel rather than letting it
244− // propagate up and cancel the parent channelFlow.
245− events.close(t)
246− }
247− }
248− // Reset the backoff only once real data actually arrives, not on
249− // block entry: a server that accepts the connection then immediately
250− // drops it would otherwise loop forever at the initial backoff and
251− // never escalate the exponential ramp.
252− var receivedAny = false
253− try {
254− readSseEvents(scope, events, { reconnectConsumedDuringRead = true }) {
255− if (!receivedAny) {
256− receivedAny = true
257− backoffMs = initialBackoffMs
258− // A genuine event confirms the connection is healthy, so reset
259− // the reconnect-attempt counter for the next outage's count.
260− _reconnectAttempts.value = 0
261− }
262− send(it)
263− }
264− } finally {
265− producer.cancel()
266− events.cancel()
267− }
268− }
269− } catch (c: CancellationException) {
270− _state.value = ConnectionState.Disconnected
271− throw c
272− } catch (e: Exception) {
273− // If the scope was cancelled (e.g. connection close), the closed-client
274− // exception is expected — don't log a spurious "stream error" warning.
275− val failureKind = classifyNonRetryableSseFailure(e)
276− if (failureKind != null) {
277− // The server rejected the request with a non-retryable 4xx (bad
278− // credentials, missing endpoint, ...) — retrying won't help. Log a
279− // scrubbed summary (class + status) instead of the full exception, whose
280− // message carries the request URL and may include auth or paths.
281− Log.w("EventStream", "SSE non-retryable 4xx (${if (failureKind == SseFailureKind.Auth) "auth" else "endpoint"}), awaiting explicit reconnect: ${safeExceptionSummary(e)}")
282− _state.value = if (failureKind == SseFailureKind.Auth) ConnectionState.AuthFailed else ConnectionState.Failed
283− if (!isActive) {
284− // Final teardown (last subscriber left) while a 4xx surfaced: end in
285− // Disconnected like every other loop-exit path. Failed must stay
286− // observable only while the flow is live/retrying, not after teardown.
287− _state.value = ConnectionState.Disconnected
288− break
289− }
290− // Don't complete the flow: a subscriber may fix the profile and call
291− // triggerReconnect(). Suspend until an explicit reconnect signal
292− // arrives (no backoff delay), then re-attempt the connection. This receive
293− // is outside the try above, so reset state to Disconnected if the last
294− // subscriber leaves (cancellation) while we're parked here — otherwise the
295− // stream would be torn down with state stuck at Failed.
296− try {
297− reconnectSignal.receive()
298− } catch (c: CancellationException) {
299− _state.value = ConnectionState.Disconnected
300− throw c
301− }
302− continue
303− } else if (isActive) {
304− Log.w("EventStream", "SSE stream error, will retry: ${safeExceptionSummary(e)}")
305− }
306− }
307− _state.value = ConnectionState.Disconnected
308− if (!isActive) break
309− // Wait for the backoff, but allow a reconnect signal to cut it short. When
310− // readSseEvents consumed a triggerReconnect() signal to drop an active read,
311− // the signal is already spent so the select below can't receive it — pass a
312− // zero backoff in that case so the reconnect is immediate (the whole point of
313− // triggerReconnect: network handoff, manual refresh, ...).
314− val signaled = waitForBackoffOrSignal(reconnectConsumedDuringRead, backoffMs)
315− backoffMs = if (signaled) initialBackoffMs else (backoffMs * 2).coerceAtMost(maxBackoffMs)
316− }
317− }
318−
319− /** Suspend for the backoff unless [reconnectConsumedDuringRead] (immediate) or a new
320− * [triggerReconnect] arrives during the wait. Returns true when the reconnect should
321− * skip the backoff ramp (signal-driven), false when the full backoff elapsed. */
322− private suspend fun waitForBackoffOrSignal(
323− reconnectConsumedDuringRead: Boolean,
324− backoffMs: Long,
325− ): Boolean {
326− if (reconnectConsumedDuringRead) return true
327− var signaled = false
328− val jitter = ((backoffMs * NetworkConfig.retryJitterFactor) * (Random.nextDouble() * 2 - 1)).toLong()
329− select {
330− reconnectSignal.onReceive { signaled = true }
331− onTimeout((backoffMs + jitter).coerceAtLeast(0)) { /* normal backoff elapsed */ }
332− }
333− return signaled
334− }
335−}
app/src/main/java/soy/iko/opencode/data/network/HttpClientFactory.ktdeleted−167
@@ -1,167 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.ServerProfile
4−import io.ktor.client.HttpClient
5−import io.ktor.client.engine.okhttp.OkHttp
6−import io.ktor.client.plugins.HttpTimeout
7−import io.ktor.client.plugins.api.Send
8−import io.ktor.client.plugins.api.createClientPlugin
9−import io.ktor.client.plugins.auth.Auth
10−import io.ktor.client.plugins.auth.providers.BasicAuthCredentials
11−import io.ktor.client.plugins.auth.providers.basic
12−import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
13−import io.ktor.client.plugins.defaultRequest
14−import io.ktor.client.plugins.sse.SSE
15−import io.ktor.http.HttpHeaders
16−import io.ktor.http.URLBuilder
17−import io.ktor.http.takeFrom
18−import io.ktor.serialization.kotlinx.json.json
19−import okhttp3.CertificatePinner
20−import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
21−import java.util.concurrent.TimeUnit
22−
23−/**
24− * Builds a Ktor client bound to a single [ServerProfile]. One client per active
25− * profile: it carries the base URL, optional Basic auth, JSON negotiation, and the
26− * SSE plugin used for `GET /event`.
27− */
28−object HttpClientFactory {
29−
30− fun create(profile: ServerProfile): HttpClient {
31− val normalizedUrl = CertPinUtil.effectiveBaseUrl(profile)
32− val isHttps = normalizedUrl.lowercase().startsWith("https://")
33− // Parse the host with OkHttp's own parser (not java.net.URI, which rejects hosts OkHttp
34− // accepts, e.g. underscores in "my_server.local"). If pinning is configured over HTTPS
35− // but the host can't be parsed, fail closed: never build an unpinned client — that would
36− // be a silent security downgrade for a user who opted into pinning.
37− val pinHost = normalizedUrl.toHttpUrlOrNull()?.host
38− val pins = CertPinUtil.parseCertPins(profile.certPin)
39− if (pins.isNotEmpty() && isHttps && pinHost == null) {
40− throw IllegalStateException(
41− "Certificate pinning is configured but the server host could not be parsed from $normalizedUrl",
42− )
43− }
44−
45− return HttpClient(OkHttp) {
46− expectSuccess = true
47−
48− engine {
49− config {
50− // A normal read timeout for REST calls. The SSE stream overrides this
51− // to infinite inside the sse {} request block (see EventStreamClient),
52− // so the long-lived event connection is never killed mid-stream.
53− readTimeout(NetworkConfig.readTimeoutSeconds, TimeUnit.SECONDS)
54− connectTimeout(NetworkConfig.connectTimeoutSeconds, TimeUnit.SECONDS)
55− retryOnConnectionFailure(true)
56− pingInterval(NetworkConfig.pingIntervalSeconds, TimeUnit.SECONDS)
57− // Pin the server certificate(s) when configured and connecting over TLS.
58− // A malformed pin throws here (surfaced as a connection failure), which is
59− // the right fail-closed behavior for a security control the user opted into.
60− if (pins.isNotEmpty() && pinHost != null && isHttps) {
61− certificatePinner(
62− CertificatePinner.Builder().apply { pins.forEach { add(pinHost, it) } }.build(),
63− )
64− }
65− }
66− }
67−
68− install(ContentNegotiation) {
69− json(OpencodeJson)
70− }
71−
72− install(SSE)
73−
74− // Request-level timeout for REST calls. The SSE stream overrides this to
75− // infinite inside the sse {} request block (see EventStreamClient) so the
76− // long-lived /event connection isn't killed after 60s. The engine's connect
77− // timeout and the SSE idle-timeout watchdog handle stuck SSE connections.
78− install(HttpTimeout) {
79− requestTimeoutMillis = NetworkConfig.restRequestTimeoutMs
80− }
81−
82− if (profile.hasAuth) {
83− if (isHttps) {
84− install(Auth) {
85− basic {
86− credentials {
87− BasicAuthCredentials(
88− username = profile.username.orEmpty(),
89− password = profile.password.orEmpty(),
90− )
91− }
92− // Send eagerly so opencode doesn't need a 401 challenge round-trip, but
93− // only to the configured host: a cross-host redirect must not carry the
94− // credentials off-origin (the plugin would still answer a genuine 401 from
95− // the real host reactively). The Auth plugin is only installed for HTTPS
96− // profiles — over HTTP, even reactive credential sending would leak
97− // passwords in cleartext, so we don't install it at all.
98− sendWithoutRequest { request ->
99− pinHost != null && request.url.host.equals(pinHost, ignoreCase = true)
100− }
101− }
102− }
103− // Defense in depth mirroring the HTTP branch below: sendWithoutRequest only gates
104− // *eager* attachment on the outgoing request — it neither strips an Authorization
105− // header that HttpRedirect copies from the original (configured-host) request onto
106− // a cross-origin redirect target, nor stops the reactive Basic provider answering a
107− // 401 from such a target. followRedirects is enabled by default, so re-check the
108− // host on every physical send and remove the header whenever it isn't the pinned
109− // host, guaranteeing credentials never leave the configured origin.
110− install(
111− createClientPlugin("HttpsBasicAuthHostScoped") {
112− on(Send) { request ->
113− if (pinHost == null || !request.url.host.equals(pinHost, ignoreCase = true)) {
114− request.headers.remove(HttpHeaders.Authorization)
115− }
116− proceed(request)
117− }
118− },
119− )
120− } else if (pinHost != null) {
121− // For HTTP profiles with auth, attach the Basic header proactively (the reactive
122− // Auth plugin is skipped for non-HTTPS so a 401 can't silently re-send credentials
123− // in cleartext), but scope it to the configured host and re-check on EVERY physical
124− // send. Redirects matter: Ktor builds the redirect request by copying the original
125− // headers, so an unconditional header would carry the cleartext credentials to a
126− // cross-host redirect target. Setting it here (and stripping it off-host) mirrors
127− // the HTTPS path's sendWithoutRequest host guard so credentials never go off-origin.
128− val credentials = java.util.Base64.getEncoder().encodeToString(
129− "${profile.username.orEmpty()}:${profile.password.orEmpty()}".toByteArray(),
130− )
131− install(
132− createClientPlugin("HttpBasicAuthHostScoped") {
133− on(Send) { request ->
134− if (request.url.host.equals(pinHost, ignoreCase = true)) {
135− request.headers[HttpHeaders.Authorization] = "Basic $credentials"
136− } else {
137− request.headers.remove(HttpHeaders.Authorization)
138− }
139− proceed(request)
140− }
141− },
142− )
143− }
144− }
145−
146− defaultRequest {
147− url.takeFrom(URLBuilder().takeFrom(normalizedUrl))
148− }
149− }
150− }
151−
152− /** Ensure a scheme and a single trailing slash so relative paths resolve correctly.
153− * Defaults to [https] when no scheme is given so credentials aren't accidentally
154− * sent over cleartext. Users who need plain HTTP must type the scheme explicitly. */
155− fun normalizeBaseUrl(raw: String): String {
156− val trimmed = raw.trim()
157− // Compare the scheme prefix case-insensitively (a lowercased copy) while
158− // preserving the original casing of the rest of the URL in the output.
159− val lowerTrimmed = trimmed.lowercase()
160− val withScheme = if (lowerTrimmed.startsWith("http://") || lowerTrimmed.startsWith("https://")) {
161− trimmed
162− } else {
163− "https://$trimmed"
164− }
165− return if (withScheme.endsWith("/")) withScheme else "$withScheme/"
166− }
167−}
app/src/main/java/soy/iko/opencode/data/network/NetworkConfig.ktdeleted−442
@@ -1,442 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−/**
4− * Centralized tuning parameters for the network and presentation layers. Keeping these
5− * in one place makes them easy to find and adjust without hunting through source files,
6− * and makes the intent of each value explicit rather than a bare magic number.
7− */
8−object NetworkConfig {
9−
10− // --- OkHttp engine timeouts (HttpClientFactory) ---
11−
12− /** Socket connect timeout for all HTTP calls, including the SSE handshake. */
13− const val connectTimeoutSeconds = 30L
14− /** Socket read timeout for ordinary REST calls. The SSE stream overrides this to INFINITE. */
15− const val readTimeoutSeconds = 60L
16− /** OkHttp WebSocket/interval ping, keeping the SSE socket alive through proxies. */
17− const val pingIntervalSeconds = 20L
18− /** Request-level timeout for REST calls (covers connect + headers + body). The SSE stream overrides this to INFINITE. */
19− const val restRequestTimeoutMs = 60_000L
20−
21− // --- REST retry (OpencodeApiClient.withRetry) ---
22−
23− /** Maximum number of attempts for a retriable REST call. */
24− const val retryMaxAttempts = 3
25− /** Initial backoff delay; doubles on each successive failure (exponential backoff). */
26− const val retryInitialDelayMs = 500L
27− /** Cap on a single retry backoff delay, guarding against overflow at high attempt counts. */
28− const val retryMaxDelayMs = 30_000L
29− /** Jitter factor for retry backoff (0.2 = ±20% symmetric random jitter on each delay). */
30− const val retryJitterFactor = 0.2
31−
32− // --- SSE stream (EventStreamClient) ---
33−
34− /** Initial reconnect backoff after an SSE stream drop; doubles up to [sseMaxBackoffMs]. */
35− const val sseInitialBackoffMs = 500L
36− /** Cap on the SSE reconnect backoff. */
37− const val sseMaxBackoffMs = 10_000L
38− /** Reconnect-attempt count at which the connection banner switches from "Reconnecting…"
39− * to "Reconnecting (attempt N)…" — after a few retries the user benefits from seeing the
40− * system is actively retrying rather than stuck. Below this the plain label is calmer. */
41− const val sseReconnectAttemptLabelThreshold = 3
42− /** Max gap between events before a silent/half-open SSE connection is dropped and reconnected. */
43− const val sseIdleTimeoutMs = 90_000L
44− /** Buffer capacity for the SSE events SharedFlow; prevents a slow subscriber stalling the read loop. */
45− const val sseEventBufferCapacity = 64
46−
47− // --- Connectivity monitor (AppContainer) ---
48−
49− /** Grace period after a network is lost before reporting offline. Absorbs the transient
50− * window during a Wi-Fi→cellular handoff where onLost(WiFi) fires before the replacement
51− * network becomes active (cm.activeNetwork is briefly null), so a handoff doesn't flash
52− * offline while a genuine loss (no active network after the grace) is still caught. */
53− const val networkOfflineGraceMs = 2_000L
54−
55− // --- Catalog cache (OpencodeApiClient) ---
56−
57− /** How long cached catalog responses (providers/agents/commands) are considered fresh. */
58− const val catalogCacheTtlMs = 60_000L
59−
60− /** TTL for files written to the cache dir to hand to external apps via FileProvider
61− * (open-externally). Stale files past this age are pruned on the next open so repeated
62− * opens of large files don't accumulate unbounded. 24h covers a typical session. */
63− const val externalCacheTtlMs = 24L * 60 * 60 * 1000
64−
65− // --- Session list (SessionListViewModel) ---
66−
67− /** Max sessions to fetch previews for in one batch. */
68− const val maxPreviewSessions = 50
69− /** Initial render window for the session list — the number of rows composed before the
70− * user scrolls to reveal more. Grows by [sessionListPageStep] as the user nears the
71− * bottom, bounding the sort/filter work on a huge list while keeping scrolling seamless. */
72− const val sessionListInitialPage = 60
73− /** How many additional rows to reveal when the session list render window is exhausted. */
74− const val sessionListPageStep = 60
75− /** Initial render window for the file-browser directory listing. A huge directory
76− * (10k+ entries) sorts/filters in full on each recomposition; windowing the render
77− * bounds the composed-row count while the sort still runs over the full list (so the
78− * order is correct, just the visible slice is capped). Grows as the user scrolls. */
79− const val fileListInitialPage = 100
80− /** How many additional file rows to reveal when the render window is exhausted. */
81− const val fileListPageStep = 100
82− /** Max concurrent preview fetches (prevents flooding the server with parallel requests). */
83− const val maxConcurrentPreviews = 8
84− /** Max characters of a session's last message to keep as a list preview. */
85− const val previewTextMaxLength = 200
86− /** Debounce delay before fetching a session preview after an SSE update, so a burst
87− * of SessionUpdated events (e.g. during active streaming) coalesces into one fetch
88− * instead of launching one per event (each downloading the full message history). */
89− const val previewDebounceMs = 500L
90− /** Debounce for applying SessionUpdated SSE events to the session list state. During
91− * active streaming the server emits these frequently; without debouncing each one
92− * triggers a full list filter + sort + recomposition, causing scroll jank. */
93− const val sessionUpdateDebounceMs = 300L
94−
95− // --- Global search (GlobalSearchViewModel) ---
96−
97− /** Max sessions whose message history is scanned in one global-search pass. Global
98− * search downloads each session's messages, so this bounds the work; if there are more
99− * sessions, the result set notes that the search was truncated. */
100− const val maxSearchSessions = 50
101− /** Debounce before a global search fires, so typing doesn't launch a fetch per keystroke. */
102− const val searchDebounceMs = 350L
103− /** Minimum query length before a global search runs (shorter queries match too much). */
104− const val minSearchQueryLength = 2
105− /** Characters of context to show around a global-search match. */
106− const val searchSnippetLength = 160
107−
108− // --- Message cache (MessageCacheStore) ---
109−
110− /** Minimum interval between on-disk writes of a session's message snapshot, so a fast
111− * token stream doesn't hammer the disk. The cache only needs to be recent enough for an
112− * instant/offline first paint; the network corrects it on the next open. */
113− const val messageCacheWriteThrottleMs = 2_000L
114−
115− /** Grace period before a deferred session delete actually fires, during which an
116− * Undo snackbar lets the user cancel it. */
117− const val undoDeleteDelayMs = 5_000L
118−
119− /** Grace period before a deferred server-profile delete actually fires, during which
120− * an Undo snackbar lets the user cancel it. Same UX rationale as [undoDeleteDelayMs]. */
121− const val undoServerDeleteDelayMs = 5_000L
122−
123− /** Grace period before a deferred crash-report delete actually fires, during which
124− * an Undo snackbar lets the user cancel it. */
125− const val undoReportDeleteDelayMs = 5_000L
126−
127− // --- In-memory message store (SessionRepository.MessageStore) ---
128−
129− /** Max messages to keep in memory per observed session; oldest are evicted beyond this. */
130− const val maxInMemoryMessages = 500
131−
132− // --- File viewer (FileViewScreen) ---
133−
134− /** Cap on how many lines the raw viewer renders and searches. A multi-megabyte file is
135− * split once (not twice) into this many lines at most, so it can't hold two full line
136− * lists in memory or stall the LazyColumn; beyond the cap a truncation banner is shown. */
137− const val maxRenderedFileLines = 5000
138−
139− // --- File browser (FileBrowserViewModel) ---
140−
141− /** Debounce delay before firing a file-search request after the user stops typing. */
142− const val fileSearchDebounceMs = 250L
143−
144− /** Debounce delay before re-running the in-conversation message search after the user
145− * stops typing. The search walks every part of every message (including stringifying
146− * tool state), so debouncing avoids jank on long conversations. The filter itself runs
147− * off the main thread; this delay coalesces rapid keystrokes. */
148− const val chatSearchDebounceMs = 200L
149−
150− // --- Attachments (chat composer) ---
151−
152− /** Max size of a single attachment (image/file) before it's rejected. Base64 inflates
153− * the payload ~33%, and the whole prompt body is held in memory, so cap generously but
154− * finitely to avoid OOM / oversized requests. */
155− const val maxAttachmentBytes = 10L * 1024 * 1024
156−
157− /** Max number of attachments staged for one prompt, to bound memory and request size. */
158− const val maxAttachments = 8
159−
160− /** Max cumulative size of all attachments staged for one prompt. The per-file
161− * [maxAttachmentBytes] cap alone allows [maxAttachments] max-size files (~80MB raw,
162− * ~106MB as base64) to pile up in memory and be re-serialized on every add/remove and
163− * again when the request body is built — a realistic OOM. This bounds the whole set. */
164− const val maxTotalAttachmentBytes = 25L * 1024 * 1024
165−
166− // --- StateFlow sharing (WhileSubscribed) ---
167−
168− /** Grace period before a cold StateFlow is stopped after its last subscriber leaves. */
169− const val stateFlowSubscriptionTimeoutMs = 5_000L
170−
171− /** Maximum time a notification action BroadcastReceiver may hold its goAsync()
172− * PendingResult open. The system ANRs a receiver that doesn't call finish() within
173− * ~10s, so this must stay below that; a slow permission-respond retry (withRetry
174− * exponential backoff up to ~90s) or a blocked outbox enqueue could otherwise blow
175− * past the window. The watchdog finishes the PendingResult at this deadline so the
176− * receiver never ANRs; the underlying network call keeps running on the app scope. */
177− const val notificationReceiverTimeoutMs = 8_000L
178−
179− // --- Draft persistence (ChatViewModel) ---
180−
181− /** Debounce delay before persisting a draft to disk after the user stops typing. */
182− const val draftDebounceMs = 500L
183−
184− /** Maximum characters allowed in the chat input field. A generous cap that prevents
185− * a huge paste from stalling the UI (the field would otherwise buffer and lay out
186− * an unbounded string) while leaving plenty of room for long prompts. */
187− const val maxDraftLengthChars = 32_000
188−
189− /** Show the "remaining characters" supportingText under the chat input once the
190− * draft length crosses this fraction of [maxDraftLengthChars], so the cap is
191− * visible before it silently kicks in but doesn't clutter a normal short prompt. */
192− const val draftCountdownThresholdFraction = 0.8f
193−
194− /** Maximum characters allowed in a session title (rename dialog). Prevents the
195− * server from rejecting an overly long title and keeps list rows readable. */
196− const val maxSessionTitleChars = 200
197−
198− // --- Profile store (ServerEditViewModel) ---
199−
200− /** Timeout for loading a profile from DataStore before giving up. */
201− const val profileLoadTimeoutMs = 5_000L
202−
203− /** Timeout for a credential test (probe) before giving up, so a hung/unresponsive server
204− * doesn't leave the "Testing…" spinner spinning indefinitely. */
205− const val testCredentialsTimeoutMs = 15_000L
206−
207− // --- SSE stream (EventStreamClient, AppContainer) ---
208−
209− /** Delay before retrying the message-activity observer after a failure. */
210− const val observerRetryDelayMs = 5_000L
211− /** Debounce before the run foreground-service is started/stopped in response to
212− * run-activity changes. A run that starts and then fails/idles almost immediately
213− * would otherwise dispatch startForegroundService() then stopService() back-to-back;
214− * if the stop wins the race before startForeground() runs, Android raises the
215− * "did not then call startForeground()" crash. Debouncing collapses that window.
216− * Also serves as a minimum-run-duration gate: a run shorter than this (a quick abort,
217− * a one-token reply) clears [anyRunActive] before the FGS ever posts, so the shade
218− * stays clean of non-dismissable notifications for trivially short runs. The Doze-
219− * resilience benefit only matters for long runs, so a few seconds of gate preserves
220− * the core benefit. */
221− const val runForegroundDebounceMs = 3_000L
222−
223− // --- Markdown rendering (MarkdownText) ---
224−
225− /** Throttle delay to coalesce streaming tokens into one re-parse. The markdown
226− * library re-parses the full AST on every content change, so during a long streaming
227− * response this is O(n²) work. 50ms (~20fps) is smooth for progressively appearing
228− * text while cutting parse work ~3x versus a per-frame (16ms) throttle. */
229− const val streamingThrottleMs = 50L
230−
231− // --- Snackbar one-shot events (ViewModels) ---
232−
233− /** Buffer capacity for transient error SharedFlows that drive snackbars. */
234− const val snackbarEventBufferCapacity = 16
235−
236− /** How long the chat top-bar refresh icon stays in its "refreshing" spinner state
237− * after a tap, giving immediate feedback that the refresh was triggered even when
238− * the connection state is already Connected (so the ConnectionBanner doesn't change). */
239− const val refreshFeedbackMs = 1_200L
240−
241− // --- UI layout constants ---
242−
243− /** Minimum window width (dp) for two-pane layout on tablets / unfolded foldables. */
244− const val twoPaneWidthThresholdDp = 840
245− /** Maximum width fraction a user message bubble can occupy (keeps it readable). */
246− const val userBubbleWidthFraction = 0.85f
247− /** Minimum number of options in a picker sheet (model/agent/command) before its search
248− * field auto-focuses and raises the keyboard on open. A tiny catalog is faster to scan by
249− * eye, so popping the keyboard for it is just friction. */
250− const val pickerSearchAutofocusThreshold = 8
251−
252− /** Minimum number of saved server profiles before the server list shows its search/filter
253− * field. A typical user has one or two servers, where scanning by eye beats typing; power
254− * users juggling many profiles get the filter once it earns its space. */
255− const val serverListSearchThreshold = 5
256−
257− /** Minimum number of crash reports before the diagnostics list shows its search field. */
258− const val diagnosticsSearchThreshold = 8
259−
260− /** Initial render window for the diagnostics crash-report list — the number of rows
261− * composed before the user scrolls to reveal more. Bounds composition work on a device
262− * that has accumulated many crash reports. Grows by [diagnosticsListPageStep] as the
263− * user nears the bottom. */
264− const val diagnosticsListInitialPage = 60
265− /** How many additional crash-report rows to reveal when the render window is exhausted. */
266− const val diagnosticsListPageStep = 60
267−
268− /** Minimum number of sessions in the usage report before the per-session list shows its
269− * filter field. A short history is faster to scan than type into. */
270− const val usageSessionSearchThreshold = 8
271−
272− /** Minimum number of sessions before the session list shows its search/filter field.
273− * Matches the sibling screens' convention: a short list is faster to scan by eye than
274− * type into, so the field earns its vertical space only once the list grows. */
275− const val sessionListSearchThreshold = 5
276− /** Extra bottom content padding (dp) for the chat message list, reserving room for the
277− * jump-to-latest FAB so it never floats over the last message. */
278− const val chatListFabInsetDp = 80
279−
280− /** Extra bottom content padding (dp) for single-pane list screens that host a FAB
281− * (session list, server list, MCP), reserving room so the FAB never floats over the
282− * last row. Unified across screens so the inset doesn't drift (the session list
283− * previously hardcoded 96dp while the chat list used [chatListFabInsetDp]). */
284− const val listFabInsetDp = 96
285− /** Left pane weight in the two-pane layout (session list). */
286− const val twoPaneLeftWeight = 0.38f
287− /** Right pane weight in the two-pane layout (chat detail). */
288− const val twoPaneRightWeight = 0.62f
289−
290− /** Maximum width (dp) for the left (session-list) pane in the two-pane layout. On a wide
291− * tablet the list pane would otherwise stretch too wide for a readable row density; capping
292− * it keeps the list compact and gives the chat detail pane the remaining space. */
293− const val twoPaneLeftMaxWidthDp = 460
294−
295− /** Minimum window width (dp) at which a NavigationRail is shown alongside the
296− * two-pane layout for top-level destination discoverability on large screens. Sits below
297− * [twoPaneWidthThresholdDp] (M3's WindowWidthSizeClass.Medium breakpoint ~600dp) so a
298− * tablet or landscape phone gets the rail while staying single-pane until 840dp, where the
299− * two-pane master/detail split takes over. */
300− const val navigationRailThresholdDp = 600
301−
302− /** Maximum width (dp) for the chat message list on large screens. On a tablet or
303− * unfolded foldable, full-width message bubbles stretch edge-to-edge, hurting
304− * readability — capping and centering the list (like Gmail/Telegram on tablets)
305− * keeps line lengths comfortable. Applied only above [twoPaneWidthThresholdDp]. */
306− const val chatContentMaxWidthDp = 800
307−
308− /** Maximum width (dp) for a single-pane list/form screen on large screens (Diagnostics,
309− * MCP, Usage, Global Search, File Browser). Mirrors [chatContentMaxWidthDp]'s rationale
310− * at a tighter width suited to dense list rows and form fields. Settings and ServerEdit
311− * use 600dp directly; this constant centralizes the same value for the screens that
312− * previously stretched edge-to-edge on tablets. */
313− const val listContentMaxWidthDp = 600
314−
315− /** Maximum width (dp) for the full-screen chat composer dialog on large screens, so
316− * the editor doesn't stretch edge-to-edge on a tablet (matching [chatContentMaxWidthDp]'s
317− * readability rationale for the message list). */
318− const val composerDialogMaxWidthDp = 800
319−
320− /** Maximum height (dp) for a modal bottom sheet's list area. Resolved against the screen
321− * (not the partial sheet) so a sheet that starts fully expanded shows a predictable list
322− * height regardless of the sheet's drag position. */
323− const val pickerSheetMaxHeightDp = 560
324−
325− /** Maximum inline height (dp) for an image attachment in the chat list. A tall image
326− * caps at this so it doesn't dominate the bubble; tapping opens the fullscreen viewer. */
327− const val inlineImageMaxHeightDp = 320
328−
329− /** Minimum inline height (dp) reserved for an image placeholder (loading/error/resolving),
330− * so the layout doesn't jump when the load completes and the image's intrinsic size is known. */
331− const val inlineImageMinHeightDp = 120
332−
333− /** Lines of a code fence rendered before collapsing to a head with a "show more" affordance.
334− * Capped low for mobile: a 200-line block rendered at once can jank a low-end phone, so the
335− * initial render is bounded and a "show more" reveals the rest in place. */
336− const val collapsedCodeLineThreshold = 80
337−
338− /** Lines of a unified diff rendered before collapsing to a head with a "show more" affordance.
339− * Same mobile-performance rationale as [collapsedCodeLineThreshold]. */
340− const val collapsedDiffLineThreshold = 80
341−
342− /** Lines of tool output rendered before collapsing to a head with a "show more" affordance. */
343− const val toolOutputCollapsedLimitChars = 4000
344−
345− /** Lines of tool output rendered before collapsing to a head with a "show more" affordance.
346− * A line-based threshold (rather than the char-based [toolOutputCollapsedLimitChars]) keeps
347− * the collapsed preview a predictable height on mobile — a 4000-char block of short lines
348− * can be 60+ lines and fill the whole screen, defeating the purpose of collapsing. The
349− * char cap still applies as a hard upper bound; this line cap kicks in first for typical
350− * multi-line output. */
351− const val toolOutputCollapsedLimitLines = 30
352−
353− /** Tool input (pretty-printed JSON) shorter than this many lines is shown expanded by
354− * default — for tools like bash/write/edit the command is the most important info and
355− * hiding it behind a tap inverts the priority. Longer inputs stay collapsed to avoid
356− * dominating the bubble. */
357− const val toolInputAutoExpandLineThreshold = 10
358−
359− /** Tool durations below this many ms are hidden from the tool-name row (sub-second runs
360− * are instant and the ms figure is noise). Set to 1000 to hide all sub-second durations,
361− * or 0 to always show. */
362− const val toolDurationHideBelowMs = 1_000L
363−
364− /** Characters of tool output included in a shared/exported transcript before truncation. */
365− const val exportToolOutputLimitChars = 2000
366−
367− /** Maximum zoom factor applied by pinch or double-tap in the fullscreen image viewer. */
368− const val imageViewerMaxZoom = 5f
369−
370− /** Zoom factor a double-tap jumps to when starting from 1× in the fullscreen image viewer. */
371− const val imageViewerDoubleTapZoom = 2.5f
372−
373− /** Duration (ms) of the animated double-tap zoom transition in the fullscreen image viewer. */
374− const val imageViewerZoomAnimMs = 220
375−
376− /** Vertical drag distance (px) in the fullscreen image viewer that triggers swipe-to-dismiss. */
377− const val imageViewerSwipeDismissThreshold = 200f
378−
379− /** Blink period (ms) of the streaming caret at the tail of a live assistant reply. */
380− const val streamingCaretPeriodMs = 500
381−
382− /** Target maximum length (chars) of a single TTS chunk. Android's TextToSpeech enforces a
383− * hard limit (getMaxSpeechInputLength, ~4000 chars) — this is a tighter cap so pause/
384− * resume restarts at a finer granularity. Without it, a pause mid-chunk restarts the
385− * whole chunk from its start; smaller chunks mean less replay on resume. Sentence
386− * boundaries are still preferred, so short sentences pack up to this cap. */
387− const val ttsChunkTargetMaxChars = 200
388−
389− /** Auto-reject a tool-permission prompt after this many ms if the user hasn't responded,
390− * so a forgotten prompt doesn't block the run indefinitely. The foreground service keeps
391− * the process alive, so without a timeout a prompt that the user walked away from holds
392− * the run open forever. The timeout is long (10 minutes) so a deliberate pause to read
393− * the prompt doesn't trip it; a reminder toast-style line appears in the dialog after
394− * [permissionReminderThresholdMs] to surface that the run is waiting. Set to 0 to disable. */
395− const val permissionAutoRejectMs = 10L * 60 * 1000
396−
397− /** Show a "still waiting" reminder in the permission dialog after this many ms. */
398− const val permissionReminderThresholdMs = 60L * 1000
399−
400− /** Duration (ms) the copy button shows its checkmark confirmation before reverting. */
401− const val copyFeedbackMs = 1200
402−
403− /** Gutter width (dp) for each side (old/new) of a unified-diff line-number column. */
404− const val diffGutterWidthDp = 36
405−
406− /** Width (dp) of the +/- prefix column in a unified-diff row. */
407− const val diffPrefixWidthDp = 16
408−
409− /** Maximum width (dp) of a breadcrumb segment in the file browser (non-last segments). */
410− const val breadcrumbSegmentMaxWidthDp = 120
411−
412− /** Maximum width (dp) of the last (current) breadcrumb segment in the file browser. */
413− const val breadcrumbLastSegmentMaxWidthDp = 220
414−
415− /** Vertical scroll threshold beyond which the chat "scroll to top" FAB appears. */
416− const val chatScrollToTopFabThreshold = 200
417−
418− /** Maximum width (dp) for an attachment chip's filename text before it truncates. */
419− const val attachmentChipNameMaxWidthDp = 120
420−
421− /** Maximum height (dp) for the expanded todo-plan checklist in a message bubble. */
422− const val todoPlanMaxHeightDp = 240
423−
424− /** Fallback height (dp) for the connection banner when no text is available (e.g. exit fade). */
425− const val connectionBannerFallbackHeightDp = 44
426−
427− // --- Motion tokens (shared across screens) ---
428−
429− /** Duration (ms) for horizontal slide push/pop nav transitions. M3 spec recommends 200ms
430− * for medium-duration container transitions. */
431− const val motionSlideDurationMs = 200
432− /** Duration (ms) for fade in/out nav and content transitions. */
433− const val motionFadeDurationMs = 180
434−
435− // --- Font scaling ---
436−
437− /** Upper bound on the *combined* app×OS font scale. The chat text-size preference
438− * multiplies on top of the system font scale, so a user at a large system size and
439− * a large app size can reach ~2× and break tight layouts. The provided app scale is
440− * clamped so the product with the OS fontScale never exceeds this. */
441− const val maxCombinedFontScale = 1.8f
442−}
app/src/main/java/soy/iko/opencode/data/network/OpencodeApiClient.ktdeleted−540
@@ -1,540 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.Agent
4−import soy.iko.opencode.data.model.Command
5−import soy.iko.opencode.data.model.CommandRequest
6−import soy.iko.opencode.data.model.CreateSessionRequest
7−import soy.iko.opencode.data.model.FileContent
8−import soy.iko.opencode.data.model.FileNode
9−import soy.iko.opencode.data.model.FileStatusEntry
10−import soy.iko.opencode.data.model.MessageWithParts
11−import soy.iko.opencode.data.model.ModelRef
12−import soy.iko.opencode.data.model.PathInfo
13−import soy.iko.opencode.data.model.FilePromptPart
14−import soy.iko.opencode.data.model.FindMatch
15−import soy.iko.opencode.data.model.PermissionReplyBody
16−import soy.iko.opencode.data.model.PermissionResponse
17−import soy.iko.opencode.data.model.Project
18−import soy.iko.opencode.data.model.PromptPart
19−import soy.iko.opencode.data.model.PromptRequest
20−import soy.iko.opencode.data.model.ProvidersResponse
21−import soy.iko.opencode.data.model.RevertRequest
22−import soy.iko.opencode.data.model.Session
23−import soy.iko.opencode.data.model.ShellRequest
24−import soy.iko.opencode.data.model.SummarizeRequest
25−import soy.iko.opencode.data.model.SymbolResult
26−import soy.iko.opencode.data.model.TextPromptPart
27−import soy.iko.opencode.data.model.UpdateSessionRequest
28−import io.ktor.client.HttpClient
29−import io.ktor.client.call.body
30−import io.ktor.client.plugins.ClientRequestException
31−import io.ktor.client.plugins.ResponseException
32−import io.ktor.client.plugins.ServerResponseException
33−import io.ktor.client.request.delete
34−import io.ktor.client.request.get
35−import io.ktor.client.request.header
36−import io.ktor.client.request.parameter
37−import io.ktor.client.request.patch
38−import io.ktor.client.request.post
39−import io.ktor.client.request.setBody
40−import io.ktor.http.ContentType
41−import io.ktor.http.contentType
42−import kotlinx.coroutines.delay
43−import kotlinx.coroutines.sync.Mutex
44−import kotlinx.coroutines.sync.withLock
45−import kotlinx.serialization.json.buildJsonObject
46−import kotlinx.serialization.json.put
47−import kotlin.random.Random
48−import java.net.URLEncoder
49−
50−/**
51− * Request/response wrapper over the opencode REST endpoints. The long-lived `/event`
52− * SSE stream lives in [EventStreamClient]; everything else is here.
53− */
54−open class OpencodeApiClient private constructor(
55− private val client: HttpClient?,
56− @Suppress("unused") private val testMode: Boolean,
57−) {
58− constructor(client: HttpClient) : this(client, false)
59− protected constructor() : this(null, true)
60−
61− // --- Catalog cache (providers/agents/commands) ---
62− // These change rarely, but the ChatViewModel re-fetches them on every creation.
63− // A short-lived in-memory cache avoids redundant network calls when navigating
64− // between sessions on the same server.
65− private data class CachedEntry<T>(val value: T, val fetchedAt: Long)
66− // Per-catalog mutexes so a slow fetch of one catalog doesn't block the others.
67− // The fetch runs OUTSIDE the lock (holding it across the network call would serialize
68− // all callers and stall invalidation). To keep that correct, each catalog carries a
69− // generation counter, bumped under the mutex by its invalidateXCache(): a fetch captures
70− // the generation before it starts and, when it completes, only writes its result back if
71− // the generation is unchanged — so an invalidation that raced the in-flight fetch is not
72− // defeated by the pre-invalidation result being stored afterwards.
73− private val providersMutex = Mutex()
74− private val agentsMutex = Mutex()
75− private val commandsMutex = Mutex()
76− private var cachedProviders: CachedEntry<ProvidersResponse>? = null
77− private var cachedAgents: CachedEntry<List<Agent>>? = null
78− private var cachedCommands: CachedEntry<List<Command>>? = null
79− // Generation counters (guarded by the matching mutex above) for the invalidation-race guard.
80− private var providersGeneration = 0
81− private var agentsGeneration = 0
82− private var commandsGeneration = 0
83−
84− /** Lightweight connectivity check. Throws on non-2xx / network failure. */
85− open suspend fun ping() {
86− withRetry { client!!.get("global/health").body<String>() }
87− }
88−
89− open suspend fun listSessions(): List<Session> = withRetry {
90− client!!.get("session").body()
91− }
92−
93− /**
94− * Create a session, optionally in a specific worktree [directory]. The directory is a
95− * query parameter (not a body field): the server records it on the session and resolves
96− * it by session id thereafter, so follow-up calls (messages, commands, abort, …) don't
97− * — and shouldn't — re-send it. A null/blank [directory] lets the server fall back to
98− * its own launch cwd, preserving the pre-directory behavior.
99− */
100− open suspend fun createSession(title: String? = null, directory: String? = null): Session {
101− // Generate the idempotency key before entering withRetry so every retry attempt
102− // shares it. Without this, a POST that reached the server but whose response was
103− // lost (reset/timeout) would be retried and create a second orphan session.
104− val idempotencyKey = java.util.UUID.randomUUID().toString()
105− val dir = directory?.takeIf { it.isNotBlank() }
106− return withRetry {
107− client!!.post("session") {
108− contentType(ContentType.Application.Json)
109− header("Idempotency-Key", idempotencyKey)
110− if (dir != null) parameter("directory", dir)
111− setBody(CreateSessionRequest(title = title))
112− }.body()
113− }
114− }
115−
116− /** List the projects (worktree roots) the server knows about, for the directory picker. */
117− open suspend fun listProjects(): List<Project> = withRetry {
118− client!!.get("project").body()
119− }
120−
121− /** The server's current path info; its [PathInfo.directory] is the default (cwd) a
122− * session with no directory override runs in. */
123− open suspend fun currentPath(): PathInfo = withRetry {
124− client!!.get("path").body()
125− }
126−
127− open suspend fun updateSession(id: String, title: String): Session = withRetry {
128− client!!.patch("session/${encode(id)}") {
129− contentType(ContentType.Application.Json)
130− setBody(UpdateSessionRequest(title = title))
131− }.body()
132− }
133−
134− open suspend fun deleteSession(id: String) {
135− try {
136− withRetry { client!!.delete("session/${encode(id)}").body<String>() }
137− } catch (t: ClientRequestException) {
138− // A DELETE that succeeded but whose response was lost gets retried; the retry
139− // hits an already-gone session and returns 404. Deleting a non-existent session
140− // is effectively success, so swallow 404 rather than surfacing a spurious failure.
141− if (t.response.status.value != 404) throw t
142− }
143− }
144−
145− open suspend fun listMessages(sessionId: String): List<MessageWithParts> = withRetry {
146− client!!.get("session/${encode(sessionId)}/message").body()
147− }
148−
149− open suspend fun sendPrompt(
150− sessionId: String,
151− text: String,
152− attachments: List<FilePromptPart> = emptyList(),
153− model: ModelRef? = null,
154− agent: String? = null,
155− // A caller-stable idempotency key. Callers that may re-invoke sendPrompt across
156− // *separate* calls for the same logical message (the offline outbox, which re-sends
157− // a message that stayed queued after an earlier flush failed) must pass a stable key
158− // derived from the persistent message id — otherwise each attempt mints a fresh key
159− // and a POST that reached the server but whose response was lost is re-created as a
160− // duplicate run. When null, a fresh key is generated (correct for one-shot sends).
161− idempotencyKey: String? = null,
162− ): MessageWithParts {
163− // Resolve the key *before* entering withRetry so all retry attempts share it. If the
164− // key were generated inside withRetry, each attempt would get a fresh UUID and the
165− // server couldn't deduplicate a request that reached it but whose response was lost.
166− val resolvedKey = idempotencyKey ?: java.util.UUID.randomUUID().toString()
167− // A text part is only included when there's actual text, so an image-only prompt
168− // (attachments, empty text) doesn't send an empty text part. Attachments follow
169− // the text so the model reads the instruction first.
170− val parts = buildList<PromptPart> {
171− if (text.isNotEmpty()) add(TextPromptPart(text))
172− addAll(attachments)
173− }
174− return withRetry {
175− client!!.post("session/${encode(sessionId)}/message") {
176− contentType(ContentType.Application.Json)
177− header("Idempotency-Key", resolvedKey)
178− setBody(
179− PromptRequest(
180− parts = parts,
181− model = model,
182− agent = agent,
183− ),
184− )
185− }.body()
186− }
187− }
188−
189− open suspend fun abort(sessionId: String) {
190− withRetry { client!!.post("session/${encode(sessionId)}/abort").body<String>() }
191− }
192−
193− /** Invoke a slash-command by name via `POST /session/:id/command`. */
194− open suspend fun runCommand(
195− sessionId: String,
196− command: String,
197− arguments: String = "",
198− agent: String? = null,
199− ): MessageWithParts {
200− // Generate the idempotency key before entering withRetry so all retry
201− // attempts share the same key, preventing duplicate command execution if
202− // the server processed the request but the response was lost.
203− val idempotencyKey = java.util.UUID.randomUUID().toString()
204− return withRetry {
205− client!!.post("session/${encode(sessionId)}/command") {
206− contentType(ContentType.Application.Json)
207− header("Idempotency-Key", idempotencyKey)
208− setBody(CommandRequest(command = command, arguments = arguments, agent = agent))
209− }.body()
210− }
211− }
212−
213− /** Revert the session to just before [messageId] (optionally part [partId]); the
214− * server hides everything after the checkpoint. Returns the updated session. Naturally
215− * idempotent (reverting to the same point twice yields the same state). */
216− open suspend fun revert(sessionId: String, messageId: String, partId: String? = null): Session = withRetry {
217− client!!.post("session/${encode(sessionId)}/revert") {
218− contentType(ContentType.Application.Json)
219− setBody(RevertRequest(messageID = messageId, partID = partId))
220− }.body()
221− }
222−
223− /** Undo the active revert checkpoint, restoring the hidden messages. */
224− open suspend fun unrevert(sessionId: String): Session = withRetry {
225− client!!.post("session/${encode(sessionId)}/unrevert").body()
226− }
227−
228− /** Create a public share link for the session. Returns the session with [Session.share] set.
229− * Mint the Idempotency-Key *before* withRetry so a retried POST (first request reached the
230− * server but its response was lost) doesn't create a second, orphaned, still-valid share. */
231− open suspend fun shareSession(sessionId: String): Session {
232− val idempotencyKey = java.util.UUID.randomUUID().toString()
233− return withRetry {
234− client!!.post("session/${encode(sessionId)}/share") {
235− header("Idempotency-Key", idempotencyKey)
236− }.body()
237− }
238− }
239−
240− /** Revoke the session's public share link. Returns the session with share cleared.
241− * Like [deleteSession], a retried DELETE (first reached the server but the response was
242− * lost) hits an already-unshared session and gets 404 — revoking a non-shared session is
243− * effectively success, so swallow 404 rather than surfacing a spurious failure. */
244− open suspend fun unshareSession(sessionId: String): Session {
245− return try {
246− withRetry { client!!.delete("session/${encode(sessionId)}/share").body() }
247− } catch (t: ClientRequestException) {
248− if (t.response.status.value != 404) throw t
249− withRetry { client!!.get("session/${encode(sessionId)}").body() }
250− }
251− }
252−
253− /** Ask the agent to summarize/compact the conversation to reclaim context. The compacted
254− * summary streams back via SSE like any run; this just triggers it. */
255− open suspend fun summarize(sessionId: String, model: ModelRef) {
256− val idempotencyKey = java.util.UUID.randomUUID().toString()
257− withRetry {
258− client!!.post("session/${encode(sessionId)}/summarize") {
259− contentType(ContentType.Application.Json)
260− header("Idempotency-Key", idempotencyKey)
261− setBody(SummarizeRequest(providerID = model.providerID, modelID = model.modelID))
262− }.body<String>()
263− }
264− }
265−
266− /** Analyze the project and (re)generate its AGENTS.md. The body is omitted so the server
267− * assigns the message id and uses its default model; the run streams back via SSE. */
268− open suspend fun initSession(sessionId: String) {
269− val idempotencyKey = java.util.UUID.randomUUID().toString()
270− withRetry {
271− client!!.post("session/${encode(sessionId)}/init") {
272− header("Idempotency-Key", idempotencyKey)
273− }.body<String>()
274− }
275− }
276−
277− /** Run a one-off shell [command] in the session's worktree. Output streams back via SSE.
278− * [agent] scopes the run (the server requires it). */
279− open suspend fun shell(sessionId: String, command: String, agent: String, model: ModelRef? = null) {
280− val idempotencyKey = java.util.UUID.randomUUID().toString()
281− withRetry {
282− client!!.post("session/${encode(sessionId)}/shell") {
283− contentType(ContentType.Application.Json)
284− header("Idempotency-Key", idempotencyKey)
285− setBody(ShellRequest(agent = agent, command = command, model = model))
286− }.body<String>()
287− }
288− }
289−
290− open suspend fun providers(): ProvidersResponse {
291− val generation: Int
292− providersMutex.withLock {
293− val cached = cachedProviders
294− if (cached != null && System.currentTimeMillis() - cached.fetchedAt < NetworkConfig.catalogCacheTtlMs) {
295− return cached.value
296− }
297− generation = providersGeneration
298− }
299− // Fetch outside the lock so a slow/retrying request (and its backoff) can't stall other
300− // callers or cache invalidation. Concurrent cold callers may double-fetch — acceptable
301− // for a rarely-fetched catalog — and the last store wins.
302− val value = withRetry { client!!.get("config/providers").body<ProvidersResponse>() }
303− providersMutex.withLock {
304− // FIX 15: skip the store if an invalidateProvidersCache() raced this fetch — the
305− // result predates the invalidation and would otherwise resurrect stale data.
306− if (providersGeneration == generation) cachedProviders = CachedEntry(value, System.currentTimeMillis())
307− }
308− return value
309− }
310−
311− /** The server's resolved configuration as a raw JSON object. Parsed loosely by callers
312− * (e.g. the MCP viewer) so a schema addition on the server never breaks decoding. */
313− open suspend fun config(): kotlinx.serialization.json.JsonObject = withRetry {
314− client!!.get("config").body()
315− }
316−
317− /** Live MCP server status (`GET /mcp`): a map of server name to its status (connected,
318− * available tools, any error). Decoded as a raw JSON object so a schema change on the
319− * server never breaks the viewer. */
320− open suspend fun mcpStatus(): kotlinx.serialization.json.JsonObject = withRetry {
321− client!!.get("mcp").body()
322− }
323−
324− /** Dynamically register an MCP server (`POST /mcp`). [config] is the server's config object
325− * (type/command-or-url/env…), sent as `{ "name": [name], "config": [config] }`. Mint the
326− * Idempotency-Key *before* withRetry so a retried POST (first reached the server but the
327− * response was lost) doesn't register a duplicate. */
328− open suspend fun addMcp(name: String, config: kotlinx.serialization.json.JsonObject): kotlinx.serialization.json.JsonObject {
329− val idempotencyKey = java.util.UUID.randomUUID().toString()
330− return withRetry {
331− client!!.post("mcp") {
332− contentType(ContentType.Application.Json)
333− header("Idempotency-Key", idempotencyKey)
334− setBody(
335− buildJsonObject {
336− put("name", name)
337− put("config", config)
338− },
339− )
340− }.body()
341− }
342− }
343−
344− open suspend fun agents(): List<Agent> {
345− val generation: Int
346− agentsMutex.withLock {
347− val cached = cachedAgents
348− if (cached != null && System.currentTimeMillis() - cached.fetchedAt < NetworkConfig.catalogCacheTtlMs) {
349− return cached.value
350− }
351− generation = agentsGeneration
352− }
353− // Fetch outside the lock (see providers()): a slow/retrying request can't stall other
354− // callers or cache invalidation; a rare concurrent double-fetch is acceptable here.
355− val value = withRetry { client!!.get("agent").body<List<Agent>>() }
356− agentsMutex.withLock {
357− // FIX 15: skip the store if an invalidateAgentsCache() raced this fetch (see providers()).
358− if (agentsGeneration == generation) cachedAgents = CachedEntry(value, System.currentTimeMillis())
359− }
360− return value
361− }
362−
363− open suspend fun commands(): List<Command> {
364− val generation: Int
365− commandsMutex.withLock {
366− val cached = cachedCommands
367− if (cached != null && System.currentTimeMillis() - cached.fetchedAt < NetworkConfig.catalogCacheTtlMs) {
368− return cached.value
369− }
370− generation = commandsGeneration
371− }
372− // Fetch outside the lock (see providers()): a slow/retrying request can't stall other
373− // callers or cache invalidation; a rare concurrent double-fetch is acceptable here.
374− val value = withRetry { client!!.get("command").body<List<Command>>() }
375− commandsMutex.withLock {
376− // FIX 15: skip the store if an invalidateCommandsCache() raced this fetch (see providers()).
377− if (commandsGeneration == generation) cachedCommands = CachedEntry(value, System.currentTimeMillis())
378− }
379− return value
380− }
381−
382− /** Invalidate the catalog cache (e.g. on server switch). */
383− open suspend fun invalidateCache() {
384− // FIX 15: bump each generation so an in-flight fetch drops its now-stale result.
385− providersMutex.withLock { cachedProviders = null; providersGeneration++ }
386− agentsMutex.withLock { cachedAgents = null; agentsGeneration++ }
387− commandsMutex.withLock { cachedCommands = null; commandsGeneration++ }
388− }
389−
390− open suspend fun invalidateProvidersCache() {
391− providersMutex.withLock { cachedProviders = null; providersGeneration++ }
392− }
393−
394− open suspend fun invalidateAgentsCache() {
395− agentsMutex.withLock { cachedAgents = null; agentsGeneration++ }
396− }
397−
398− open suspend fun invalidateCommandsCache() {
399− commandsMutex.withLock { cachedCommands = null; commandsGeneration++ }
400− }
401−
402− /** Respond to a permission request so a paused tool run can proceed. */
403− open suspend fun respondPermission(
404− sessionId: String,
405− permissionId: String,
406− response: PermissionResponse,
407− ): String = try {
408− withRetry {
409− client!!.post("session/${encode(sessionId)}/permissions/${encode(permissionId)}") {
410− contentType(ContentType.Application.Json)
411− setBody(PermissionReplyBody(response.wire))
412− }.body<String>()
413− }
414− } catch (t: ClientRequestException) {
415− // A response that reached the server but whose reply was lost gets retried; the
416− // retry finds the permission already resolved (404 gone / 409 conflict). Both mean
417− // the answer landed, so treat them as success instead of a spurious failure.
418− val code = t.response.status.value
419− if (code != 404 && code != 409) throw t
420− ""
421− }
422−
423− // --- Files ---
424−
425− open suspend fun findFiles(query: String): List<String> = withRetry {
426− client!!.get("find/file") { parameter("query", query) }.body()
427− }
428−
429− /** Ripgrep content search across the project (`GET /find?pattern=`). */
430− open suspend fun findText(pattern: String): List<FindMatch> = withRetry {
431− client!!.get("find") { parameter("pattern", pattern) }.body()
432− }
433−
434− /** LSP workspace symbol search (`GET /find/symbol?query=`). */
435− open suspend fun findSymbol(query: String): List<SymbolResult> = withRetry {
436− client!!.get("find/symbol") { parameter("query", query) }.body()
437− }
438−
439− open suspend fun listDirectory(path: String): List<FileNode> = withRetry {
440− client!!.get("file") { parameter("path", path) }.body()
441− }
442−
443− open suspend fun readFile(path: String): FileContent = withRetry {
444− client!!.get("file/content") { parameter("path", path) }.body()
445− }
446−
447− open suspend fun fileStatus(): List<FileStatusEntry> = withRetry {
448− client!!.get("file/status").body()
449− }
450−}
451−
452−private suspend fun <T> withRetry(
453− maxAttempts: Int = NetworkConfig.retryMaxAttempts,
454− initialDelayMs: Long = NetworkConfig.retryInitialDelayMs,
455− block: suspend () -> T,
456−): T = withRetryInternal(maxAttempts, initialDelayMs, jitterFactor = NetworkConfig.retryJitterFactor, block)
457−
458−/**
459− * Retry a suspending block up to [maxAttempts] times with exponential backoff.
460− * Cancellation exceptions are re-thrown immediately. Client errors (4xx) are
461− * non-retryable — a 401 or 404 won't succeed on retry, so they surface immediately
462− * instead of wasting up to 3.5 s of backoff. Network failures, timeouts, and 5xx
463− * server errors are retried. Exposed as `internal` so the retry/skip rules are
464− * unit-testable without an HTTP server.
465− */
466−internal suspend fun <T> withRetryInternal(
467− maxAttempts: Int = NetworkConfig.retryMaxAttempts,
468− initialDelayMs: Long = NetworkConfig.retryInitialDelayMs,
469− jitterFactor: Double = NetworkConfig.retryJitterFactor,
470− block: suspend () -> T,
471−): T {
472− var lastError: Throwable? = null
473− for (attempt in 1..maxAttempts) {
474− try {
475− return block()
476− } catch (c: kotlinx.coroutines.CancellationException) {
477− throw c
478− } catch (t: ClientRequestException) {
479− // 408 (Request Timeout) and 429 (Too Many Requests) are transient — retry with
480− // backoff. All other 4xx are non-retryable (a 401/404 won't succeed on retry).
481− val status = t.response.status.value
482− if (status != 408 && status != 429) throw t
483− lastError = t
484− if (attempt < maxAttempts) {
485− delay(jitteredBackoff(attempt, initialDelayMs, jitterFactor))
486− }
487− } catch (t: ServerResponseException) {
488− // 5xx server errors are retryable with backoff.
489− lastError = t
490− if (attempt < maxAttempts) {
491− delay(jitteredBackoff(attempt, initialDelayMs, jitterFactor))
492− }
493− } catch (t: ResponseException) {
494− // 3xx (redirect limit exceeded) is non-retryable.
495− throw t
496− } catch (t: io.ktor.serialization.ContentConvertException) {
497− // A malformed/unexpected response body (deserialization failure via content
498− // negotiation) is deterministic — it fails identically on every attempt — so
499− // retrying only burns the whole backoff budget re-parsing the same bytes. Fail
500− // fast instead.
501− throw t
502− } catch (t: IllegalArgumentException) {
503− // Also deterministic: a bad argument, or a raw kotlinx SerializationException
504− // (which extends IllegalArgumentException) thrown outside content negotiation.
505− throw t
506− } catch (t: Exception) {
507− lastError = t
508− if (attempt < maxAttempts) {
509− delay(jitteredBackoff(attempt, initialDelayMs, jitterFactor))
510− }
511− }
512− }
513− throw lastError ?: IllegalStateException("withRetry failed without error")
514−}
515−
516−/** Computes an exponential backoff delay with symmetric jitter. Exposed as `internal`
517− * so the backoff formula is unit-testable without an HTTP server. */
518−internal fun jitteredBackoff(
519− attempt: Int,
520− initialDelayMs: Long,
521− jitterFactor: Double,
522−): Long {
523− // Guard against Int overflow from the shift and Long overflow from
524− // the multiplication at high attempt counts.
525− val shift = (attempt - 1).coerceAtMost(30)
526− val baseDelay = (initialDelayMs * (1L shl shift)).coerceAtMost(NetworkConfig.retryMaxDelayMs)
527− // Symmetric jitter: vary by ±jitterFactor so the delay is sometimes
528− // shorter, sometimes longer — spreads concurrent client retries and
529− // prevents thundering-herd reconnection storms.
530− val jitter = ((baseDelay * jitterFactor) * (Random.nextDouble() * 2 - 1)).toLong()
531− return (baseDelay + jitter).coerceAtLeast(0)
532−}
533−
534−/** URL-encode a path segment, replacing + with %20 (URLEncoder uses query-param encoding).
535− * URLEncoder leaves '.' unencoded, so a "." or ".." segment would otherwise survive as a real
536− * path-traversal component; percent-encode a segment that is nothing but dots. */
537−private fun encode(segment: String): String {
538− val encoded = URLEncoder.encode(segment, "UTF-8").replace("+", "%20")
539− return if (encoded.isNotEmpty() && encoded.all { it == '.' }) encoded.replace(".", "%2E") else encoded
540−}
app/src/main/java/soy/iko/opencode/data/network/OpencodeJson.ktdeleted−37
@@ -1,37 +0,0 @@
1−package soy.iko.opencode.data.network
2−
3−import soy.iko.opencode.data.model.BusEvent
4−import soy.iko.opencode.data.model.MessageInfo
5−import soy.iko.opencode.data.model.Part
6−import soy.iko.opencode.data.model.ToolState
7−import soy.iko.opencode.data.model.UnknownEvent
8−import soy.iko.opencode.data.model.UnknownMessage
9−import soy.iko.opencode.data.model.UnknownPart
10−import soy.iko.opencode.data.model.ToolUnknown
11−import kotlinx.serialization.ExperimentalSerializationApi
12−import kotlinx.serialization.json.Json
13−import kotlinx.serialization.modules.SerializersModule
14−
15−/**
16− * Single shared Json for the whole app.
17− *
18− * The polymorphic default deserializers are the resilience layer: when the server
19− * sends a `type` / `role` / `status` we don't model, decoding falls back to the
20− * Unknown variant instead of throwing — so a new opencode release can't break the
21− * event stream or message decoding.
22− */
23−@OptIn(ExperimentalSerializationApi::class)
24−val OpencodeJson: Json = Json {
25− ignoreUnknownKeys = true
26− isLenient = true
27− coerceInputValues = true
28− encodeDefaults = true
29− explicitNulls = false
30− classDiscriminator = "type"
31− serializersModule = SerializersModule {
32− polymorphicDefaultDeserializer(Part::class) { UnknownPart.serializer() }
33− polymorphicDefaultDeserializer(BusEvent::class) { UnknownEvent.serializer() }
34− polymorphicDefaultDeserializer(MessageInfo::class) { UnknownMessage.serializer() }
35− polymorphicDefaultDeserializer(ToolState::class) { ToolUnknown.serializer() }
36− }
37−}
app/src/main/java/soy/iko/opencode/data/repo/AttachmentDraftStore.ktdeleted−114
@@ -1,114 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.sync.Mutex
7−import kotlinx.coroutines.sync.withLock
8−import kotlinx.coroutines.withContext
9−import kotlinx.serialization.Serializable
10−import kotlinx.serialization.decodeFromString
11−import kotlinx.serialization.encodeToString
12−import kotlinx.serialization.json.Json
13−import soy.iko.opencode.util.runCatchingCancellable
14−import java.io.File
15−
16−/**
17− * One staged (not-yet-sent) attachment, in the minimal form needed to re-send and preview
18− * it after a process restart. Only the self-contained wire payload is kept — the base64
19− * `data:` [url] — because the original content Uri's read permission does NOT survive a
20− * process restart, whereas the data URL is self-sufficient (and Coil re-renders it as the
21− * thumbnail for images).
22− */
23−@Serializable
24−data class PersistedAttachment(
25− val id: String,
26− val name: String,
27− val mime: String,
28− val url: String,
29− val filename: String? = null,
30−)
31−
32−/**
33− * Persists attachments staged for each session so an interrupted compose survives process
34− * death, mirroring how [DraftStore] persists the text draft.
35− *
36− * Backed by one small JSON file per session under filesDir (not cacheDir, which the OS may
37− * evict) rather than SharedPreferences: a base64 payload can be several megabytes and
38− * SharedPreferences loads its whole file into memory on first access.
39− */
40−open class AttachmentDraftStore private constructor(
41− private val appContext: Context?,
42− @Suppress("unused") private val testMode: Boolean,
43−) {
44− constructor(context: Context) : this(context.applicationContext, false)
45− protected constructor() : this(null, true)
46−
47− private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
48−
49− /** Session ids are validated tokens upstream, but sanitize anyway so a stray id can't
50− * escape the directory. */
51− private val idRegex = Regex("[^A-Za-z0-9_-]")
52−
53− private val dir: File? by lazy {
54− appContext?.let { File(it.filesDir, "attachment_drafts").apply { mkdirs() } }
55− }
56−
57− private fun fileFor(sessionId: String): File? =
58− dir?.let { File(it, idRegex.replace(sessionId, "_") + ".json") }
59−
60− /** Per-session write lock so rapid add/remove/clear mutations (each launched as an
61− * independent coroutine by the ViewModel) serialize their writes to the same file
62− * instead of racing — otherwise an older snapshot could land last and overwrite the
63− * newer one on disk, or two writes could tear the file. */
64− private val locks = java.util.concurrent.ConcurrentHashMap<String, Mutex>()
65− private fun lockFor(sessionId: String): Mutex = locks.getOrPut(sessionId) { Mutex() }
66−
67− /** Load the staged attachments for [sessionId], or empty if none / unreadable. */
68− open suspend fun load(sessionId: String): List<PersistedAttachment> = lockFor(sessionId).withLock {
69− withContext(Dispatchers.IO) {
70− val file = fileFor(sessionId)?.takeIf { it.exists() } ?: return@withContext emptyList()
71− runCatchingCancellable { json.decodeFromString<List<PersistedAttachment>>(file.readText()) }
72− .getOrDefault(emptyList())
73− }
74− }
75−
76− /** Persist [attachments] for [sessionId] (an empty list deletes the file). */
77− open suspend fun save(sessionId: String, attachments: List<PersistedAttachment>): Unit = lockFor(sessionId).withLock {
78− withContext(Dispatchers.IO) {
79− val file = fileFor(sessionId) ?: return@withContext
80− runCatchingCancellable {
81− if (attachments.isEmpty()) file.delete()
82− else {
83− // FIX: write atomically (temp file + rename) like RecentSessionsStore so a
84− // process kill mid-write can't leave a truncated file that fails to decode
85− // and silently drops the staged attachments on reload.
86− val encoded = json.encodeToString(attachments)
87− val tmp = File(file.parentFile, file.name + ".tmp")
88− tmp.writeText(encoded)
89− if (!tmp.renameTo(file)) {
90− file.writeText(encoded)
91− tmp.delete()
92− }
93− }
94− }.onFailure { Log.w("AttachmentDraftStore", "Failed to persist attachments for $sessionId", it) }
95− Unit
96− }
97− }
98−
99− /** Remove staged attachments for a session (call on session deletion). */
100− open suspend fun remove(sessionId: String) {
101− // Keep the per-session Mutex in [locks] rather than evicting it: remove() is not always
102− // terminal — a concurrent teardown save() for the same session must serialize against this
103− // delete under the *same* Mutex instance. Evicting here would let that save() acquire a
104− // fresh Mutex, so the two operations no longer serialize (resurrecting an orphan file, or
105− // theoretically tearing a write). The bounded per-session map growth matches the other
106− // lock-keyed stores.
107− lockFor(sessionId).withLock {
108− withContext(Dispatchers.IO) {
109− runCatchingCancellable { fileFor(sessionId)?.delete() }
110− Unit
111− }
112− }
113− }
114−}
app/src/main/java/soy/iko/opencode/data/repo/BackupManager.ktdeleted−180
@@ -1,180 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import kotlinx.coroutines.flow.first
4−import kotlinx.serialization.Serializable
5−import kotlinx.serialization.decodeFromString
6−import kotlinx.serialization.encodeToString
7−import kotlinx.serialization.json.Json
8−import soy.iko.opencode.data.model.ServerProfile
9−
10−/** A server entry in a backup. [password] is present only when the user opted to include it. */
11−@Serializable
12−data class BackupServer(
13− val id: String,
14− val label: String,
15− val baseUrl: String,
16− val username: String? = null,
17− val password: String? = null,
18− val requireHttps: Boolean = false,
19− val certPin: String? = null,
20−)
21−
22−/** App preferences in a backup. */
23−@Serializable
24−data class BackupSettings(
25− // Every field is defaulted (to SettingsStore's own defaults) so a backup written by an older
26− // app version — one whose settings block predates a field added later — still decodes. Without
27− // defaults a missing field throws MissingFieldException in import() BEFORE the server-restore
28− // loop, aborting the ENTIRE restore (servers/pins/archives included) despite the best-effort
29− // contract. ignoreUnknownKeys only tolerates EXTRA keys, not missing required ones.
30− val themeMode: String = ThemeMode.SYSTEM.name,
31− val dynamicColor: Boolean = false,
32− val sendOnEnter: Boolean = true,
33− val appLock: Boolean = false,
34− val appLockReLockSeconds: Int = SettingsStore.DEFAULT_APP_LOCK_RELOCK_SECONDS,
35− val chatTextScale: Float = SettingsStore.DEFAULT_CHAT_TEXT_SCALE,
36− val codeWrap: Boolean = false,
37− val sessionSortMode: String = "RECENT",
38− val sessionSortDescending: Boolean = true,
39− val sessionShowArchived: Boolean = false,
40− val preferredModelId: String = "",
41− val preferredAgentName: String = "",
42− val compactMessageSpacing: Boolean = false,
43− val hapticsEnabled: Boolean = true,
44− val reducedMotion: Boolean = false,
45− val languageOverride: String = "",
46− val notifRunComplete: Boolean = true,
47− val notifPermission: Boolean = true,
48− val notifError: Boolean = true,
49− val swipeLeftAction: String = SwipeAction.DELETE.name,
50− val swipeRightAction: String = SwipeAction.ARCHIVE.name,
51−)
52−
53−/** The full backup document. [version] guards against future format changes. */
54−@Serializable
55−data class BackupData(
56− val version: Int = 1,
57− val servers: List<BackupServer> = emptyList(),
58− val settings: BackupSettings? = null,
59− val pinned: List<String> = emptyList(),
60− val archived: List<String> = emptyList(),
61−)
62−
63−/**
64− * Exports/imports the app's servers, settings, and per-session flags as a single JSON
65− * document (via the Storage Access Framework in the UI). Passwords are only written when the
66− * user explicitly opts in, since the exported file is plaintext and leaves the app's encrypted
67− * store.
68− */
69−class BackupManager(
70− private val profileStore: ProfileStore,
71− private val settingsStore: SettingsStore,
72− private val sessionPrefsStore: SessionPrefsStore,
73−) {
74− private val json = Json { prettyPrint = true; ignoreUnknownKeys = true; encodeDefaults = true }
75−
76− /** Build the backup JSON. Reads the current profiles/settings/flags. */
77− suspend fun export(includePasswords: Boolean): String {
78− val servers = profileStore.profiles.first().map {
79− BackupServer(
80− id = it.id,
81− label = it.label,
82− baseUrl = it.baseUrl,
83− username = it.username,
84− password = if (includePasswords) it.password else null,
85− requireHttps = it.requireHttps,
86− certPin = it.certPin,
87− )
88− }
89− val settings = BackupSettings(
90− themeMode = settingsStore.themeMode.first().name,
91− dynamicColor = settingsStore.dynamicColor.first(),
92− sendOnEnter = settingsStore.sendOnEnter.first(),
93− appLock = settingsStore.appLock.first(),
94− appLockReLockSeconds = settingsStore.appLockReLockSeconds.first(),
95− chatTextScale = settingsStore.chatTextScale.first(),
96− codeWrap = settingsStore.codeWrap.first(),
97− sessionSortMode = settingsStore.sessionSortMode.first(),
98− sessionSortDescending = settingsStore.sessionSortDescending.first(),
99− sessionShowArchived = settingsStore.sessionShowArchived.first(),
100− preferredModelId = settingsStore.preferredModelId.first(),
101− preferredAgentName = settingsStore.preferredAgentName.first(),
102− compactMessageSpacing = settingsStore.compactMessageSpacing.first(),
103− hapticsEnabled = settingsStore.hapticsEnabled.first(),
104− reducedMotion = settingsStore.reducedMotion.first(),
105− languageOverride = settingsStore.languageOverride.first(),
106− notifRunComplete = settingsStore.notifRunComplete.first(),
107− notifPermission = settingsStore.notifPermission.first(),
108− notifError = settingsStore.notifError.first(),
109− swipeLeftAction = settingsStore.swipeLeftAction.first(),
110− swipeRightAction = settingsStore.swipeRightAction.first(),
111− )
112− val data = BackupData(
113− servers = servers,
114− settings = settings,
115− pinned = sessionPrefsStore.pinned.first().toList(),
116− archived = sessionPrefsStore.archived.first().toList(),
117− )
118− return json.encodeToString(data)
119− }
120−
121− /** Apply a backup document. Throws on malformed JSON so the caller can report it. Servers
122− * are upserted (existing ids overwritten); settings and flags are restored best-effort. */
123− suspend fun import(text: String) {
124− val data = json.decodeFromString<BackupData>(text)
125− for (s in data.servers) {
126− val username = s.username?.takeIf { it.isNotBlank() }
127− val incomingPassword = s.password?.takeIf { it.isNotEmpty() }
128− // A backup exported *without* passwords carries null. This is an upsert, so don't let
129− // that null wipe a password already stored for this server id — preserve the existing
130− // secret when the backup didn't include one (only the backup explicitly carrying a
131− // password should overwrite it). Re-importing a password-less backup would otherwise
132− // silently break auth for every matching server.
133− val password = incomingPassword ?: username?.let {
134− profileStore.resolve(
135− ServerProfile(id = s.id, label = s.label, baseUrl = s.baseUrl, username = it),
136− ).password
137− }
138− profileStore.save(
139− ServerProfile(
140− id = s.id,
141− label = s.label,
142− baseUrl = s.baseUrl,
143− username = username,
144− password = password,
145− lastUsed = 0,
146− requireHttps = s.requireHttps,
147− certPin = s.certPin?.takeIf { it.isNotBlank() },
148− ),
149− )
150− }
151− data.settings?.let { settings ->
152− // Parse the enum defensively (a bad name from an edited backup shouldn't abort the
153− // import) WITHOUT wrapping the suspend setThemeMode call — wrapping it would swallow
154− // a CancellationException and break structured concurrency.
155− ThemeMode.entries.find { it.name == settings.themeMode }?.let { settingsStore.setThemeMode(it) }
156− settingsStore.setDynamicColor(settings.dynamicColor)
157− settingsStore.setSendOnEnter(settings.sendOnEnter)
158− settingsStore.setAppLock(settings.appLock)
159− settingsStore.setAppLockReLockSeconds(settings.appLockReLockSeconds)
160− settingsStore.setChatTextScale(settings.chatTextScale)
161− settingsStore.setCodeWrap(settings.codeWrap)
162− settingsStore.setSessionSortMode(settings.sessionSortMode)
163− settingsStore.setSessionSortDescending(settings.sessionSortDescending)
164− settingsStore.setSessionShowArchived(settings.sessionShowArchived)
165− settingsStore.setPreferredModelId(settings.preferredModelId)
166− settingsStore.setPreferredAgentName(settings.preferredAgentName)
167− settingsStore.setCompactMessageSpacing(settings.compactMessageSpacing)
168− settingsStore.setHapticsEnabled(settings.hapticsEnabled)
169− settingsStore.setReducedMotion(settings.reducedMotion)
170− settingsStore.setLanguageOverride(settings.languageOverride)
171− settingsStore.setNotifRunComplete(settings.notifRunComplete)
172− settingsStore.setNotifPermission(settings.notifPermission)
173− settingsStore.setNotifError(settings.notifError)
174− SwipeAction.entries.find { it.name == settings.swipeLeftAction }?.let { settingsStore.setSwipeLeftAction(it) }
175− SwipeAction.entries.find { it.name == settings.swipeRightAction }?.let { settingsStore.setSwipeRightAction(it) }
176− }
177− data.pinned.forEach { sessionPrefsStore.setPinned(it, true) }
178− data.archived.forEach { sessionPrefsStore.setArchived(it, true) }
179− }
180−}
app/src/main/java/soy/iko/opencode/data/repo/CrashLogger.ktdeleted−274
@@ -1,274 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.content.pm.PackageManager
5−import android.os.Build
6−import android.util.Log
7−import androidx.core.content.pm.PackageInfoCompat
8−import kotlinx.coroutines.CoroutineScope
9−import kotlinx.coroutines.Dispatchers
10−import kotlinx.coroutines.Job
11−import kotlinx.coroutines.SupervisorJob
12−import kotlinx.coroutines.cancel
13−import kotlinx.coroutines.delay
14−import kotlinx.coroutines.flow.MutableStateFlow
15−import kotlinx.coroutines.flow.StateFlow
16−import kotlinx.coroutines.flow.asStateFlow
17−import kotlinx.coroutines.launch
18−import java.io.File
19−import java.io.PrintWriter
20−import java.io.StringWriter
21−import java.text.SimpleDateFormat
22−import java.util.Date
23−import java.util.Locale
24−import soy.iko.opencode.util.runCatchingCancellable
25−
26−/**
27− * A self-contained crash reporter with no network or third-party backend. An uncaught
28− * exception is written to app-private storage ([Context.filesDir]/crashes) as a plain
29− * text report (timestamp, device/app metadata, and the full stack trace), then the
30− * previous handler is re-invoked so the process still dies normally.
31− *
32− * Reports are surfaced in the in-app Diagnostics screen, where they can be viewed,
33− * shared, or deleted. This closes the "no idea what's crashing in the field" gap
34− * without pulling in a hosted analytics SDK.
35− */
36−class CrashLogger private constructor(private val appContext: Context) {
37−
38− data class CrashReport(
39− val fileName: String,
40− val timestamp: Long,
41− val preview: String,
42− )
43−
44− private val crashDir = File(appContext.filesDir, "crashes").apply { mkdirs() }
45− private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
46− private val crashPrefs = appContext.getSharedPreferences("crash_logger", android.content.Context.MODE_PRIVATE)
47−
48− private val _reports = MutableStateFlow<List<CrashReport>>(emptyList())
49− val reports: StateFlow<List<CrashReport>> = _reports.asStateFlow()
50−
51− fun install() {
52− val previous = Thread.getDefaultUncaughtExceptionHandler()
53− Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
54− runCatching { writeReport(thread, throwable) }
55− .onFailure { Log.e("CrashLogger", "Failed to write crash report", it) }
56− previous?.uncaughtException(thread, throwable)
57− }
58− // Load crash reports off the main thread so startup isn't blocked by file I/O
59− // (listFiles + reading the first line of each report). The StateFlow updates
60− // whenever the scan completes, so the Diagnostics screen reflects the result.
61− scope.launch { runCatchingCancellable { refresh() } }
62− }
63−
64− /** Monotonic guard so a slower earlier scan can't overwrite a newer one's result.
65− * refresh() runs on the multi-threaded IO dispatcher from several call sites
66− * (install/deleteReport/scheduleDelete/clearAll), so two scans can overlap. */
67− private val refreshGeneration = java.util.concurrent.atomic.AtomicLong(0)
68−
69− fun refresh() {
70− val generation = refreshGeneration.incrementAndGet()
71− val scanned = crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }
72− ?.sortedByDescending { it.lastModified() }
73− ?.map { f ->
74− CrashReport(
75− fileName = f.name,
76− timestamp = f.lastModified(),
77− preview = runCatching { f.useLines { it.firstOrNull() ?: "" } }.getOrDefault(""),
78− )
79− }
80− .orEmpty()
81− // Publish only if no newer refresh has started meanwhile, so a stale scan (e.g. one
82− // that started before a delete) can't momentarily re-show a just-removed report.
83− if (generation == refreshGeneration.get()) _reports.value = scanned
84− }
85−
86− fun readReport(fileName: String): String? {
87− val file = File(crashDir, fileName).canonicalFile
88− if (!file.path.startsWith(crashDir.canonicalPath + File.separator) || !file.isFile) return null
89− return runCatching { file.readText() }.getOrNull()
90− }
91−
92− fun deleteReport(fileName: String) {
93− scope.launch {
94− val file = File(crashDir, fileName).canonicalFile
95− if (file.path.startsWith(crashDir.canonicalPath + File.separator)) {
96− file.delete()
97− }
98− refresh()
99− }
100− }
101−
102− /** Whether any crash report is newer than the last-acknowledged timestamp — i.e. a
103− * crash happened in a previous run that the user hasn't been prompted about yet.
104− * Called on cold start to surface a "crashed last time" dialog. */
105− fun hasUnacknowledgedCrash(): Boolean {
106− val acknowledgedAt = crashPrefs.getLong(KEY_ACKNOWLEDGED_AT, 0L)
107− return crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }
108− ?.any { it.lastModified() > acknowledgedAt } == true
109− }
110−
111− /** Mark all current crash reports as acknowledged so the cold-start prompt doesn't
112− * re-fire on the next launch. */
113− fun acknowledgeCrashes() {
114− crashPrefs.edit().putLong(KEY_ACKNOWLEDGED_AT, System.currentTimeMillis()).apply()
115− }
116−
117− /** Deferred deletions keyed by file name, so an Undo can cancel one before it fires. */
118− private val pendingDeletes = java.util.concurrent.ConcurrentHashMap<String, Job>()
119−
120− /**
121− * Schedule [fileName] for deletion after [delayMs], cancellable via
122− * [cancelScheduledDelete]. Runs on the logger's own long-lived scope — not the
123− * Diagnostics screen's composition scope — so navigating away during the undo window
124− * still commits the delete instead of silently dropping it. A repeated schedule for
125− * the same name replaces the prior timer.
126− */
127− fun scheduleDelete(fileName: String, delayMs: Long) {
128− val job = scope.launch {
129− delay(delayMs)
130− // Atomically claim the delete by removing our own map entry BEFORE deleting.
131− // The remove is the synchronization point with cancelScheduledDelete: whichever
132− // removes the entry first wins. If an undo raced the timer and removed it first,
133− // this returns false and we skip the delete — so the file survives, matching the
134− // `true` that cancel returned to the UI. Deleting first (then removing) would let
135− // a cancel land in the gap and falsely report "undo succeeded" for a gone file.
136− // remove(name, thisJob) also no-ops for a stale job after a reschedule.
137− val claimed = coroutineContext[Job]?.let { pendingDeletes.remove(fileName, it) } == true
138− if (!claimed) return@launch
139− val file = File(crashDir, fileName).canonicalFile
140− if (file.path.startsWith(crashDir.canonicalPath + File.separator)) {
141− file.delete()
142− }
143− refresh()
144− }
145− pendingDeletes.put(fileName, job)?.cancel()
146− }
147−
148− /** Cancel a pending deferred delete (the Undo action). Returns true if it was still
149− * pending (undo succeeded), false if the delete had already fired. */
150− fun cancelScheduledDelete(fileName: String): Boolean {
151− val job = pendingDeletes.remove(fileName) ?: return false
152− job.cancel()
153− return true
154− }
155−
156− fun clearAll() {
157− scope.launch {
158− crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }?.forEach { it.delete() }
159− refresh()
160− }
161− }
162−
163− /** Deferred whole-directory clear, cancellable via [cancelScheduledClearAll] so the bulk
164− * action gets the same undo window as a single-report delete. Runs on the logger's own
165− * scope so it commits even if the user leaves the Diagnostics screen. */
166− private var pendingClearAll: Job? = null
167−
168− fun scheduleClearAll(delayMs: Long) {
169− pendingClearAll?.cancel()
170− pendingClearAll = scope.launch {
171− delay(delayMs)
172− pendingClearAll = null
173− crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") }?.forEach { it.delete() }
174− refresh()
175− }
176− }
177−
178− /** Cancel a pending clear-all (the Undo action). Returns true if it was still pending. */
179− fun cancelScheduledClearAll(): Boolean {
180− val job = pendingClearAll ?: return false
181− pendingClearAll = null
182− job.cancel()
183− return true
184− }
185−
186− fun reportCount(): Int = _reports.value.size
187−
188− /** Cancel the internal coroutine scope so background work doesn't outlive the
189− * process. Called from [AppContainer.shutdown]. The UncaughtExceptionHandler is
190− * intentionally left installed — a crash during shutdown still needs to be logged. */
191− fun shutdown() {
192− scope.cancel()
193− }
194−
195− private fun writeReport(thread: Thread, throwable: Throwable) {
196− val now = Date()
197− val stamp = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS", Locale.US).format(now)
198− // Append a short random suffix so two crashes in the same millisecond don't
199− // overwrite each other.
200− val suffix = java.lang.Long.toHexString(System.nanoTime())
201− val file = File(crashDir, "crash-$stamp-$suffix.txt")
202− val sw = StringWriter()
203− PrintWriter(sw).use { pw ->
204− pw.println("opencode-android crash report")
205− pw.println("Time: ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US).format(now)}")
206− pw.println("Thread: ${thread.name}")
207− pw.println("App version: ${appVersion()}")
208− pw.println("Device: ${Build.MANUFACTURER} ${Build.MODEL}")
209− pw.println("Android: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
210− pw.println("ABI: ${Build.SUPPORTED_ABIS.joinToString()}")
211− pw.println()
212− pw.println(throwable.javaClass.name + ": " + throwable.message)
213− throwable.printStackTrace(pw)
214− }
215− // Scrub URLs from the *entire* report. printStackTrace re-emits the exception
216− // message (and every "Caused by:" message) verbatim, so scrubbing only the
217− // top-level message above is futile — Ktor/OkHttp embed the full request URL
218− // in those messages, which may contain auth or internal paths. Scrubbing the
219− // assembled text guarantees no URL survives anywhere in the stored report.
220− file.writeText(scrubUrls(sw.toString()))
221− trimOldReports()
222− }
223−
224− /** Keep only the [MAX_REPORTS] most recent crash reports, deleting older ones. Runs inside
225− * the uncaught-exception handler (the whole call is wrapped in runCatching upstream), so it
226− * must not throw; each delete is guarded. */
227− private fun trimOldReports() {
228− val files = crashDir.listFiles { f -> f.isFile && f.name.endsWith(".txt") } ?: return
229− if (files.size <= MAX_REPORTS) return
230− files.sortedByDescending { it.lastModified() }
231− .drop(MAX_REPORTS)
232− .forEach { runCatching { it.delete() } }
233− }
234−
235− private fun appVersion(): String = runCatching {
236− val pi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
237− appContext.packageManager.getPackageInfo(
238− appContext.packageName,
239− PackageManager.PackageInfoFlags.of(0),
240− )
241− } else {
242− @Suppress("DEPRECATION")
243− appContext.packageManager.getPackageInfo(appContext.packageName, 0)
244− }
245− "${pi.versionName} (${PackageInfoCompat.getLongVersionCode(pi)})"
246− }.getOrDefault("unknown")
247−
248− companion object {
249− /** Cap on retained crash report files. A deterministic crash-loop (e.g. a crash on
250− * startup) writes one report per crash with no other bound, so without this the
251− * crashes/ dir grows without limit until the user manually clears it. */
252− private const val MAX_REPORTS = 20
253−
254− private const val KEY_ACKNOWLEDGED_AT = "acknowledged_at"
255−
256− /** Regex matching http(s) URLs, shared by report writing and [scrubUrls]. */
257− internal val SCRUB_URL_REGEX = Regex("https?://[^\\s\"']+")
258−
259− /**
260− * Replace every http(s) URL in [text] with `[url]`. Exposed as `internal` so the
261− * redaction (used on the whole crash report, including exception messages and
262− * stack traces produced by printStackTrace) can be unit-tested in isolation.
263− */
264− internal fun scrubUrls(text: String): String = SCRUB_URL_REGEX.replace(text, "[url]")
265−
266− @Volatile
267− private var instance: CrashLogger? = null
268−
269− fun get(context: Context): CrashLogger =
270− instance ?: synchronized(this) {
271− instance ?: CrashLogger(context.applicationContext).also { instance = it }
272− }
273− }
274−}
app/src/main/java/soy/iko/opencode/data/repo/DraftStore.ktdeleted−260
@@ -1,260 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.CoroutineScope
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.flow.MutableStateFlow
7−import kotlinx.coroutines.flow.StateFlow
8−import kotlinx.coroutines.flow.asStateFlow
9−import kotlinx.coroutines.flow.update
10−import android.util.Log
11−import kotlinx.coroutines.launch
12−import java.util.concurrent.Executors
13−
14−/**
15− * Persists the in-progress message draft for each session so it survives
16− * back-navigation and process death. Backed by SharedPreferences because the
17− * UI needs the initial value synchronously and drafts are low-stakes data.
18− *
19− * The prefs file is loaded on a background thread at construction time. Until
20− * the load completes, [drafts] reports an empty map and [get] returns "" rather
21− * than blocking the caller (previously a [CountDownLatch] could stall the main
22− * thread for up to 2 seconds on a slow disk).
23− */
24−open class DraftStore private constructor(
25− private val appContext: Context?,
26− private val scope: CoroutineScope?,
27− @Suppress("unused") private val testMode: Boolean,
28−) {
29− constructor(context: Context, scope: CoroutineScope) : this(context.applicationContext, scope, false)
30− protected constructor() : this(null, null, true)
31−
32− private val prefs by lazy {
33− appContext?.getSharedPreferences("drafts", Context.MODE_PRIVATE)
34− ?: error("No context — override methods in test subclass")
35− }
36−
37− /** Single-thread executor for flushDraft when prefs aren't initialized yet,
38− * so the main thread is never blocked on disk I/O. */
39− private val flushExecutor by lazy {
40− Executors.newSingleThreadExecutor { r ->
41− Thread(r, "DraftStore-flush").apply { isDaemon = true }
42− }
43− }
44−
45− private val _drafts = MutableStateFlow<Map<String, String>>(emptyMap())
46− /** The full in-memory snapshot of all drafts, updated when prefs finish loading. */
47− open val drafts: StateFlow<Map<String, String>> = _drafts.asStateFlow()
48−
49− /** Queued follow-up messages per session, persisted under a namespaced key so a
50− * follow-up queued mid-run survives process death (the in-memory-only StateFlow in
51− * ChatViewModel would otherwise lose it, along with the cleared draft). */
52− private val _followUps = MutableStateFlow<Map<String, String>>(emptyMap())
53−
54− private val _ready = MutableStateFlow(false)
55− /** True once the background prefs load has completed. */
56− open val ready: StateFlow<Boolean> = _ready.asStateFlow()
57−
58− /** Keys written in-memory (set / cleared / removed) *before* the async prefs load
59− * finished. For these the in-memory state is authoritative — the load must not
60− * resurrect a persisted value the user has since cleared, which a plain putAll(current)
61− * merge cannot express (it can add/override, but not delete). Consulted once, in the
62− * init merge. Separate sets because drafts and follow-ups share the session-id key space
63− * but live under different prefs keys. */
64− // ConcurrentHashMap-backed sets: weakly-consistent iteration so the init merge's forEach
65− // can't throw ConcurrentModificationException if a mutator adds a key concurrently.
66− private val touchedDraftKeys: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
67− private val touchedFollowUpKeys: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
68−
69− private fun markDraftTouched(sessionId: String) {
70− if (!_ready.value) touchedDraftKeys.add(sessionId)
71− }
72− private fun markFollowUpTouched(sessionId: String) {
73− if (!_ready.value) touchedFollowUpKeys.add(sessionId)
74− }
75−
76− init {
77− // Eagerly load the prefs file on a background thread so the first main-thread
78− // get() doesn't block on disk I/O. The loaded snapshot is published via [_drafts]
79− // so callers can observe readiness without blocking.
80− if (scope != null && appContext != null) {
81− scope.launch(Dispatchers.IO) {
82− val all = runCatching {
83− prefs.all.mapValues { it.value as? String ?: "" }
84− }.getOrDefault(emptyMap())
85− // Partition persisted keys: follow-up keys carry a prefix, everything else
86− // is a plain per-session draft.
87− val drafts = mutableMapOf<String, String>()
88− val followUps = mutableMapOf<String, String>()
89− all.forEach { (k, v) ->
90− if (k.startsWith(FOLLOWUP_PREFIX)) followUps[k.removePrefix(FOLLOWUP_PREFIX)] = v
91− else drafts[k] = v
92− }
93− // Merge instead of overwriting: any in-memory writes that arrived before
94− // the background load completed (e.g. a share-intent draft injected via
95− // setImmediate) take priority over the persisted snapshot so they aren't
96− // clobbered. For keys the user explicitly touched before the load finished,
97− // drop the persisted entry first so a value they *cleared* isn't resurrected
98− // (the cleared key is absent from `current`, so putAll alone can't remove it).
99− _drafts.update { current ->
100− drafts.apply {
101− touchedDraftKeys.forEach { remove(it) }
102− putAll(current)
103− }
104− }
105− _followUps.update { current ->
106− followUps.apply {
107− touchedFollowUpKeys.forEach { remove(it) }
108− putAll(current)
109− }
110− }
111− _ready.value = true
112− }
113− } else {
114− _ready.value = true
115− }
116− }
117−
118− /** Returns the draft for [sessionId], or "" if not found or still loading. */
119− open fun get(sessionId: String): String = _drafts.value[sessionId].orEmpty()
120−
121− /** Returns the queued follow-up for [sessionId], or "" if none / still loading. */
122− open fun getFollowUp(sessionId: String): String = _followUps.value[sessionId].orEmpty()
123−
124− /** Persist a queued follow-up immediately (fire-and-forget, main-thread-safe).
125− * Mirrors [flushDraft]: async apply() when prefs are open, else a background thread,
126− * so a follow-up queued just before process death is flushed before the process exits.
127− * A blank [text] clears the stored follow-up. */
128− open fun flushFollowUp(sessionId: String, text: String) {
129− markFollowUpTouched(sessionId)
130− _followUps.update { current ->
131− val updated = current.toMutableMap()
132− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
133− updated
134− }
135− writeAsync(FOLLOWUP_PREFIX + sessionId, text)
136− }
137−
138− /** Persist [key]=[text] (or remove it when blank) without blocking the main thread on
139− * first-time disk I/O — see [flushDraft] for the prefs-not-yet-open rationale. */
140− private fun writeAsync(key: String, text: String) {
141− val write = {
142− runCatching {
143− prefs.edit().apply {
144− if (text.isBlank()) remove(key) else putString(key, text)
145− }.apply()
146− }.onFailure { Log.w("DraftStore", "Failed to persist $key", it) }
147− }
148− // FIX: always submit to the single-thread flushExecutor (never apply directly) so
149− // writes persist in submission order. Previously the post-init fast path applied
150− // synchronously on the caller's thread, which could land BEFORE an earlier still-queued
151− // write, persisting stale text. The task resolves the prefs lazy and calls apply().
152− runCatching { flushExecutor.execute { write() } }
153− }
154−
155− /** Update the in-memory draft immediately without persisting to disk.
156− * Used when navigation must see the new value synchronously (e.g. share-intent
157− * injection before ChatScreen composes). Call [set] afterwards to persist. */
158− open fun setImmediate(sessionId: String, text: String) {
159− markDraftTouched(sessionId)
160− _drafts.update { current ->
161− val updated = current.toMutableMap()
162− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
163− updated
164− }
165− }
166−
167− open suspend fun set(sessionId: String, text: String) {
168− markDraftTouched(sessionId)
169− _drafts.update { current ->
170− val updated = current.toMutableMap()
171− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
172− updated
173− }
174− // Route persistence through the single-thread flushExecutor (like the other writers)
175− // rather than the shared IO pool, so this write can't race ahead of an earlier queued
176− // flush and land stale. writeAsync persists sessionId=text (or removes it when blank),
177− // which is exactly this draft's persistence.
178− writeAsync(sessionId, text)
179− }
180−
181− /** Remove the draft for a session (call on session deletion to avoid orphaned entries).
182− * Also clears any queued follow-up so a deleted session leaves nothing behind. */
183− open suspend fun remove(sessionId: String) {
184− markDraftTouched(sessionId)
185− markFollowUpTouched(sessionId)
186− _drafts.update { current ->
187− val updated = current.toMutableMap()
188− updated.remove(sessionId)
189− updated
190− }
191− _followUps.update { current ->
192− val updated = current.toMutableMap()
193− updated.remove(sessionId)
194− updated
195− }
196− // Submit the (combined draft + follow-up) removal to the same single-thread
197− // flushExecutor the other writers use, so it can't race ahead of an earlier queued
198− // write and resurrect stale text. Mirrors flushDraft's submission pattern.
199− runCatching {
200− flushExecutor.execute {
201− runCatching {
202− prefs.edit().remove(sessionId).remove(FOLLOWUP_PREFIX + sessionId).apply()
203− }.onFailure { Log.w("DraftStore", "Failed to remove draft for $sessionId", it) }
204− }
205− }
206− }
207−
208− /**
209− * Synchronously persist a draft. Intended for [ViewModel.onCleared] where the
210− * viewModelScope is already cancelled and a suspending write can't be used.
211− *
212− * If the SharedPreferences file has already been opened (the normal case — the
213− * background init load touches it shortly after construction), the write uses
214− * [apply] (asynchronous) and returns immediately without blocking the main thread.
215− *
216− * If the prefs file has NOT been opened yet (a rare race where onCleared fires
217− * before the background init), the write is dispatched to a background thread
218− * instead of blocking the main thread on a synchronous disk read. The draft
219− * may be lost if the process exits before the write completes, but this is
220− * preferable to an ANR.
221− */
222− open fun flushDraft(sessionId: String, text: String) {
223− markDraftTouched(sessionId)
224− _drafts.update { current ->
225− val updated = current.toMutableMap()
226− if (text.isBlank()) updated.remove(sessionId) else updated[sessionId] = text
227− updated
228− }
229− // FIX: always route the persistence through the single-thread flushExecutor so writes
230− // land in submission order. Previously, once prefs were open this applied synchronously
231− // on the calling (main) thread, so a newer direct write could persist BEFORE an older
232− // still-queued write completed, clobbering the draft with stale text. The executor task
233− // resolves the prefs lazy and uses apply() (async) exactly as before; the write may be
234− // lost only if the process exits before the queued task runs (as previously).
235− runCatching {
236− flushExecutor.execute {
237− runCatching {
238− prefs.edit().apply {
239− if (text.isBlank()) remove(sessionId) else putString(sessionId, text)
240− }.apply()
241− }.onFailure { Log.w("DraftStore", "Failed to flush draft for $sessionId", it) }
242− }
243− }
244− }
245−
246− private companion object {
247− /** Key prefix distinguishing persisted follow-ups from plain drafts in the shared
248− * prefs file. The leading/trailing spaces can't collide with a real opencode session
249− * id (which are non-blank, space-free tokens like "ses_..."). */
250− const val FOLLOWUP_PREFIX = " followup "
251− }
252−
253− /** Shut down the background flush executor. Call from AppContainer.shutdown(). */
254− open fun shutdown() {
255− flushExecutor.shutdown()
256− // Await pending flushDraft writes so drafts aren't lost if the process exits
257− // immediately after shutdown (e.g. ANR-triggered process kill).
258− runCatching { flushExecutor.awaitTermination(2, java.util.concurrent.TimeUnit.SECONDS) }
259− }
260−}
app/src/main/java/soy/iko/opencode/data/repo/ErrorKind.ktdeleted−78
@@ -1,78 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import io.ktor.client.plugins.ClientRequestException
4−import io.ktor.client.plugins.HttpRequestTimeoutException
5−import io.ktor.client.plugins.RedirectResponseException
6−import io.ktor.client.plugins.ResponseException
7−import io.ktor.client.plugins.ServerResponseException
8−import java.io.IOException
9−import java.net.ConnectException
10−import java.net.SocketTimeoutException
11−import java.net.UnknownHostException
12−
13−/**
14− * User-facing categories for a thrown error. Extracted so the classification logic is
15− * unit-testable without an Android [android.content.Context] (the mapping from a kind
16− * to a localized string lives in [friendlyError]).
17− */
18−enum class ErrorKind {
19− /** Server host could not be resolved / connection refused. */
20− NOT_REACHABLE,
21−
22− /** Connect or read timed out. */
23− TIMEOUT,
24−
25− /** Server returned a 5xx response. */
26− SERVER,
27−
28− /** Server returned a 4xx response (auth, not-found, etc.). */
29− CLIENT,
30−
31− /** Any other network-level I/O failure. */
32− NETWORK,
33−
34− /** Anything that isn't network-related. */
35− UNKNOWN,
36−}
37−
38−/**
39− * Classify a throwable into an [ErrorKind] by inspecting concrete exception types rather
40− * than string-matching class names. Unwraps [cause] chains so an exception surface-wrapped
41− * by a library still classifies correctly.
42− */
43−fun classifyError(t: Throwable): ErrorKind {
44− var current: Throwable? = t
45− // Walk a bounded cause chain so wrappers (e.g. an IllegalStateException around an
46− // IOException) still classify by their root.
47− var hops = 0
48− while (current != null && hops < 8) {
49− when (current) {
50− is UnknownHostException, is ConnectException -> return ErrorKind.NOT_REACHABLE
51− is SocketTimeoutException, is HttpRequestTimeoutException ->
52− return ErrorKind.TIMEOUT
53− is ServerResponseException -> return ErrorKind.SERVER
54− is ClientRequestException -> return ErrorKind.CLIENT
55− is RedirectResponseException -> return ErrorKind.CLIENT
56− is IOException -> return ErrorKind.NETWORK
57− else -> {
58− // Any other ResponseException (unrecognized status family).
59− if (current is ResponseException) return ErrorKind.SERVER
60− }
61− }
62− current = current.cause
63− hops++
64− }
65− return ErrorKind.UNKNOWN
66−}
67−
68−/** The HTTP status code carried by a client/server error, if any. */
69−fun responseStatusCode(t: Throwable): Int? {
70− var current: Throwable? = t
71− var hops = 0
72− while (current != null && hops < 8) {
73− if (current is ResponseException) return current.response.status.value
74− current = current.cause
75− hops++
76− }
77− return null
78−}
app/src/main/java/soy/iko/opencode/data/repo/FileBrowserPrefs.ktdeleted−90
@@ -1,90 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import androidx.datastore.preferences.core.booleanPreferencesKey
5−import androidx.datastore.preferences.core.edit
6−import androidx.datastore.preferences.core.stringPreferencesKey
7−import androidx.datastore.preferences.preferencesDataStore
8−import kotlinx.coroutines.flow.Flow
9−import kotlinx.coroutines.flow.flowOf
10−import kotlinx.coroutines.flow.map
11−
12−private val Context.fileBrowserPrefsDataStore by preferencesDataStore(name = "file_browser_prefs")
13−
14−/** Sort axis for the file-browser directory listing. Name is always available; Size/Modified
15− * depend on the server emitting size/mtime (otherwise they sort nulls to the bottom). */
16−enum class FileSortKey { NAME, SIZE, MODIFIED }
17−
18−/**
19− * Persisted file-browser display prefs (folders-first, show-hidden, sort key + direction,
20− * changed-only filter) so a user who prefers size-sort or hidden-files-visible keeps it
21− * across restarts, not just rotation.
22− *
23− * `open` with a `protected` no-arg constructor so tests can subclass and override the flows
24− * without a real DataStore (mirrors the other stores). The flow accessors are getters (not
25− * eager initializers) and null-guard the context so the test constructor never touches disk.
26− */
27−@Suppress("TooManyFunctions")
28−open class FileBrowserPrefs private constructor(
29− private val appContext: Context?,
30− @Suppress("unused") private val testMode: Boolean,
31−) {
32− constructor(context: Context) : this(context.applicationContext, false)
33− protected constructor() : this(null, true)
34−
35− private val foldersFirstKey = booleanPreferencesKey("folders_first")
36− private val showHiddenKey = booleanPreferencesKey("show_hidden")
37− private val sortKeyPref = stringPreferencesKey("sort_key")
38− private val sortDescKey = booleanPreferencesKey("sort_desc")
39− private val changedOnlyKey = booleanPreferencesKey("changed_only")
40−
41− // Folders-first is the most useful default; the toggle flips between folders-first name
42− // sort and the server's raw order.
43− open val foldersFirst: Flow<Boolean>
44− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[foldersFirstKey] ?: true }
45− ?: flowOf(true)
46−
47− // Default off so the listing isn't cluttered with dotfiles; the user reveals .env / .git
48− // / .opencode on demand.
49− open val showHidden: Flow<Boolean>
50− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[showHiddenKey] ?: false }
51− ?: flowOf(false)
52−
53− // Stored as the enum name; an unknown value falls back to NAME (forward-compatible with a
54− // future rename/removal of an enum entry).
55− open val sortKey: Flow<FileSortKey>
56− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { prefs ->
57− runCatching { FileSortKey.valueOf(prefs[sortKeyPref] ?: FileSortKey.NAME.name) }
58− .getOrDefault(FileSortKey.NAME)
59− } ?: flowOf(FileSortKey.NAME)
60−
61− open val sortDesc: Flow<Boolean>
62− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[sortDescKey] ?: false }
63− ?: flowOf(false)
64−
65− // Default off: the changed-only filter narrows the listing to git-tracked changes, which is
66− // useful when reviewing a diff but not the default browsing view.
67− open val changedOnly: Flow<Boolean>
68− get() = appContext?.fileBrowserPrefsDataStore?.data?.map { it[changedOnlyKey] ?: false }
69− ?: flowOf(false)
70−
71− open suspend fun setFoldersFirst(value: Boolean) {
72− appContext?.fileBrowserPrefsDataStore?.edit { it[foldersFirstKey] = value }
73− }
74−
75− open suspend fun setShowHidden(value: Boolean) {
76− appContext?.fileBrowserPrefsDataStore?.edit { it[showHiddenKey] = value }
77− }
78−
79− open suspend fun setSortKey(key: FileSortKey) {
80− appContext?.fileBrowserPrefsDataStore?.edit { it[sortKeyPref] = key.name }
81− }
82−
83− open suspend fun setSortDesc(value: Boolean) {
84− appContext?.fileBrowserPrefsDataStore?.edit { it[sortDescKey] = value }
85− }
86−
87− open suspend fun setChangedOnly(value: Boolean) {
88− appContext?.fileBrowserPrefsDataStore?.edit { it[changedOnlyKey] = value }
89− }
90−}
app/src/main/java/soy/iko/opencode/data/repo/MessageCacheStore.ktdeleted−137
@@ -1,137 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.sync.Mutex
7−import kotlinx.coroutines.sync.withLock
8−import kotlinx.coroutines.withContext
9−import kotlinx.serialization.builtins.ListSerializer
10−import soy.iko.opencode.data.model.MessageWithParts
11−import soy.iko.opencode.data.network.OpencodeJson
12−import soy.iko.opencode.util.runCatchingCancellable
13−import java.io.File
14−
15−/**
16− * On-disk cache of a session's reduced message list, so a conversation shows instantly on
17− * open (and remains readable while offline / before the network responds) instead of a blank
18− * screen until `GET /session/:id/message` returns.
19− *
20− * One JSON file per session under filesDir, encoded with [OpencodeJson] so the same sealed
21− * polymorphism used on the wire round-trips (unknown parts/messages are concrete
22− * `__unknown` variants, so they encode too). Every operation is best-effort — a cache
23− * miss or a write failure just falls back to the network — so problems never surface to
24− * the user. No annotation processing (Room/KSP) per the project's manual-DI convention.
25− */
26−open class MessageCacheStore private constructor(
27− private val appContext: Context?,
28− @Suppress("unused") private val testMode: Boolean,
29−) {
30− constructor(context: Context) : this(context.applicationContext, false)
31− protected constructor() : this(null, true)
32−
33− private val serializer = ListSerializer(MessageWithParts.serializer())
34−
35− /** Session ids are validated tokens upstream, but sanitize anyway so a stray id can't
36− * escape the directory. */
37− private val idRegex = Regex("[^A-Za-z0-9_-]")
38−
39− private val dir: File? by lazy {
40− appContext?.let { File(it.filesDir, "message_cache").apply { mkdirs() } }
41− }
42−
43− /** Per-profile subdirectory: two servers with a colliding session id must not share a cache
44− * file, so entries are namespaced by profile id under [dir]. */
45− private fun profileDir(profileId: String): File? =
46− dir?.let { File(it, idRegex.replace(profileId, "_")).apply { mkdirs() } }
47−
48− private fun fileFor(profileId: String, sessionId: String): File? =
49− profileDir(profileId)?.let { File(it, idRegex.replace(sessionId, "_") + ".json") }
50−
51− /** Per-session write lock so concurrent save/remove/load on the same file (e.g. both
52− * panes of two-pane mode saving the same session, or a save racing a delete's remove)
53− * can't tear or half-write the cache file. Keyed by session id; the map grows only with
54− * the number of distinct sessions touched, and each [Mutex] is a few bytes. */
55− private val locks = java.util.concurrent.ConcurrentHashMap<String, Mutex>()
56− private fun lockFor(sessionId: String): Mutex = locks.getOrPut(sessionId) { Mutex() }
57−
58− /** Sessions whose cache file has been removed by [remove]. A teardown flush of an
59− * observer (CacheWriter.flushOnTeardown) runs under NonCancellable and can race with
60− * remove(): both serialize on [lockFor], but their relative order is nondeterministic.
61− * If the flush's save lands after remove, it re-creates the deleted session's cache
62− * file, defeating the deletion (a privacy/disk-leak with no background cleanup). The
63− * tombstone lets a post-remove save detect the deletion and skip. Keyed by
64− * "$profileId/$sessionId" — a bare sessionId would suppress a *different* server's
65− * saves if two servers share a colliding session id (the very case the per-profile
66− * namespacing at [profileDir] exists to defend against). Cleared by [load] so
67− * re-opening a session re-enables saving. Bounded by distinct deleted sessions. */
68− private val tombstones: MutableSet<String> =
69− java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap())
70−
71− private fun tombstoneKey(profileId: String, sessionId: String): String = "$profileId/$sessionId"
72−
73− /** Load the cached messages for [sessionId] under [profileId], or empty if none / unreadable. */
74− open suspend fun load(profileId: String, sessionId: String): List<MessageWithParts> = lockFor(sessionId).withLock {
75− // Re-opening a session re-enables saving: clear any tombstone so a fresh conversation
76− // write isn't suppressed by a prior deletion of the same (reused) id.
77− tombstones.remove(tombstoneKey(profileId, sessionId))
78− withContext(Dispatchers.IO) {
79− val file = fileFor(profileId, sessionId)?.takeIf { it.exists() } ?: return@withContext emptyList()
80− runCatchingCancellable { OpencodeJson.decodeFromString(serializer, file.readText()) }
81− .getOrDefault(emptyList())
82− }
83− }
84−
85− /** Persist [messages] for [sessionId] under [profileId] (an empty list deletes the file). */
86− open suspend fun save(profileId: String, sessionId: String, messages: List<MessageWithParts>): Unit = lockFor(sessionId).withLock {
87− // Skip if this session was deleted since the observer started: a teardown flush racing
88− // after remove() must not re-create the file. (Held under the same per-session lock as
89− // remove, so the tombstone is visible to a save that lost the race.)
90− if (tombstoneKey(profileId, sessionId) in tombstones) return@withLock
91− withContext(Dispatchers.IO) {
92− val file = fileFor(profileId, sessionId) ?: return@withContext
93− runCatchingCancellable {
94− if (messages.isEmpty()) file.delete()
95− else {
96− // FIX: write atomically (temp file + rename) like RecentSessionsStore so a
97− // process kill mid-write can't leave a truncated file that fails to decode,
98− // wiping the cached conversation on the next open.
99− val encoded = OpencodeJson.encodeToString(serializer, messages)
100− val tmp = File(file.parentFile, file.name + ".tmp")
101− tmp.writeText(encoded)
102− if (!tmp.renameTo(file)) {
103− file.writeText(encoded)
104− tmp.delete()
105− }
106− }
107− }.onFailure { Log.w("MessageCacheStore", "Failed to cache messages for $sessionId", it) }
108− Unit
109− }
110− }
111−
112− /** Remove a session's cached messages (call on deletion). Clears the entry in every profile
113− * namespace: session ids are unique per server and deletion is terminal, so the caller
114− * needn't know which profile owned it. The per-session lock is intentionally NOT evicted —
115− * a concurrent teardown save() for this id must serialize against the same [Mutex] instance,
116− * and the map is bounded by the number of distinct sessions touched.
117− * [profileId] namespaces the tombstone so a delete on one server doesn't suppress another
118− * server's saves for a colliding session id. */
119− open suspend fun remove(profileId: String, sessionId: String) {
120− lockFor(sessionId).withLock {
121− // Set the tombstone before deleting so a concurrent/loser save sees it and skips,
122− // instead of re-creating the file we're about to delete.
123− tombstones.add(tombstoneKey(profileId, sessionId))
124− withContext(Dispatchers.IO) {
125− runCatchingCancellable {
126− val name = idRegex.replace(sessionId, "_") + ".json"
127− dir?.listFiles()?.forEach { entry ->
128− if (entry.isDirectory) File(entry, name).delete()
129− }
130− // Back-compat: pre-namespacing caches were written flat under [dir].
131− dir?.let { File(it, name).delete() }
132− }
133− Unit
134− }
135− }
136− }
137−}
app/src/main/java/soy/iko/opencode/data/repo/OutboxStore.ktdeleted−168
@@ -1,168 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import android.util.Log
5−import kotlinx.coroutines.Dispatchers
6−import kotlinx.coroutines.flow.MutableStateFlow
7−import kotlinx.coroutines.flow.StateFlow
8−import kotlinx.coroutines.flow.asStateFlow
9−import kotlinx.coroutines.sync.Mutex
10−import kotlinx.coroutines.sync.withLock
11−import kotlinx.coroutines.withContext
12−import kotlinx.serialization.Serializable
13−import kotlinx.serialization.decodeFromString
14−import kotlinx.serialization.encodeToString
15−import kotlinx.serialization.json.Json
16−import soy.iko.opencode.data.model.ModelRef
17−import soy.iko.opencode.util.runCatchingCancellable
18−import java.io.File
19−
20−/**
21− * One prompt composed while offline (or with no active connection), queued to send when
22− * connectivity returns. Tagged with the [profileId] it was composed for so a reconnect to a
23− * *different* server doesn't misfire it against a session id that only exists on the
24− * original server. [attachments] carry their self-contained base64 data URLs, so a queued
25− * image survives a process restart just like a staged attachment.
26− */
27−@Serializable
28−data class OutboxMessage(
29− val id: String,
30− val profileId: String,
31− val sessionId: String,
32− val text: String,
33− val attachments: List<PersistedAttachment> = emptyList(),
34− val model: ModelRef? = null,
35− val agent: String? = null,
36− val createdAt: Long,
37−)
38−
39−/**
40− * A persisted send-queue: prompts the user composed while disconnected, flushed on
41− * reconnect (see [soy.iko.opencode.di.AppContainer.observeOutbox]). Backed by one JSON file
42− * under filesDir (not SharedPreferences) because a queued attachment's base64 payload can be
43− * several megabytes. The in-memory [messages] StateFlow is the source of truth the UI and the
44− * flusher observe; disk is written through under a mutex on every mutation.
45− */
46−open class OutboxStore private constructor(
47− private val appContext: Context?,
48− @Suppress("unused") private val testMode: Boolean,
49−) {
50− constructor(context: Context) : this(context.applicationContext, false)
51− protected constructor() : this(null, true)
52−
53− private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
54− private val ioMutex = Mutex()
55−
56− private val _messages = MutableStateFlow<List<OutboxMessage>>(emptyList())
57− /** All queued messages across sessions/servers, in enqueue order. */
58− open val messages: StateFlow<List<OutboxMessage>> = _messages.asStateFlow()
59−
60− /** Set once the on-disk queue has been read into [_messages] (under [ioMutex]). Until this
61− * is true, a [mutate] must read disk first — otherwise a mutation that beats [load] would
62− * persist from an empty in-memory snapshot and overwrite (or, for a removal, delete) the
63− * persisted queue, losing every message the user composed offline in a previous run. */
64− private var loaded = false
65−
66− private val file: File? by lazy {
67− appContext?.let { File(it.filesDir, "outbox.json") }
68− }
69−
70− /** Read the persisted queue into [messages]. Call once at startup. Idempotent. */
71− open suspend fun load() {
72− ioMutex.withLock { loadLocked() }
73− }
74−
75− /** Read the on-disk queue into memory. MUST be called while holding [ioMutex]. Idempotent
76− * (guarded by [loaded]) so a [mutate] that arrives before [load] can call it to guarantee
77− * disk is read before any write, then a later [load] is a no-op. Returns true once the queue
78− * is in memory (or the file is genuinely absent), false if an existing file couldn't be
79− * read — the caller MUST NOT persist on false or it would overwrite the still-valid queue. */
80− private suspend fun loadLocked(): Boolean {
81− if (loaded) return true
82− val f = file?.takeIf { it.exists() }
83− if (f == null) {
84− // A genuinely absent file is a normal empty queue: mark loaded so mutations proceed.
85− loaded = true
86− return true
87− }
88− // Only mark [loaded] AFTER a successful read. A transient read/decode failure (or a
89− // cancelled read) of an *existing* file must not clobber the still-valid on-disk queue:
90− // leave loaded=false and report failure so the caller skips its write and a later
91− // mutate/load retries the read, instead of persisting an empty snapshot over the user's
92− // offline-composed messages.
93− val diskList = withContext(Dispatchers.IO) {
94− runCatchingCancellable { json.decodeFromString<List<OutboxMessage>>(f.readText()) }
95− }.getOrElse { return false }
96− // Don't clobber items enqueued while the load was in flight: merge by id, keeping
97− // the in-memory version on conflict (it's newer).
98− if (_messages.value.isEmpty()) {
99− _messages.value = diskList.sortedBy { it.createdAt }
100− } else {
101− val known = _messages.value.mapTo(mutableSetOf()) { it.id }
102− val merged = (diskList.filter { it.id !in known } + _messages.value).sortedBy { it.createdAt }
103− _messages.value = merged
104− // The merge reconciled items enqueued while this load was in flight with the
105− // on-disk set; write the merged set back so a later process kill can't drop the
106− // raced enqueue. persist() doesn't take ioMutex, so this won't deadlock.
107− persist(merged)
108− }
109− loaded = true
110− return true
111− }
112−
113− open suspend fun enqueue(message: OutboxMessage) = mutate { current ->
114− current.filterNot { it.id == message.id } + message
115− }
116−
117− open suspend fun remove(id: String) = mutate { current -> current.filterNot { it.id == id } }
118−
119− /** Remove every queued message for [sessionId] (e.g. the user discarded them, or the
120− * session was deleted). */
121− open suspend fun removeForSession(sessionId: String) =
122− mutate { current -> current.filterNot { it.sessionId == sessionId } }
123−
124− private suspend fun mutate(transform: (List<OutboxMessage>) -> List<OutboxMessage>) {
125− // Persist *under* the lock so concurrent mutations (e.g. the flusher removing sent
126− // messages while the UI enqueues a new one) can't race their disk writes: without
127− // this, the older snapshot could land last and drop/resurrect a queued prompt, or two
128− // overlapping writeText/delete calls could tear the file. The lock serializes both the
129− // in-memory update and the write, guaranteeing on-disk order matches memory order.
130− ioMutex.withLock {
131− // Ensure the persisted queue has been read into memory before mutating: a mutation
132− // that races ahead of load() would otherwise transform an empty in-memory snapshot
133− // and persist()/delete() the file, destroying messages queued in a previous run.
134− val loadedOk = loadLocked()
135− val updated = transform(_messages.value).sortedBy { it.createdAt }
136− _messages.value = updated
137− // Only write when the existing on-disk queue was actually read. If the read of an
138− // existing file failed (loadedOk == false), _messages is missing whatever it held, so
139− // persisting `updated` would overwrite the still-valid file with an incomplete
140− // snapshot — losing the user's prior offline-composed messages. Keep the transform in
141− // memory (so the UI reflects the new item) but leave disk untouched; loaded stays
142− // false, so the next mutate/load retries the read and then merges + persists.
143− if (loadedOk) persist(updated)
144− }
145− }
146−
147− private suspend fun persist(list: List<OutboxMessage>) {
148− val f = file ?: return
149− withContext(Dispatchers.IO) {
150− runCatchingCancellable {
151− if (list.isEmpty()) {
152− f.delete()
153− } else {
154− // FIX: write atomically (temp file + rename) like RecentSessionsStore so a
155− // process kill mid-write can't leave a truncated file — a torn file fails to
156− // decode and load() would then drop ALL queued offline messages.
157− val encoded = json.encodeToString(list)
158− val tmp = File(f.parentFile, f.name + ".tmp")
159− tmp.writeText(encoded)
160− if (!tmp.renameTo(f)) {
161− f.writeText(encoded)
162− tmp.delete()
163− }
164− }
165− }.onFailure { Log.w("OutboxStore", "Failed to persist outbox", it) }
166− }
167− }
168−}
app/src/main/java/soy/iko/opencode/data/repo/ProfileStore.ktdeleted−251
@@ -1,251 +0,0 @@
1−// Jetpack Security (androidx.security:security-crypto) was deprecated wholesale in 1.1.0 with
2−// no first-party drop-in replacement; we intentionally keep using EncryptedSharedPreferences /
3−// MasterKey for the encrypted password store (on-disk-compatible, still functional). Suppress
4−// the expected deprecation warnings here so the build log stays clean until a future migration.
5−@file:Suppress("DEPRECATION")
6−
7−package soy.iko.opencode.data.repo
8−
9−import android.content.Context
10−import android.content.SharedPreferences
11−import android.util.Log
12−import androidx.datastore.preferences.core.edit
13−import androidx.datastore.preferences.core.stringPreferencesKey
14−import androidx.datastore.preferences.preferencesDataStore
15−import androidx.security.crypto.EncryptedSharedPreferences
16−import androidx.security.crypto.MasterKey
17−import soy.iko.opencode.data.model.ServerProfile
18−import soy.iko.opencode.data.network.OpencodeJson
19−import kotlinx.coroutines.Dispatchers
20−import kotlinx.coroutines.sync.Mutex
21−import kotlinx.coroutines.sync.withLock
22−import kotlinx.coroutines.flow.Flow
23−import kotlinx.coroutines.flow.flowOn
24−import kotlinx.coroutines.flow.map
25−import kotlinx.coroutines.withContext
26−import kotlinx.serialization.Serializable
27−import kotlinx.serialization.builtins.ListSerializer
28−
29−private val Context.dataStore by preferencesDataStore(name = "server_profiles")
30−
31−/**
32− * Persists server profiles. Non-secret fields go to DataStore (as a JSON list);
33− * the Basic-auth password is stored separately in EncryptedSharedPreferences, keyed
34− * by profile id, and merged back in on read.
35− */
36−open class ProfileStore private constructor(
37− private val appContext: Context?,
38− @Suppress("unused") private val testMode: Boolean,
39−) {
40− constructor(context: Context) : this(context.applicationContext, false)
41− protected constructor() : this(null, true)
42−
43− private val profilesKey = stringPreferencesKey("profiles_json")
44−
45− /** Guards [migrateFallbackPasswords] so it runs at most once per process, not on every
46− * DataStore emission. The mutex serializes concurrent callers so a second collector waits
47− * for the migration's writes to land (rather than skipping ahead and reading empty secure
48− * prefs mid-migration); [migrationDone] is only set true *after* the writes complete. */
49− private val migrationMutex = Mutex()
50− @Volatile private var migrationDone = false
51−
52− private val securePrefs: SharedPreferences? by lazy {
53− val ctx = appContext ?: return@lazy null
54− runCatching {
55− val masterKey = MasterKey.Builder(ctx)
56− .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
57− .build()
58− EncryptedSharedPreferences.create(
59− ctx,
60− "server_secrets",
61− masterKey,
62− EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
63− EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
64− )
65− }.getOrElse {
66− Log.e("ProfileStore", "Encrypted prefs unavailable; passwords will not be persisted", it)
67− null
68− }
69− }
70−
71− /** True when EncryptedSharedPreferences could not be initialized. */
72− open val securePrefsUnavailable: Boolean get() = securePrefs == null
73−
74− /** Plaintext fallback used only when encrypted prefs are unavailable, so the user
75− * can still connect — but passwords won't survive an app reinstall. */
76− private val fallbackPrefs: SharedPreferences by lazy {
77− appContext!!.getSharedPreferences("server_secrets_fallback", Context.MODE_PRIVATE)
78− }
79−
80− private fun prefsForPasswords(): SharedPreferences =
81− securePrefs ?: fallbackPrefs
82−
83− /** Migrate any plaintext passwords from the fallback prefs to secure prefs,
84− * then clear the fallback. Runs at most once per process — subsequent calls
85− * are no-ops — so DataStore re-emissions don't repeatedly scan SharedPreferences. */
86− private suspend fun migrateFallbackPasswords() {
87− if (migrationDone) return
88− migrationMutex.withLock {
89− // Re-check inside the lock: a concurrent caller may have completed the migration
90− // while we were waiting. Serializing here (rather than a bare compareAndSet that
91− // marks done before doing the work) ensures a second collector doesn't read the
92− // secure store before the first caller's write has populated it.
93− if (migrationDone) return
94− val secure = securePrefs
95− if (secure == null) {
96− // No secure store to migrate into; nothing to do, and no point retrying.
97− migrationDone = true
98− return
99− }
100− withContext(Dispatchers.IO) {
101− val fallbackKeys = fallbackPrefs.all.keys.filter { it.startsWith("pw_") }
102− if (fallbackKeys.isNotEmpty()) {
103− // Write passwords to the secure store FIRST, then remove them from the
104− // plaintext fallback. SharedPreferences.apply() persists to disk
105− // asynchronously, so removing from fallback before the secure batch lands
106− // could lose the password if the process dies between the two writes.
107− // Writing secure first makes the worst case a harmless duplicate (both
108− // stores hold it; the migration is idempotent) rather than data loss.
109− secure.edit().apply {
110− for (key in fallbackKeys) {
111− val pw = fallbackPrefs.getString(key, null) ?: continue
112− putString(key, pw)
113− }
114− }.apply()
115− fallbackPrefs.edit().apply {
116− for (key in fallbackKeys) remove(key)
117− }.apply()
118− }
119− }
120− // Only mark done once the writes are in the secure store's in-memory cache (apply()
121− // updates it synchronously), so the next collector past the mutex reads real values.
122− migrationDone = true
123− }
124− }
125−
126− /** Stored shape on DataStore (everything except the secret password). */
127− @Serializable
128− private data class StoredProfile(
129− val id: String,
130− val label: String,
131− val baseUrl: String,
132− val username: String? = null,
133− val lastUsed: Long = 0,
134− // Non-secret TLS options; default to prior behavior for profiles saved before these
135− // fields existed (deserialization uses these defaults for missing keys).
136− val requireHttps: Boolean = false,
137− val certPin: String? = null,
138− )
139−
140− open val profiles: Flow<List<ServerProfile>> = appContext?.dataStore?.data?.map { prefs ->
141− // Migrate any orphaned plaintext passwords to secure prefs on first load.
142− migrateFallbackPasswords()
143− val json = prefs[profilesKey] ?: return@map emptyList()
144− val stored = runCatching {
145− OpencodeJson.decodeFromString(ListSerializer(StoredProfile.serializer()), json)
146− }.onFailure { Log.w("ProfileStore", "Failed to decode stored profiles, ignoring", it) }
147− .getOrDefault(emptyList())
148− .sortedByDescending { it.lastUsed }
149− // Batch all password lookups into a single IO dispatch instead of one
150− // withContext round-trip per profile (N dispatches → 1). DataStore already
151− // runs this map block on IO, but each passwordFor() call still pays the
152− // suspend + redispatch overhead.
153− val pwPrefs = prefsForPasswords()
154− stored.map { it.toProfile(pwPrefs) }
155− }
156− // The .map above runs in the *collector's* context, and every consumer collects on
157− // viewModelScope (Main). Without this, kotlinx JSON decode + EncryptedSharedPreferences
158− // AES decryption would run on the UI thread on each emission. flowOn moves that work to IO.
159− ?.flowOn(Dispatchers.IO)
160− ?: kotlinx.coroutines.flow.flowOf(emptyList())
161−
162− private fun StoredProfile.toProfile(pwPrefs: SharedPreferences): ServerProfile {
163− val pw = username?.let { pwPrefs.getString(passwordKey(id), null) }
164− return ServerProfile(
165− id = id,
166− label = label,
167− baseUrl = baseUrl,
168− username = username,
169− password = pw,
170− lastUsed = lastUsed,
171− requireHttps = requireHttps,
172− certPin = certPin,
173− )
174− }
175−
176− open suspend fun resolve(profile: ServerProfile): ServerProfile {
177− val pw = if (profile.hasAuth) {
178− withContext(Dispatchers.IO) { prefsForPasswords().getString(passwordKey(profile.id), null) }
179− } else {
180− null
181− }
182− return profile.copy(password = pw)
183− }
184−
185− open suspend fun save(profile: ServerProfile) {
186− // Write the password first so that if the DataStore write fails, we're left
187− // with an orphaned password (harmless, cleaned up on next save/delete) rather
188− // than a profile with no password (which would break authentication).
189− withContext(Dispatchers.IO) {
190− prefsForPasswords().edit().apply {
191− val pw = profile.password
192− if (!profile.username.isNullOrBlank() && !pw.isNullOrEmpty()) {
193− putString(passwordKey(profile.id), pw)
194− } else {
195− remove(passwordKey(profile.id))
196− }
197− }.apply()
198− }
199− appContext!!.dataStore.edit { prefs ->
200− val current = prefs[profilesKey]?.let {
201− runCatching { OpencodeJson.decodeFromString(ListSerializer(StoredProfile.serializer()), it) }
202− .getOrDefault(emptyList())
203− } ?: emptyList()
204− // If the incoming profile has lastUsed=0 (e.g. ServerEditViewModel.save()
205− // couldn't read the existing value due to a DataStore timeout), preserve
206− // the existing nonzero lastUsed so saving an edit doesn't reset the
207− // profile's sort position in the server list.
208− val preservedLastUsed = if (profile.lastUsed == 0L) {
209− current.firstOrNull { it.id == profile.id }?.lastUsed ?: 0L
210− } else {
211− profile.lastUsed
212− }
213− val stored = StoredProfile(
214− id = profile.id,
215− label = profile.label,
216− baseUrl = profile.baseUrl,
217− username = profile.username?.takeIf { it.isNotBlank() },
218− lastUsed = preservedLastUsed,
219− requireHttps = profile.requireHttps,
220− certPin = profile.certPin?.takeIf { it.isNotBlank() },
221− )
222− val updated = current.filterNot { it.id == profile.id } + stored
223− prefs[profilesKey] = OpencodeJson.encodeToString(ListSerializer(StoredProfile.serializer()), updated)
224− }
225− }
226−
227− open suspend fun delete(id: String) {
228− // Delete the profile from DataStore first, then the password. If the process
229− // dies between the two, an orphaned password remains (harmless, cleaned up on
230− // next save/delete) rather than a profile with no password.
231− appContext!!.dataStore.edit { prefs ->
232− val current = prefs[profilesKey]?.let {
233− runCatching { OpencodeJson.decodeFromString(ListSerializer(StoredProfile.serializer()), it) }
234− .getOrDefault(emptyList())
235− } ?: emptyList()
236− prefs[profilesKey] = OpencodeJson.encodeToString(
237− ListSerializer(StoredProfile.serializer()),
238− current.filterNot { it.id == id },
239− )
240− }
241− // Clean up the password in both secure and fallback prefs so no orphaned
242− // plaintext password lingers if secure prefs were temporarily unavailable.
243− withContext(Dispatchers.IO) {
244− val key = passwordKey(id)
245− securePrefs?.edit()?.remove(key)?.apply()
246− fallbackPrefs.edit().remove(key).apply()
247− }
248− }
249−
250− private fun passwordKey(id: String) = "pw_$id"
251−}
app/src/main/java/soy/iko/opencode/data/repo/RecentModelsStore.ktdeleted−80
@@ -1,80 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.flow.MutableStateFlow
5−import kotlinx.coroutines.flow.StateFlow
6−import kotlinx.coroutines.flow.asStateFlow
7−
8−/**
9− * Persists the most recently picked models so the model picker can surface them as a
10− * "Recent" section above the full catalog. Backed by SharedPreferences because the UI
11− * needs the initial value synchronously and the list is tiny (≤ [MAX_ENTRIES]), mirroring
12− * the low-stakes-persistence rationale of [SearchHistoryStore]. `open` with a `protected`
13− * no-arg constructor so tests can subclass and override without a real Context.
14− *
15− * Entries are stored as `providerID\modelID` composite keys (the separator is chosen so it
16− * can't collide with provider or model ids, which are URL/path-safe identifiers).
17− */
18−open class RecentModelsStore private constructor(
19− private val appContext: Context?,
20− @Suppress("unused") private val testMode: Boolean,
21−) {
22− constructor(context: Context) : this(context.applicationContext, false)
23− protected constructor() : this(null, true)
24−
25− private val prefs by lazy {
26− appContext?.getSharedPreferences("recent_models", Context.MODE_PRIVATE)
27− ?: error("No context — override methods in test subclass")
28− }
29−
30− private val _entries = MutableStateFlow<List<String>>(emptyList())
31− open val entries: StateFlow<List<String>> = _entries.asStateFlow()
32−
33− init {
34− if (appContext != null) {
35− _entries.value = runCatching {
36− prefs.getString(KEY, null)
37− ?.takeIf { it.isNotBlank() }
38− ?.split(SEPARATOR)
39− ?.filter { it.isNotBlank() }
40− ?.take(MAX_ENTRIES)
41− }.getOrDefault(emptyList()) ?: emptyList()
42− }
43− }
44−
45− /** Insert [providerId]/[modelId] at the head of the recents, deduped and capped at
46− * [MAX_ENTRIES]. Blank ids are ignored. */
47− open fun add(providerId: String, modelId: String) {
48− val p = providerId.trim()
49− val m = modelId.trim()
50− if (p.isBlank() || m.isBlank()) return
51− val key = "$p$SEPARATOR$m"
52− val updated = (listOf(key) + _entries.value.filter { it != key }).take(MAX_ENTRIES)
53− _entries.value = updated
54− runCatching {
55− prefs.edit().putString(KEY, updated.joinToString(SEPARATOR)).apply()
56− }
57− }
58−
59− /** Split a stored composite key back into its provider/model id pair. Returns null if
60− * the entry is malformed (shouldn't happen, but a corrupt prefs value must never crash
61− * the picker). */
62− fun split(entry: String): Pair<String, String>? {
63− val parts = entry.split(SEPARATOR)
64− return if (parts.size == 2 && parts[0].isNotBlank() && parts[1].isNotBlank())
65− parts[0] to parts[1] else null
66− }
67−
68− open fun clear() {
69− _entries.value = emptyList()
70− runCatching { prefs.edit().remove(KEY).apply() }
71− }
72−
73− private companion object {
74− const val KEY = "models"
75− // A newline can't appear in a provider/model id (they're URL/path-safe), so it's a
76− // safe list separator that won't collide with id contents.
77− const val SEPARATOR = "\n"
78− const val MAX_ENTRIES = 5
79− }
80−}
app/src/main/java/soy/iko/opencode/data/repo/RecentSessionsStore.ktdeleted−64
@@ -1,64 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.Dispatchers
5−import kotlinx.coroutines.sync.Mutex
6−import kotlinx.coroutines.sync.withLock
7−import kotlinx.coroutines.withContext
8−import kotlinx.serialization.Serializable
9−import kotlinx.serialization.decodeFromString
10−import kotlinx.serialization.encodeToString
11−import kotlinx.serialization.json.Json
12−import java.io.File
13−
14−/** A minimal session summary persisted for the home-screen widget and launcher shortcuts. */
15−@Serializable
16−data class RecentSession(val id: String, val title: String)
17−
18−/**
19− * Persists a short list of recent sessions to a small JSON file under filesDir so app-external
20− * surfaces (the home-screen widget's [android.widget.RemoteViewsService] and the "Resume last"
21− * launcher shortcut) can read them without a live connection or in-memory state. Both the app
22− * and the widget's RemoteViews factory run in the same process, so a plain file is sufficient.
23− */
24−object RecentSessionsStore {
25−
26− private const val FILE = "recent_sessions.json"
27− const val MAX = 8
28−
29− private val json = Json { ignoreUnknownKeys = true }
30−
31− /** Serializes concurrent [write]s. The synchronous [read] (called from the widget's
32− * RemoteViewsService) can't take a suspend lock, so [write] instead swaps the file in
33− * atomically via a temp-file rename — the reader always sees either the old or the new
34− * complete file, never a half-written one. */
35− private val writeMutex = Mutex()
36−
37− private fun file(context: Context) = File(context.applicationContext.filesDir, FILE)
38−
39− /** Synchronous read — safe to call from the widget factory (bounded, tiny file). */
40− fun read(context: Context): List<RecentSession> {
41− val f = file(context).takeIf { it.exists() } ?: return emptyList()
42− return runCatching { json.decodeFromString<List<RecentSession>>(f.readText()) }
43− .getOrDefault(emptyList())
44− }
45−
46− /** Persist [sessions] (capped to [MAX]); a no-op empty list writes an empty file. */
47− suspend fun write(context: Context, sessions: List<RecentSession>) = withContext(Dispatchers.IO) {
48− writeMutex.withLock {
49− runCatching {
50− val target = file(context)
51− val encoded = json.encodeToString(sessions.take(MAX))
52− val tmp = File(target.parentFile, "$FILE.tmp")
53− tmp.writeText(encoded)
54− // Atomic replace on POSIX filesystems (app's internal storage); the reader
55− // never observes a torn file. Fall back to a direct write if rename fails.
56− if (!tmp.renameTo(target)) {
57− target.writeText(encoded)
58− tmp.delete()
59− }
60− }
61− Unit
62− }
63− }
64−}
app/src/main/java/soy/iko/opencode/data/repo/SearchHistoryStore.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import kotlinx.coroutines.flow.MutableStateFlow
5−import kotlinx.coroutines.flow.StateFlow
6−import kotlinx.coroutines.flow.asStateFlow
7−import soy.iko.opencode.data.network.NetworkConfig
8−
9−/**
10− * Persists the most recent unique global-search queries so the search screen can
11− * surface them as suggestions. Backed by SharedPreferences because the UI needs the
12− * initial value synchronously and the list is tiny (≤ [MAX_ENTRIES]), mirroring the
13− * low-stakes-persistence rationale of [DraftStore]. `open` with a `protected`
14− * no-arg constructor so tests can subclass and override without a real Context.
15− */
16−open class SearchHistoryStore private constructor(
17− private val appContext: Context?,
18− @Suppress("unused") private val testMode: Boolean,
19−) {
20− constructor(context: Context) : this(context.applicationContext, false)
21− protected constructor() : this(null, true)
22−
23− private val prefs by lazy {
24− appContext?.getSharedPreferences("search_history", Context.MODE_PRIVATE)
25− ?: error("No context — override methods in test subclass")
26− }
27−
28− private val _queries = MutableStateFlow<List<String>>(emptyList())
29− open val queries: StateFlow<List<String>> = _queries.asStateFlow()
30−
31− init {
32− if (appContext != null) {
33− _queries.value = runCatching {
34− prefs.getString(KEY, null)
35− ?.takeIf { it.isNotBlank() }
36− ?.split(SEPARATOR)
37− ?.filter { it.isNotBlank() }
38− ?.take(MAX_ENTRIES)
39− }.getOrDefault(emptyList()) ?: emptyList()
40− }
41− }
42−
43− /** Insert [query] at the head of the history, deduped and capped at [MAX_ENTRIES].
44− * Blank or sub-min-length queries are ignored so accidental empties and stray
45− * keystrokes don't pollute the suggestions. */
46− open fun add(query: String) {
47− val trimmed = query.trim()
48− if (trimmed.isBlank() || trimmed.length < NetworkConfig.minSearchQueryLength) return
49− val updated = (listOf(trimmed) + _queries.value.filter { it != trimmed }).take(MAX_ENTRIES)
50− _queries.value = updated
51− runCatching {
52− prefs.edit().putString(KEY, updated.joinToString(SEPARATOR)).apply()
53− }
54− }
55−
56− open fun clear() {
57− _queries.value = emptyList()
58− runCatching { prefs.edit().remove(KEY).apply() }
59− }
60−
61− private companion object {
62− const val KEY = "queries"
63− // The search field is single-line, so a newline can't appear in a stored query
64− // and is safe to use as the list separator.
65− const val SEPARATOR = "\n"
66− const val MAX_ENTRIES = 10
67− }
68−}
app/src/main/java/soy/iko/opencode/data/repo/SessionPrefsStore.ktdeleted−73
@@ -1,73 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import androidx.datastore.preferences.core.edit
5−import androidx.datastore.preferences.core.stringSetPreferencesKey
6−import androidx.datastore.preferences.preferencesDataStore
7−import kotlinx.coroutines.flow.Flow
8−import kotlinx.coroutines.flow.flowOf
9−import kotlinx.coroutines.flow.map
10−
11−private val Context.sessionPrefsDataStore by preferencesDataStore(name = "session_prefs")
12−
13−/**
14− * Local, per-session organization flags the opencode server doesn't track: **pinned**
15− * (sorted to the top of the session list) and **archived** (hidden from the list unless the
16− * user opts to show them). Keyed by opencode session id.
17− *
18− * `open` with a `protected` no-arg constructor so tests can subclass and override the flows
19− * without a real DataStore (mirrors the other stores). The flow accessors are getters (not
20− * eager initializers) and null-guard the context so the test constructor never touches disk.
21− */
22−open class SessionPrefsStore private constructor(
23− private val appContext: Context?,
24− @Suppress("unused") private val testMode: Boolean,
25−) {
26− constructor(context: Context) : this(context.applicationContext, false)
27− protected constructor() : this(null, true)
28−
29− private val pinnedKey = stringSetPreferencesKey("pinned")
30− private val archivedKey = stringSetPreferencesKey("archived")
31− private val mutedKey = stringSetPreferencesKey("muted")
32−
33− open val pinned: Flow<Set<String>>
34− get() = appContext?.sessionPrefsDataStore?.data?.map { it[pinnedKey] ?: emptySet() }
35− ?: flowOf(emptySet())
36−
37− open val archived: Flow<Set<String>>
38− get() = appContext?.sessionPrefsDataStore?.data?.map { it[archivedKey] ?: emptySet() }
39− ?: flowOf(emptySet())
40−
41− /** Session ids the user has muted (suppress unread badge + completion notification). */
42− open val muted: Flow<Set<String>>
43− get() = appContext?.sessionPrefsDataStore?.data?.map { it[mutedKey] ?: emptySet() }
44− ?: flowOf(emptySet())
45−
46− open suspend fun setPinned(sessionId: String, pinned: Boolean) = toggle(pinnedKey, sessionId, pinned)
47−
48− open suspend fun setArchived(sessionId: String, archived: Boolean) = toggle(archivedKey, sessionId, archived)
49−
50− open suspend fun setMuted(sessionId: String, muted: Boolean) = toggle(mutedKey, sessionId, muted)
51−
52− /** Drop a session from all sets — call on deletion so ids don't accumulate forever. */
53− open suspend fun forget(sessionId: String) {
54− val ctx = appContext ?: return
55− ctx.sessionPrefsDataStore.edit { prefs ->
56− prefs[pinnedKey] = (prefs[pinnedKey] ?: emptySet()) - sessionId
57− prefs[archivedKey] = (prefs[archivedKey] ?: emptySet()) - sessionId
58− prefs[mutedKey] = (prefs[mutedKey] ?: emptySet()) - sessionId
59− }
60− }
61−
62− private suspend fun toggle(
63− key: androidx.datastore.preferences.core.Preferences.Key<Set<String>>,
64− sessionId: String,
65− on: Boolean,
66− ) {
67− val ctx = appContext ?: return
68− ctx.sessionPrefsDataStore.edit { prefs ->
69− val current = prefs[key] ?: emptySet()
70− prefs[key] = if (on) current + sessionId else current - sessionId
71− }
72− }
73−}
app/src/main/java/soy/iko/opencode/data/repo/SessionRepository.ktdeleted−647
@@ -1,647 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import soy.iko.opencode.data.model.AssistantMessage
4−import soy.iko.opencode.data.model.BusEvent
5−import soy.iko.opencode.data.model.FilePromptPart
6−import soy.iko.opencode.data.model.MessageInfo
7−import soy.iko.opencode.data.model.MessagePartRemoved
8−import soy.iko.opencode.data.model.MessagePartUpdated
9−import soy.iko.opencode.data.model.MessageRemoved
10−import soy.iko.opencode.data.model.MessageUpdated
11−import soy.iko.opencode.data.model.MessageWithParts
12−import soy.iko.opencode.data.model.ModelRef
13−import soy.iko.opencode.data.model.Part
14−import soy.iko.opencode.data.model.SessionError
15−import soy.iko.opencode.data.model.SessionIdle
16−import soy.iko.opencode.data.model.UnknownMessage
17−import soy.iko.opencode.data.network.EventStreamClient
18−import soy.iko.opencode.data.network.NetworkConfig
19−import soy.iko.opencode.data.network.OpencodeApiClient
20−import soy.iko.opencode.util.runCatchingCancellable
21−import soy.iko.opencode.util.safeExceptionSummary
22−import android.util.Log
23−import kotlinx.coroutines.CoroutineScope
24−import kotlinx.coroutines.Dispatchers
25−import kotlinx.coroutines.Job
26−import kotlinx.coroutines.NonCancellable
27−import kotlinx.coroutines.delay
28−import kotlinx.coroutines.withContext
29−import kotlinx.coroutines.channels.Channel
30−import kotlinx.coroutines.flow.Flow
31−import kotlinx.coroutines.flow.channelFlow
32−import kotlinx.coroutines.flow.consumeAsFlow
33−import kotlinx.coroutines.flow.conflate
34−import kotlinx.coroutines.flow.flowOn
35−import kotlinx.coroutines.launch
36−import kotlinx.coroutines.sync.Mutex
37−import kotlinx.coroutines.sync.withLock
38−
39−/**
40− * Source of truth for a session's conversation. It seeds from `GET /session/:id/message`
41− * and then reduces [BusEvent]s from the SSE stream into an ordered list of messages,
42− * each keyed by message id with parts keyed by part id (idempotent upserts).
43− */
44−open class SessionRepository(
45− private val api: OpencodeApiClient,
46− private val eventStream: EventStreamClient,
47− // Optional on-disk cache so a conversation renders instantly on open and stays readable
48− // offline. Null in tests (and any path that doesn't wire it), where caching is skipped.
49− private val messageCache: MessageCacheStore? = null,
50− // Profile the cache is namespaced under, so two servers with a colliding session id don't
51− // share a cache file. Empty in tests / when no cache is wired.
52− private val profileId: String = "",
53−) {
54− open suspend fun listSessions() = api.listSessions()
55− open suspend fun createSession(title: String? = null, directory: String? = null) =
56− api.createSession(title, directory)
57− open suspend fun deleteSession(id: String) = api.deleteSession(id)
58− open suspend fun abort(sessionId: String) = api.abort(sessionId)
59−
60− open suspend fun sendPrompt(
61− sessionId: String,
62− text: String,
63− attachments: List<FilePromptPart> = emptyList(),
64− model: ModelRef?,
65− agent: String? = null,
66− // Stable key for retriable/re-sendable messages (the offline outbox). See
67− // [OpencodeApiClient.sendPrompt]. Null generates a fresh key per call.
68− idempotencyKey: String? = null,
69− ) = api.sendPrompt(sessionId, text, attachments, model, agent, idempotencyKey)
70−
71− open suspend fun runCommand(
72− sessionId: String,
73− command: String,
74− arguments: String = "",
75− agent: String? = null,
76− ) = api.runCommand(sessionId, command, arguments = arguments, agent = agent)
77−
78− /**
79− * A live, ordered view of [sessionId]'s messages. Begins collecting the event
80− * stream before the initial REST load so no streamed part is missed, then reduces
81− * events into the in-memory state. The flow is conflated so a fast burst of
82− * streaming tokens (each publishing a fresh snapshot) never back-pressures the
83− * event reducer — a slow collector simply sees the most recent snapshot.
84− */
85− /** Per-subscription helper that persists reduced snapshots to [messageCache], throttled so a
86− * fast token stream doesn't hammer the disk, plus a NonCancellable teardown flush. Extracted
87− * from [observeMessages] so this cache-write branching lives in its own methods. [scope] is
88− * the channelFlow scope, so scheduled saves are torn down with the flow — the teardown flush
89− * re-persists a trailing write the cancellation dropped. */
90− private inner class CacheWriter(private val scope: CoroutineScope, private val sessionId: String) {
91− private var lastWrite = 0L
92− private var pending: Job? = null
93− // Most recent snapshot handed to [schedule], and the most recent one whose on-disk write
94− // completed. `saved` is assigned from inside the launched save *after* it returns, so a
95− // save cancelled mid-IO by teardown is NOT marked saved and [flushOnTeardown] re-persists
96− // it. Written from the save coroutines, read from the collector/teardown; the only race is
97− // a stale read causing one redundant, idempotent re-save (atomic temp+rename makes a
98− // duplicate write of identical data harmless) — never data loss.
99− private var latest: List<MessageWithParts>? = null
100− private var saved: List<MessageWithParts>? = null
101−
102− fun schedule(snapshot: List<MessageWithParts>) {
103− val cache = messageCache ?: return
104− if (snapshot.isEmpty()) return
105− latest = snapshot
106− val now = System.currentTimeMillis()
107− pending?.cancel()
108− // Immediate write once the throttle window has elapsed; otherwise a trailing-edge
109− // write so a burst that ends inside the window (a run's final tokens right after a
110− // write) still persists its last snapshot. A newer snapshot cancels and replaces a
111− // pending trailing write, so continuous streaming coalesces to one write per window.
112− val delayMs = if (now - lastWrite >= NetworkConfig.messageCacheWriteThrottleMs) {
113− lastWrite = now
114− 0L
115− } else {
116− NetworkConfig.messageCacheWriteThrottleMs
117− }
118− pending = scope.launch {
119− if (delayMs > 0) delay(delayMs)
120− cache.save(profileId, sessionId, snapshot)
121− saved = snapshot
122− }
123− }
124−
125− suspend fun flushOnTeardown() {
126− // Scheduled saves are children of [scope], so teardown cancels a pending trailing
127− // write before its delay elapses — a run's final tokens would never reach disk. Flush
128− // the latest un-saved snapshot under NonCancellable so it survives the cancellation.
129− val cache = messageCache ?: return
130− val pendingSnapshot = latest ?: return
131− if (pendingSnapshot !== saved) {
132− withContext(NonCancellable) { cache.save(profileId, sessionId, pendingSnapshot) }
133− }
134− }
135− }
136−
137− open fun observeMessages(sessionId: String): Flow<List<MessageWithParts>> = channelFlow {
138− val store = MessageStore()
139− val lock = Mutex()
140− // Conflated dirty signal: a burst of reduce()/seed() calls coalesces into a
141− // single snapshot+send per demand cycle. Previously every changed event called
142− // snapshot() — allocating an O(N) copy of the whole message list — and ~97% of
143− // those copies were immediately discarded by the outer .conflate() during fast
144− // streaming (hundreds of tokens/sec). Marking dirty and snapshotting in one
145− // drain loop means N events in a burst allocate ~1 snapshot, not N.
146− val dirty = Channel<Unit>(Channel.CONFLATED)
147−
148− // Mark the store dirty; the drain loop below snapshots and publishes. CONFLATED
149− // collapses repeated marks into a single pending signal, so a tight burst of
150− // events doesn't even allocate N marks.
151− fun publish() { dirty.trySend(Unit) }
152−
153− // Subscribe to events first so we don't miss early deltas during the initial load.
154− launch {
155− eventStream.events.collect { event ->
156− if (lock.withLock { store.reduce(sessionId, event) }) publish()
157− }
158− }
159−
160− // Seed generation counter, shared between the initial load and the reconnect
161− // re-seed. Guards against a stale fetch (from an earlier reconnect, or from a slow
162− // initial load) clobbering a newer seed. Only mutated/read under [lock].
163− var seedGeneration = 0
164−
165− // Message ids introduced by the on-disk cache seed below. The initial REST seed uses
166− // these to prune ghosts: a cache-seeded message absent from the authoritative REST
167− // snapshot was deleted server-side while the app was closed. Restricting the prune to
168− // cache-seeded ids means live SSE messages added since subscribe (not yet indexed by
169− // REST) are never dropped. Written/read only in this collector coroutine.
170− var cacheSeededIds: Set<String> = emptySet()
171−
172− // Seed from the on-disk cache first so the conversation renders instantly — and stays
173− // readable offline — before the network responds. Guarded on generation 0 so a
174− // reconnect re-seed that somehow raced ahead isn't clobbered; the initial REST seed
175− // (also generation 0) then overrides this with authoritative data when it succeeds.
176− messageCache?.let { cache ->
177− val cached = cache.load(profileId, sessionId)
178− if (cached.isNotEmpty()) {
179− val changed = lock.withLock {
180− if (seedGeneration == 0) {
181− cacheSeededIds = cached.mapTo(mutableSetOf()) { it.info.id }
182− store.seed(cached, clearPivot = false)
183− } else false
184− }
185− if (changed) publish()
186− }
187− }
188−
189− // Re-seed from REST when the SSE stream reconnects after a drop. The REST fetch
190− // is performed *outside* the lock so events arriving via SSE during the fetch are
191− // not blocked. The seed itself is under the lock; a seed generation counter ensures
192− // a stale fetch (from an earlier reconnect) doesn't clobber a newer one.
193− launch {
194− // Re-seed from REST when the SSE stream reconnects after a drop. The
195− // hasConnectedBefore flag is NOT reset on disconnect — it stays true after
196− // the first successful connection so a subsequent reconnect triggers the
197− // re-seed. Resetting it on disconnect would make the condition always false
198− // after the first cycle, turning the re-seed into dead code.
199− //
200− // A seed generation counter guards against a stale re-seed clobbering a
201− // newer one: if two reconnects fire in quick succession, the older fetch
202− // (which returns later) is discarded because its generation no longer matches.
203− var hasConnectedBefore = false
204− eventStream.state.collect { state ->
205− if (state == EventStreamClient.ConnectionState.Connected) {
206− if (hasConnectedBefore) {
207− // Pivot before the fetch: parts already in memory predate this
208− // snapshot and must yield to it, while parts that stream in during
209− // the fetch (added to streamedSincePivot via reduce) outrank it.
210− // Bump the generation under the same lock so the compare in the
211− // initial seed sees a consistent value.
212− val generation = lock.withLock {
213− store.beginReseed()
214− ++seedGeneration
215− }
216− val fresh = runCatchingCancellable { api.listMessages(sessionId) }
217− .onFailure { Log.w("SessionRepository", "Re-seed message load failed for $sessionId; relying on SSE: ${safeExceptionSummary(it)}") }
218− .getOrDefault(emptyList())
219− var seedChanged = false
220− lock.withLock {
221− if (generation == seedGeneration) {
222− // Merge without pruning: SSE events arriving during the
223− // REST fetch may have added messages not yet indexed by
224− // the REST endpoint. Pruning would silently delete them.
225− // Stale messages from deletions during the disconnect
226− // gap are eventually removed via MessageRemoved events
227− // or on the next app restart.
228− seedChanged = store.seed(fresh, prune = false)
229− }
230− }
231− if (seedChanged) publish()
232− }
233− hasConnectedBefore = true
234− }
235− }
236− }
237−
238− // Load the authoritative message list concurrently with the drain loop below so the
239− // cache seed and any early SSE-reduced parts are emitted immediately. Running it inline
240− // here (before the drain starts) would withhold the already-reduced cached conversation
241− // until this fetch resolved — a blank screen for the whole withRetry backoff when offline.
242− launch {
243− val initialResult = runCatchingCancellable { api.listMessages(sessionId) }
244− .onFailure { Log.w("SessionRepository", "Initial message load failed for $sessionId; relying on cache/SSE: ${safeExceptionSummary(it)}") }
245− // Apply the initial seed only if no reconnect re-seed has run yet (generation still 0).
246− // A re-seed is always a fresher full snapshot, so if the (possibly slow) initial fetch
247− // returns after one has applied, seeding this older REST data would clobber the newer
248− // state — reverting a completed run to "running", regressing cost/token/part state —
249− // until the next SSE event or reconnect healed it. Only seed on SUCCESS: on failure
250− // (e.g. offline) keep whatever's shown (the cache seed above) rather than clearing it.
251− val seeded = lock.withLock {
252− val list = initialResult.getOrNull()
253− if (seedGeneration == 0 && list != null) {
254− // Prune ghosts first: cache-seeded messages absent from this authoritative
255− // REST snapshot were deleted server-side while the app was closed. Without
256− // this they'd survive restart forever (re-seeded from cache, never pruned by
257− // the reconnect path, and re-persisted by the drain loop).
258− val pruned = store.pruneStaleCacheSeeded(cacheSeededIds, list)
259− val changed = store.seed(list)
260− pruned || changed
261− } else false
262− }
263− if (seeded) publish()
264− }
265−
266− // Single drain: one snapshot+send per conflated dirty signal. The snapshot is
267− // taken under the lock so a reader never sees a half-reduced state; send() runs
268− // outside the lock so a slow downstream collector can't stall the drain. This
269− // loop also keeps the flow alive until the collector cancels; the launched jobs
270− // above are children of this scope and are torn down with it.
271− // Per-subscription cache writer: throttled snapshot persistence + a NonCancellable
272− // teardown flush. `this` is the channelFlow scope, so its scheduled saves are torn down
273− // with the flow (the teardown flush re-persists a cancelled trailing write).
274− val cacheWriter = CacheWriter(this, sessionId)
275− // Guarantee at least one emission even when nothing seeds the store: with no on-disk
276− // cache, a failing initial REST load (swallowed above), and a quiet SSE stream, none of
277− // the seed paths publish, so the flow would emit nothing at all. The sole collector
278− // (ChatViewModel) only clears its loading spinner on an emission, so without this a
279− // first-open of an erroring/empty session spins forever with no way to reach the
280− // "Failed to load / Retry" affordance. CONFLATED dirty coalesces this with any seed
281− // publish into a single send.
282− publish()
283− try {
284− dirty.consumeAsFlow().collect {
285− val snapshot = lock.withLock { store.snapshot() }
286− send(snapshot)
287− // Persist to the on-disk cache, throttled so a fast token stream doesn't hammer
288− // the disk — the cache only needs to be "recent enough" for an instant/offline
289− // first paint; the network corrects it on the next open.
290− cacheWriter.schedule(snapshot)
291− }
292− } finally {
293− cacheWriter.flushOnTeardown()
294− }
295− // Run the whole reducer pipeline — event reduction, list rebuilds, and the O(N)
296− // snapshot copy — on Dispatchers.Default rather than the collector's context. The
297− // sole consumer collects via stateIn(viewModelScope), i.e. Main.immediate, so without
298− // this every streamed token's reduce()/snapshot() would execute on the UI thread
299− // (hundreds/sec on a fast run). The seed REST calls here only suspend, so moving them
300− // off Main is harmless. JSON decoding already runs off-Main upstream in EventStreamClient.
301− }.flowOn(Dispatchers.Default).conflate()
302−
303− companion object {
304− /** Convenience: is this event a run-completion signal for [sessionId]?
305− * A null sessionID is NOT treated as a wildcard — an idle event with no
306− * session id must not reset the running state of every open chat. */
307− fun isIdle(event: BusEvent, sessionId: String): Boolean =
308− event is SessionIdle && event.properties.sessionID == sessionId
309−
310− fun isError(event: BusEvent, sessionId: String): Boolean =
311− event is SessionError && event.properties.sessionID == sessionId
312−
313− /** Does this event indicate an in-progress run for [sessionId]? A live streamed part or
314− * an assistant message that isn't yet complete/errored means the agent is still working.
315− * Used to restore the "running" indicator after an SSE reconnect: if the run is still
316− * going, such live events keep arriving; a run that finished during the outage produces
317− * none (its completion arrives via the REST re-seed, not the event stream). */
318− fun isRunActivity(event: BusEvent, sessionId: String): Boolean = when (event) {
319− // The session id rides on the part for message.part.updated; properties.sessionID
320− // is null on the wire. Mirror reduce()'s `part.sessionID ?: properties.sessionID`
321− // so a run that's only streaming parts still re-lights the indicator on reconnect.
322− is MessagePartUpdated -> (event.properties.part.sessionID ?: event.properties.sessionID) == sessionId
323− is MessageUpdated -> {
324− val info = event.properties.info
325− info.sessionID == sessionId && info is AssistantMessage && !info.isComplete && info.error == null
326− }
327− else -> false
328− }
329− }
330−}
331−
332−/**
333− * In-memory reduction state for one observed session. Not thread-safe; guard with a Mutex.
334− * Exposed as `internal` so the reducer logic can be unit-tested directly.
335− */
336−internal class MessageStore {
337− // messageId -> mutable holder (info + insertion-ordered parts); the map itself is
338− // insertion-ordered.
339− private val messages = LinkedHashMap<String, Holder>()
340−
341− /**
342− * Mutable per-message holder. Parts live in an insertion-ordered map keyed by part id, so a
343− * streamed part update is an O(1) put instead of an O(P) list rebuild. The immutable
344− * [MessageWithParts] view is materialized lazily and cached until the next mutation — so a
345− * burst of streamed token updates rebuilds a message's part list at most once per published
346− * [snapshot], not once per token. The cached view is also reference-stable across snapshots
347− * while unchanged, so Compose skips recomposing bubbles that didn't change.
348− */
349− private class Holder(var info: MessageInfo, val parts: LinkedHashMap<String, Part>) {
350− private var cached: MessageWithParts? = null
351− fun view(): MessageWithParts =
352− cached ?: MessageWithParts(info, parts.values.toList()).also { cached = it }
353− /** Adopt an existing immutable instance as the cache — avoids an immediate rebuild and
354− * preserves its identity (e.g. when seeding an authoritative REST snapshot). */
355− fun adopt(m: MessageWithParts) { cached = m }
356− fun invalidate() { cached = null }
357− }
358−
359− /** Build a [Holder] from an immutable message, reusing [m] itself as the cached view. */
360− private fun holderOf(m: MessageWithParts): Holder {
361− val parts = LinkedHashMap<String, Part>(m.parts.size)
362− for (p in m.parts) parts[p.id] = p
363− return Holder(m.info, parts).also { it.adopt(m) }
364− }
365−
366− /** Part ids upserted via [reduce] since the last reseed pivot ([beginReseed]) or seed.
367− * On a reconnect re-seed these are the parts that streamed in *during* the REST fetch,
368− * so they're newer than the snapshot and must win over it; every other part is taken
369− * from the authoritative REST snapshot. Without this distinction the merge kept every
370− * overlapping in-memory part, so a part that changed server-side during the disconnect
371− * (e.g. a tool going running -> completed) stayed stale until app restart. */
372− private val streamedSincePivot = mutableSetOf<String>()
373−
374− /** Message ids whose `info` was updated via a live SSE [reduce] since the last reseed
375− * pivot ([beginReseed]) or seed. Parallels [streamedSincePivot] but for message info:
376− * on a reconnect re-seed these are the messages whose info changed *during* the REST
377− * fetch, so the in-memory info is newer than the snapshot and must win; every other
378− * message's info is taken from the authoritative REST snapshot. Without this the merge
379− * kept the in-memory info, so a run that finished server-side during the disconnect
380− * (e.g. cost/token totals, completion time) stayed stale until app restart. */
381− private val messageInfoUpdatedSincePivot = mutableSetOf<String>()
382−
383− /** Mark the point a reconnect re-seed's REST fetch begins: parts/info streamed from here
384− * on are newer than the fetched snapshot. Call under the same lock as [seed]/[reduce]. */
385− fun beginReseed() {
386− streamedSincePivot.clear()
387− messageInfoUpdatedSincePivot.clear()
388− }
389−
390− /** Maximum number of messages to keep in memory; oldest are evicted when exceeded. */
391− internal val maxMessages = NetworkConfig.maxInMemoryMessages
392−
393− fun snapshot(): List<MessageWithParts> = messages.values.map { it.view() }
394−
395− fun seed(initial: List<MessageWithParts>, prune: Boolean = false, clearPivot: Boolean = true): Boolean {
396− var changed = false
397− // On re-seed (after SSE reconnect), remove messages that are no longer in the
398− // server snapshot (e.g. deleted during the disconnection gap). This keeps the
399− // in-memory state in sync with the authoritative REST snapshot rather than
400− // accumulating stale messages forever. Skipped on the initial seed to avoid
401− // racing with just-arrived SSE events whose messages may not yet be in REST.
402− if (prune) {
403− val incomingIds = initial.mapTo(mutableSetOf()) { it.info.id }
404− val before = messages.size
405− messages.keys.retainAll(incomingIds)
406− if (messages.size != before) changed = true
407− }
408−
409− for (m in initial) {
410− val existing = messages[m.info.id]
411− if (existing == null) {
412− messages[m.info.id] = holderOf(m)
413− changed = true
414− } else {
415− // A part streamed in between subscribe and this initial load may already
416− // have populated this message (see observeMessages). Merge instead of
417− // overwriting so that newer streamed part isn't discarded: take the
418− // snapshot's part order, swap in the streamed version where ids overlap,
419− // append any streamed-only parts, and adopt the authoritative REST info.
420− // existing.parts is already keyed by part id (insertion-ordered).
421− val streamedById = existing.parts
422− val snapshotIds = m.parts.mapTo(mutableSetOf()) { it.id }
423− // Prefer the in-memory version of an overlapping part ONLY if it streamed
424− // in since the reseed pivot (i.e. during this fetch), so it's newer than
425− // the snapshot. Otherwise the REST snapshot is authoritative and wins,
426− // discarding an in-memory part that went stale during a disconnect.
427− val ordered = m.parts.map { p ->
428− if (p.id in streamedSincePivot) streamedById[p.id] ?: p else p
429− }.toMutableList()
430− // Append only parts that streamed in *since the pivot* and are absent from the
431− // snapshot — i.e. genuinely newer than this REST fetch. A part in memory from
432− // before the pivot that the snapshot omits was removed server-side (its
433− // MessagePartRemoved missed during a disconnect gap, or it was deleted while the
434− // app was closed and only survives from the cache seed); the authoritative REST
435− // snapshot must be allowed to drop it, else it reappears as a ghost — and, once
436− // the drain loop persists this merge, gets baked into the on-disk cache forever
437− // (the message still exists, so pruneStaleCacheSeeded never removes it). This
438− // mirrors the overlapping-part branch above and the info branch below, which both
439− // already gate on the pivot.
440− for (p in existing.parts.values) {
441− if (p.id !in snapshotIds && p.id in streamedSincePivot) ordered.add(p)
442− }
443− // Adopt the authoritative REST info unless the in-memory info was itself
444− // updated live since the pivot (i.e. during this fetch), in which case it's
445− // newer than the snapshot. Otherwise the REST snapshot wins, discarding
446− // in-memory info that went stale during a disconnect.
447− val info = if (existing.info is UnknownMessage || m.info.id !in messageInfoUpdatedSincePivot) m.info else existing.info
448− val merged = MessageWithParts(info = info, parts = ordered)
449− if (merged != existing.view()) {
450− messages[m.info.id] = holderOf(merged)
451− changed = true
452− }
453− }
454− }
455− // A part that streamed in *before* this initial load (observeMessages subscribes to
456− // SSE before fetching) inserts its message at the front of the insertion-ordered map,
457− // and the merge above keeps that position — pinning a running message above the older
458− // history that seed() inserts afterward. Restore chronological order by creation time
459− // FIRST, so eviction below drops the genuinely-oldest entries: evictOldMessages()
460− // removes from the map's front, which before reordering is the newest streamed message.
461− if (reorderByTime()) changed = true
462− if (evictOldMessages()) changed = true
463− // Reset the pivot: everything just merged is now the baseline, so only parts/info
464− // that stream in *after* this seed can outrank the next reconnect's snapshot. The
465− // on-disk cache seed passes clearPivot = false: it runs *before* the authoritative
466− // initial REST seed, so clearing here would strip pivot protection from SSE parts/info
467− // that streamed in since subscribe, letting that REST seed regress them.
468− if (clearPivot) {
469− streamedSincePivot.clear()
470− messageInfoUpdatedSincePivot.clear()
471− }
472− return changed
473− }
474−
475− /** Remove messages that were seeded from the on-disk cache ([cacheSeededIds]) but are
476− * absent from the authoritative REST snapshot [rest] — i.e. deleted server-side while the
477− * app was closed. Restricted to cache-seeded ids so a message added by a live SSE event
478− * since subscribe (which the REST endpoint may not have indexed yet) is never pruned.
479− * This is what actually removes ghosts on restart; the reconnect re-seed deliberately
480− * keeps prune=false to avoid racing just-arrived SSE. Call under the same lock as [seed].
481− * Returns true if anything was removed. */
482− fun pruneStaleCacheSeeded(cacheSeededIds: Set<String>, rest: List<MessageWithParts>): Boolean {
483− if (cacheSeededIds.isEmpty()) return false
484− val restIds = rest.mapTo(mutableSetOf()) { it.info.id }
485− var changed = false
486− for (id in cacheSeededIds) {
487− if (id !in restIds && messages.remove(id) != null) changed = true
488− }
489− return changed
490− }
491−
492− /** Reorder the message map by message creation time (stable). Ties and entries with no
493− * server time yet (e.g. a brand-new message still streaming and not in REST) keep their
494− * relative order, so such a message stays last. Preserves each entry's map key so the
495− * synthetic UnknownMessage keys aren't collapsed. Returns true if the order changed. */
496− private fun reorderByTime(): Boolean {
497− val entries = messages.entries.map { it.key to it.value }
498− val sorted = entries.sortedBy { it.second.info.time?.created ?: Long.MAX_VALUE }
499− // Detect a reordering by comparing keys positionally, instead of allocating two more
500− // N-sized key lists just to compare them.
501− var changed = false
502− for (i in sorted.indices) {
503− if (sorted[i].first != entries[i].first) { changed = true; break }
504− }
505− if (!changed) return false
506− messages.clear()
507− for ((k, v) in sorted) messages[k] = v
508− return true
509− }
510−
511− /** Returns true if the state changed (and a new snapshot should be published). */
512− fun reduce(sessionId: String, event: BusEvent): Boolean {
513− return when (event) {
514− is MessageUpdated -> handleMessageUpdated(sessionId, event)
515−
516− is MessagePartUpdated -> {
517− val part = event.properties.part
518− val messageId = part.messageID ?: event.properties.messageID
519− val partSession = part.sessionID ?: event.properties.sessionID
520− when {
521− messageId == null -> false
522− partSession != null -> if (partSession == sessionId) upsertPart(messageId, part) else false
523− // No session id anywhere on the event: a null session is NOT a wildcard
524− // (mirroring isIdle/isError). Every open session's store sees the shared
525− // event stream, so accepting it unconditionally would leak the part into
526− // unrelated conversations (e.g. both panes in two-pane mode). Attribute it
527− // only if this store already holds the parent message — MessageUpdated,
528− // which always carries a session id, will have created it here first.
529− else -> if (messages.containsKey(messageId)) upsertPart(messageId, part) else false
530− }
531− }
532−
533− is MessagePartRemoved -> handlePartRemoved(sessionId, event)
534−
535− is MessageRemoved -> handleMessageRemoved(sessionId, event)
536−
537− else -> false
538− }
539− }
540−
541− private fun handleMessageUpdated(sessionId: String, event: MessageUpdated): Boolean {
542− val info = event.properties.info
543− if (info.sessionID != sessionId) return false
544− // An UnknownMessage with an empty id (e.g. from an unrecognized server role with no id
545− // field) would collide with other such messages in the map. It carries no id, only
546− // sessionID/time, so derive a synthetic key. Prefer the immutable creation timestamp: it's
547− // stable across updates, so a later update to the SAME unknown message (whose `time.updated`
548− // or `time.completed` changes) coalesces onto its holder via the existing==info guard below
549− // instead of forking a duplicate — the failure mode a full-content hash has, since any
550− // content change moves the hash. Distinct unknown messages still separate by their distinct
551− // creation times; only when even `created` is absent do we fall back to the content hash.
552− val key = if (info.id.isEmpty() && info is UnknownMessage) {
553− info.time?.created?.let { "unknown-c$it" } ?: "unknown-h${info.hashCode()}"
554− } else {
555− info.id
556− }
557− val existing = messages[key]
558− // A server re-sending byte-identical info is a no-op: skip it so we don't publish a
559− // redundant snapshot (mirrors upsertPart's identical-part guard).
560− if (existing != null && existing.info == info) return false
561− if (existing == null) {
562− messages[key] = Holder(info, LinkedHashMap())
563− } else {
564− existing.info = info
565− existing.invalidate()
566− }
567− // Record that this message's info streamed in live, so a re-seed after a reconnect knows
568− // it's newer than the REST snapshot and keeps it (see seed()/beginReseed()).
569− messageInfoUpdatedSincePivot.add(key)
570− if (existing == null) evictOldMessages()
571− return true
572− }
573−
574− /** Returns false if [eventSession] is non-null and doesn't match [sessionId]. */
575− private fun matchesSession(eventSession: String?, sessionId: String): Boolean =
576− eventSession == null || eventSession == sessionId
577−
578− private fun handlePartRemoved(sessionId: String, event: MessagePartRemoved): Boolean {
579− val messageId = event.properties.messageID ?: return false
580− val partId = event.properties.partID ?: return false
581− if (!matchesSession(event.properties.sessionID, sessionId)) return false
582− return removePart(messageId, partId)
583− }
584−
585− private fun handleMessageRemoved(sessionId: String, event: MessageRemoved): Boolean {
586− val id = event.properties.messageID ?: return false
587− if (!matchesSession(event.properties.sessionID, sessionId)) return false
588− val removed = messages.remove(id) ?: return false
589− messageInfoUpdatedSincePivot.remove(id)
590− removed.parts.keys.forEach { streamedSincePivot.remove(it) }
591− return true
592− }
593−
594− private fun upsertPart(messageId: String, part: Part): Boolean {
595− val current = messages[messageId]
596− if (current != null) {
597− // O(1) map lookup + put, vs the former O(P) indexOfFirst scan and full-list copy
598− // on every streamed token. A LinkedHashMap re-put keeps the part's original
599− // position (replace-in-place); a new id is appended — matching the old list order.
600− if (current.parts[part.id] == part) return false
601− current.parts[part.id] = part
602− current.invalidate()
603− } else {
604− val parts = LinkedHashMap<String, Part>()
605− parts[part.id] = part
606− messages[messageId] = Holder(
607− info = UnknownMessage(id = messageId, sessionID = part.sessionID ?: ""),
608− parts = parts,
609− )
610− }
611− // Record that this part streamed in, so a re-seed after a reconnect knows it's
612− // newer than the REST snapshot and keeps it (see seed()/beginReseed()).
613− streamedSincePivot.add(part.id)
614− if (current == null) evictOldMessages()
615− return true
616− }
617−
618− private fun removePart(messageId: String, partId: String): Boolean {
619− val current = messages[messageId] ?: return false
620− if (current.parts.remove(partId) == null) return false
621− // Drop the pivot entry too so the set doesn't accumulate ids of removed parts for
622− // the rest of the session (it's otherwise only cleared on reseed/eviction). No
623− // correctness impact today — a stale entry just falls back to the REST snapshot's
624− // version in seed() — but keeping it symmetric with handleMessageRemoved/eviction
625− // bounds the set's growth over a long-lived session.
626− streamedSincePivot.remove(partId)
627− current.invalidate()
628− return true
629− }
630−
631− /** Evict the oldest messages when the store exceeds [maxMessages], keeping memory bounded.
632− * Returns true if any messages were evicted. */
633− private fun evictOldMessages(): Boolean {
634− var evicted = false
635− while (messages.size > maxMessages) {
636− val oldestKey = messages.keys.iterator().next()
637− val removed = messages.remove(oldestKey)
638− // Prune the evicted message's pivot bookkeeping so these sets don't grow
639− // unbounded over a long-running session that never reconnects (they're only
640− // otherwise cleared on reseed/seed).
641− messageInfoUpdatedSincePivot.remove(oldestKey)
642− removed?.parts?.keys?.forEach { streamedSincePivot.remove(it) }
643− evicted = true
644− }
645− return evicted
646− }
647−}
app/src/main/java/soy/iko/opencode/data/repo/SettingsStore.ktdeleted−279
@@ -1,279 +0,0 @@
1−package soy.iko.opencode.data.repo
2−
3−import android.content.Context
4−import androidx.datastore.preferences.core.booleanPreferencesKey
5−import androidx.datastore.preferences.core.edit
6−import androidx.datastore.preferences.core.floatPreferencesKey
7−import androidx.datastore.preferences.core.intPreferencesKey
8−import androidx.datastore.preferences.core.stringPreferencesKey
9−import androidx.datastore.preferences.preferencesDataStore
10−import kotlinx.coroutines.flow.Flow
11−import kotlinx.coroutines.flow.map
12−
13−enum class ThemeMode { SYSTEM, LIGHT, DARK, AMOLED }
14−
15−private val Context.settingsDataStore by preferencesDataStore(name = "settings")
16−
17−/** App-preferences store: theme mode, dynamic color (Material You), input behavior. */
18−@Suppress("TooManyFunctions")
19−class SettingsStore(context: Context) {
20−
21− private val appContext = context.applicationContext
22− private val themeKey = stringPreferencesKey("theme_mode")
23− private val dynamicColorKey = booleanPreferencesKey("dynamic_color")
24− private val sendOnEnterKey = booleanPreferencesKey("send_on_enter")
25− private val appLockKey = booleanPreferencesKey("app_lock")
26− private val appLockReLockSecondsKey = intPreferencesKey("app_lock_relock_seconds")
27− private val chatTextScaleKey = floatPreferencesKey("chat_text_scale")
28− private val codeWrapKey = booleanPreferencesKey("code_wrap")
29− private val sessionSortModeKey = stringPreferencesKey("session_sort_mode")
30− private val sessionSortDescendingKey = booleanPreferencesKey("session_sort_descending")
31− private val sessionShowArchivedKey = booleanPreferencesKey("session_show_archived")
32− private val preferredModelIdKey = stringPreferencesKey("preferred_model_id")
33− private val preferredAgentNameKey = stringPreferencesKey("preferred_agent_name")
34− private val compactMessageSpacingKey = booleanPreferencesKey("compact_message_spacing")
35− private val hapticsEnabledKey = booleanPreferencesKey("haptics_enabled")
36− private val reducedMotionKey = booleanPreferencesKey("reduced_motion")
37− private val languageOverrideKey = stringPreferencesKey("language_override")
38− private val notifRunCompleteKey = booleanPreferencesKey("notif_run_complete")
39− private val notifPermissionKey = booleanPreferencesKey("notif_permission")
40− private val notifErrorKey = booleanPreferencesKey("notif_error")
41− private val swipeLeftActionKey = stringPreferencesKey("swipe_left_action")
42− private val swipeRightActionKey = stringPreferencesKey("swipe_right_action")
43−
44− companion object {
45− /** Bounds for the chat text-size multiplier so the UI can't be scaled into
46− * unreadability or an unusable micro-font. 1.0 is the design default. */
47− const val MIN_CHAT_TEXT_SCALE = 0.8f
48− const val MAX_CHAT_TEXT_SCALE = 1.6f
49− const val DEFAULT_CHAT_TEXT_SCALE = 1.0f
50− /** 0 means re-lock the instant the app backgrounds. Other entries are the grace
51− * period (seconds) during which a quick app-switch does NOT re-prompt for auth. */
52− val APP_LOCK_RELOCK_OPTIONS_SECONDS: List<Int> = listOf(0, 30, 60, 300, 1800, 3600)
53− const val DEFAULT_APP_LOCK_RELOCK_SECONDS = 0
54− }
55−
56− val themeMode: Flow<ThemeMode> = appContext.settingsDataStore.data.map { prefs ->
57− runCatching { ThemeMode.valueOf(prefs[themeKey] ?: ThemeMode.SYSTEM.name) }
58− .getOrDefault(ThemeMode.SYSTEM)
59− }
60−
61− // Default OFF so the app ships with its hand-built "Tokyo Night" brand palette rather than
62− // the wallpaper-derived Material You scheme, which fully replaces the brand colours. Users
63− // on Android 12+ can still opt into dynamic color from Settings.
64− val dynamicColor: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
65− prefs[dynamicColorKey] ?: false
66− }
67−
68− /** When true, the hardware Enter key sends the prompt; when false, Enter inserts a
69− * newline and Ctrl+Enter sends. Soft-keyboard IME action always sends. Defaults to
70− * true to match the prior hardcoded behavior. */
71− val sendOnEnter: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
72− prefs[sendOnEnterKey] ?: true
73− }
74−
75− /** When true, the app requires device biometric/credential authentication on launch
76− * (and when returning from the background) before the UI is shown, protecting the
77− * stored server credentials. Defaults to false so the app is usable out of the box. */
78− val appLock: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
79− prefs[appLockKey] ?: false
80− }
81−
82− /** Grace period (seconds) before re-locking after the app backgrounds. 0 = re-lock
83− * immediately (the prior behavior). Lets a quick app-switch not re-prompt, which is the
84− * standard reason users disable biometric locks in messaging/banking apps. */
85− val appLockReLockSeconds: Flow<Int> = appContext.settingsDataStore.data.map { prefs ->
86− prefs[appLockReLockSecondsKey] ?: DEFAULT_APP_LOCK_RELOCK_SECONDS
87− }
88−
89− /** Multiplier applied to chat message (markdown) and code text so users can size the
90− * conversation for readability independently of the system font scale. Clamped to
91− * [[MIN_CHAT_TEXT_SCALE], [MAX_CHAT_TEXT_SCALE]] on read so a corrupt/out-of-range
92− * stored value can never produce an unreadable UI. Defaults to 1.0 (design size). */
93− val chatTextScale: Flow<Float> = appContext.settingsDataStore.data.map { prefs ->
94− (prefs[chatTextScaleKey] ?: DEFAULT_CHAT_TEXT_SCALE)
95− .coerceIn(MIN_CHAT_TEXT_SCALE, MAX_CHAT_TEXT_SCALE)
96− }
97−
98− /** When true, fenced/indented code blocks soft-wrap long lines instead of scrolling
99− * horizontally. Defaults to false (horizontal scroll) to preserve code formatting. */
100− val codeWrap: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
101− prefs[codeWrapKey] ?: false
102− }
103−
104− /** Persisted session-list sort mode so a chosen ordering survives process death (not just
105− * rotation). Stored as the enum name; an unknown value falls back to RECENT. */
106− val sessionSortMode: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
107− prefs[sessionSortModeKey] ?: "RECENT"
108− }
109−
110− /** Persisted session-list sort direction. Defaults to descending (newest first). */
111− val sessionSortDescending: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
112− prefs[sessionSortDescendingKey] ?: true
113− }
114−
115− /** Persisted "show archived sessions" toggle so the choice survives process death. */
116− val sessionShowArchived: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
117− prefs[sessionShowArchivedKey] ?: false
118− }
119−
120− /** Preferred default model id for new sessions. Empty means "use the server default".
121− * A user who always picks a specific model doesn't have to pick it every session. */
122− val preferredModelId: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
123− prefs[preferredModelIdKey] ?: ""
124− }
125−
126− /** Preferred default agent name for new sessions. Empty means "use the server default". */
127− val preferredAgentName: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
128− prefs[preferredAgentNameKey] ?: ""
129− }
130−
131− /** When true, chat message bubbles use a tighter vertical spacing (8dp vs the default 16dp)
132− * so power users can fit more conversation on screen. Defaults to false (the design default). */
133− val compactMessageSpacing: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
134− prefs[compactMessageSpacingKey] ?: false
135− }
136−
137− /** When true, haptic feedback is fired on taps and confirmations. Defaults to true (the
138− * existing behavior). An in-app toggle lets users disable haptics without turning off
139− * system-wide vibration. Read by a CompositionLocal that gates haptic calls. */
140− val hapticsEnabled: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
141− prefs[hapticsEnabledKey] ?: true
142− }
143−
144− /** When true, animations and transitions are limited (collapsed to instant/snap).
145− * Defaults to false — the app already honors the system Developer Options animator
146− * scale, but this gives users an in-app toggle without disabling motion OS-wide.
147− * Read by a CompositionLocal that gates animation specs. */
148− val reducedMotion: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
149− prefs[reducedMotionKey] ?: false
150− }
151−
152− /** Override the app language (an ISO 639-1 code like "en" or "es", or empty for the
153− * system default). Applied via AppCompat's per-app language API so the OS can
154− * handle locale resolution without an app restart on Android 13+. */
155− val languageOverride: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
156− prefs[languageOverrideKey] ?: ""
157− }
158−
159− /** Granular notification toggles. Each gates a notification channel's posting so a user
160− * can mute specific notification types in-app (in addition to the OS channel controls).
161− * Default true for all (matching the prior "always post" behavior). */
162− val notifRunComplete: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
163− prefs[notifRunCompleteKey] ?: true
164− }
165− val notifPermission: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
166− prefs[notifPermissionKey] ?: true
167− }
168− val notifError: Flow<Boolean> = appContext.settingsDataStore.data.map { prefs ->
169− prefs[notifErrorKey] ?: true
170− }
171−
172− /** Remappable swipe actions for the session list. Stored as the SwipeAction enum name;
173− * an unknown value falls back to the default. Defaults: left=DELETE, right=ARCHIVE
174− * (matching the prior hardcoded behavior). */
175− val swipeLeftAction: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
176− prefs[swipeLeftActionKey] ?: SwipeAction.DELETE.name
177− }
178− val swipeRightAction: Flow<String> = appContext.settingsDataStore.data.map { prefs ->
179− prefs[swipeRightActionKey] ?: SwipeAction.ARCHIVE.name
180− }
181−
182− suspend fun setThemeMode(mode: ThemeMode) {
183− appContext.settingsDataStore.edit { it[themeKey] = mode.name }
184− }
185−
186− suspend fun setDynamicColor(enabled: Boolean) {
187− appContext.settingsDataStore.edit { it[dynamicColorKey] = enabled }
188− }
189−
190− suspend fun setSendOnEnter(enabled: Boolean) {
191− appContext.settingsDataStore.edit { it[sendOnEnterKey] = enabled }
192− }
193−
194− suspend fun setAppLock(enabled: Boolean) {
195− appContext.settingsDataStore.edit { it[appLockKey] = enabled }
196− }
197−
198− suspend fun setAppLockReLockSeconds(seconds: Int) {
199− appContext.settingsDataStore.edit {
200− it[appLockReLockSecondsKey] = APP_LOCK_RELOCK_OPTIONS_SECONDS.minBy { k -> Math.abs(k - seconds) }
201− }
202− }
203−
204− suspend fun setChatTextScale(scale: Float) {
205− appContext.settingsDataStore.edit {
206− it[chatTextScaleKey] = scale.coerceIn(MIN_CHAT_TEXT_SCALE, MAX_CHAT_TEXT_SCALE)
207− }
208− }
209− suspend fun setCodeWrap(enabled: Boolean) {
210− appContext.settingsDataStore.edit {
211− it[codeWrapKey] = enabled
212− }
213− }
214−
215− suspend fun setSessionSortMode(mode: String) {
216− appContext.settingsDataStore.edit { it[sessionSortModeKey] = mode }
217− }
218−
219− suspend fun setSessionSortDescending(descending: Boolean) {
220− appContext.settingsDataStore.edit { it[sessionSortDescendingKey] = descending }
221− }
222− suspend fun setSessionShowArchived(show: Boolean) {
223− appContext.settingsDataStore.edit {
224− it[sessionShowArchivedKey] = show
225− }
226− }
227−
228− suspend fun setPreferredModelId(modelId: String) {
229− appContext.settingsDataStore.edit {
230− if (modelId.isEmpty()) it.remove(preferredModelIdKey) else it[preferredModelIdKey] = modelId
231− }
232− }
233−
234− suspend fun setPreferredAgentName(agentName: String) {
235− appContext.settingsDataStore.edit {
236− if (agentName.isEmpty()) it.remove(preferredAgentNameKey) else it[preferredAgentNameKey] = agentName
237− }
238− }
239−
240− suspend fun setCompactMessageSpacing(enabled: Boolean) {
241− appContext.settingsDataStore.edit {
242− it[compactMessageSpacingKey] = enabled
243− }
244− }
245−
246− suspend fun setHapticsEnabled(enabled: Boolean) {
247− appContext.settingsDataStore.edit { it[hapticsEnabledKey] = enabled }
248− }
249−
250− suspend fun setReducedMotion(enabled: Boolean) {
251− appContext.settingsDataStore.edit { it[reducedMotionKey] = enabled }
252− }
253−
254− suspend fun setLanguageOverride(code: String) {
255− appContext.settingsDataStore.edit {
256− if (code.isEmpty()) it.remove(languageOverrideKey) else it[languageOverrideKey] = code
257− }
258− }
259−
260− suspend fun setNotifRunComplete(enabled: Boolean) {
261− appContext.settingsDataStore.edit { it[notifRunCompleteKey] = enabled }
262− }
263− suspend fun setNotifPermission(enabled: Boolean) {
264− appContext.settingsDataStore.edit { it[notifPermissionKey] = enabled }
265− }
266− suspend fun setNotifError(enabled: Boolean) {
267− appContext.settingsDataStore.edit { it[notifErrorKey] = enabled }
268− }
269−
270− suspend fun setSwipeLeftAction(action: SwipeAction) {
271− appContext.settingsDataStore.edit { it[swipeLeftActionKey] = action.name }
272− }
273− suspend fun setSwipeRightAction(action: SwipeAction) {
274− appContext.settingsDataStore.edit { it[swipeRightActionKey] = action.name }
275− }
276−}
277−
278−/** Remappable swipe actions for the session list. NONE disables the swipe entirely. */
279−enum class SwipeAction { DELETE, ARCHIVE, MARK_READ, NONE }
app/src/main/java/soy/iko/opencode/di/AppContainer.ktdeleted−1504
@@ -1,1504 +0,0 @@
1−package soy.iko.opencode.di
2−
3−import android.content.Context
4−import android.net.ConnectivityManager
5−import android.net.Network
6−import android.net.NetworkCapabilities
7−import android.net.NetworkRequest
8−import android.util.Log
9−import soy.iko.opencode.data.model.AssistantMessage
10−import soy.iko.opencode.data.model.BusEvent
11−import soy.iko.opencode.data.model.FilePromptPart
12−import soy.iko.opencode.data.model.MessagePartUpdated
13−import soy.iko.opencode.data.model.MessageUpdated
14−import soy.iko.opencode.data.model.Permission
15−import soy.iko.opencode.data.model.PermissionReplied
16−import soy.iko.opencode.data.model.PermissionResponse
17−import soy.iko.opencode.data.model.PermissionUpdated
18−import soy.iko.opencode.data.model.StepFinishPart
19−import soy.iko.opencode.data.model.ServerProfile
20−import soy.iko.opencode.data.model.SessionError
21−import soy.iko.opencode.data.model.SessionIdle
22−import soy.iko.opencode.data.model.ToolPart
23−import soy.iko.opencode.data.model.TODO_WRITE_TOOL
24−import soy.iko.opencode.data.model.parseTodos
25−import soy.iko.opencode.data.model.statusEnum
26−import soy.iko.opencode.data.model.TodoStatus
27−import soy.iko.opencode.data.model.inputElement
28−import soy.iko.opencode.data.repo.AttachmentDraftStore
29−import soy.iko.opencode.data.repo.BackupManager
30−import soy.iko.opencode.data.repo.DraftStore
31−import soy.iko.opencode.data.repo.ErrorKind
32−import soy.iko.opencode.data.repo.FileBrowserPrefs
33−import soy.iko.opencode.data.repo.MessageCacheStore
34−import soy.iko.opencode.data.repo.OutboxMessage
35−import soy.iko.opencode.data.repo.OutboxStore
36−import soy.iko.opencode.data.repo.RecentModelsStore
37−import soy.iko.opencode.data.repo.SearchHistoryStore
38−import soy.iko.opencode.data.repo.SessionPrefsStore
39−import soy.iko.opencode.data.repo.SessionRepository
40−import soy.iko.opencode.data.repo.ProfileStore
41−import soy.iko.opencode.data.repo.SettingsStore
42−import soy.iko.opencode.data.repo.classifyError
43−import soy.iko.opencode.data.repo.responseStatusCode
44−import soy.iko.opencode.data.network.EventStreamClient
45−import soy.iko.opencode.data.network.HttpClientFactory
46−import soy.iko.opencode.data.network.NetworkConfig
47−import soy.iko.opencode.data.network.OpencodeApiClient
48−import soy.iko.opencode.notification.NotificationChannels
49−import soy.iko.opencode.notification.RunForegroundService
50−import soy.iko.opencode.util.safeExceptionSummary
51−import soy.iko.opencode.notification.SessionNotifications
52−import soy.iko.opencode.R
53−import soy.iko.opencode.util.runCatchingCancellable
54−import kotlinx.coroutines.CoroutineScope
55−import kotlinx.coroutines.Dispatchers
56−import kotlinx.coroutines.ExperimentalCoroutinesApi
57−import kotlinx.coroutines.SupervisorJob
58−import kotlinx.coroutines.cancel
59−import kotlinx.coroutines.delay
60−import kotlinx.coroutines.flow.MutableSharedFlow
61−import kotlinx.coroutines.flow.MutableStateFlow
62−import kotlinx.coroutines.flow.SharedFlow
63−import kotlinx.coroutines.flow.StateFlow
64−import kotlinx.coroutines.flow.asSharedFlow
65−import kotlinx.coroutines.flow.asStateFlow
66−import kotlinx.coroutines.flow.collectLatest
67−import kotlinx.coroutines.flow.combine
68−import kotlinx.coroutines.flow.debounce
69−import kotlinx.coroutines.flow.distinctUntilChanged
70−import kotlinx.coroutines.flow.drop
71−import kotlinx.coroutines.flow.emptyFlow
72−import kotlinx.coroutines.flow.first
73−import kotlinx.coroutines.Job
74−import kotlinx.coroutines.flow.flatMapLatest
75−import kotlinx.coroutines.flow.map
76−import kotlinx.coroutines.flow.update
77−import kotlinx.coroutines.isActive
78−import kotlinx.coroutines.launch
79−import kotlinx.coroutines.sync.Mutex
80−import kotlinx.coroutines.sync.withLock
81−import kotlinx.coroutines.withTimeoutOrNull
82−import java.util.concurrent.atomic.AtomicBoolean
83−
84−/**
85− * Result of probing a server URL to check connectivity and whether authentication
86− * is required, without persisting a profile or opening a long-lived connection.
87− */
88−sealed class ProbeResult {
89− /** Server is reachable and accepts unauthenticated requests. */
90− object Reachable : ProbeResult()
91−
92− /** Server is reachable but rejected the probe with an authentication error. */
93− object NeedsAuth : ProbeResult()
94−
95− /** Server could not be reached (host unresolved, connection refused, timeout, etc.). */
96− data class Unreachable(val error: String) : ProbeResult()
97−}
98−
99−/**
100− * Hand-written service locator held by [soy.iko.opencode.OpencodeApp]. Owns the
101− * process-wide singletons and the currently active [OpencodeConnection].
102− */
103−open class AppContainer private constructor(
104− private val appContext: Context?,
105− private val skipInit: Boolean,
106− @Suppress("unused") private val testMode: Boolean,
107−) {
108− constructor(context: Context) : this(context.applicationContext, false, false)
109− protected constructor() : this(null, true, true)
110−
111− private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
112− open val profileStore: ProfileStore by lazy { ProfileStore(appContext!!) }
113− open val settingsStore: SettingsStore by lazy { SettingsStore(appContext!!) }
114− open val draftStore: DraftStore by lazy { DraftStore(appContext!!, appScope) }
115− open val attachmentDraftStore: AttachmentDraftStore by lazy { AttachmentDraftStore(appContext!!) }
116− open val sessionPrefsStore: SessionPrefsStore by lazy { SessionPrefsStore(appContext!!) }
117− open val messageCacheStore: MessageCacheStore by lazy { MessageCacheStore(appContext!!) }
118− open val outboxStore: OutboxStore by lazy { OutboxStore(appContext!!) }
119− open val searchHistoryStore: SearchHistoryStore by lazy { SearchHistoryStore(appContext!!) }
120− open val recentModelsStore: RecentModelsStore by lazy { RecentModelsStore(appContext!!) }
121− open val fileBrowserPrefs: FileBrowserPrefs by lazy { FileBrowserPrefs(appContext!!) }
122− open val backupManager: BackupManager by lazy { BackupManager(profileStore, settingsStore, sessionPrefsStore) }
123−
124− /** True while the outbox is actively flushing queued messages to the server, so the UI
125− * can show a "sending queued messages…" indicator. */
126− private val _outboxSending = MutableStateFlow(false)
127− open val outboxSending: StateFlow<Boolean> = _outboxSending.asStateFlow()
128−
129− /** Bumped to nudge an immediate outbox flush (after enqueue, or a manual "Send now"),
130− * independent of connection/online changes. */
131− private val _outboxFlushTrigger = MutableStateFlow(0)
132− open fun flushOutbox() { _outboxFlushTrigger.update { it + 1 } }
133−
134− private val _activeConnection = MutableStateFlow<OpencodeConnection?>(null)
135− open val activeConnection: StateFlow<OpencodeConnection?> = _activeConnection.asStateFlow()
136−
137− /** True while a background auto-reconnect to the most-recent server is in flight. */
138− private val _reconnecting = MutableStateFlow(false)
139− open val reconnecting: StateFlow<Boolean> = _reconnecting.asStateFlow()
140−
141− /**
142− * Set once a startup auto-reconnect succeeds. The server list collects this and
143− * (once) navigates straight to the session list so a returning user skips it.
144− * [consumeAutoConnect] guards against re-firing on screen re-entry.
145− */
146− private val _autoConnectDone = MutableStateFlow(false)
147− open val autoConnectDone: StateFlow<Boolean> = _autoConnectDone.asStateFlow()
148− private val autoConnectConsumed = AtomicBoolean(false)
149− open fun consumeAutoConnect(): Boolean = autoConnectConsumed.compareAndSet(false, true)
150−
151− /** Text shared into the app (ACTION_SEND), prefilled into a session draft. */
152− private val _pendingShare = MutableStateFlow<String?>(null)
153− open val pendingShare: StateFlow<String?> = _pendingShare.asStateFlow()
154− open fun setPendingShare(text: String) { _pendingShare.value = text }
155− open fun consumePendingShare(): String? {
156− val current = _pendingShare.value ?: return null
157− return if (_pendingShare.compareAndSet(current, null)) current else null
158− }
159−
160− /** Image/file Uris (as strings) shared into the app, staged as attachments in the next
161− * opened session. Consumed once by the first ChatScreen to compose after the share. */
162− private val _pendingSharedMedia = MutableStateFlow<List<String>>(emptyList())
163− open val pendingSharedMedia: StateFlow<List<String>> = _pendingSharedMedia.asStateFlow()
164− open fun setPendingSharedMedia(uris: List<String>) { _pendingSharedMedia.value = uris }
165− open fun consumePendingSharedMedia(): List<String> {
166− val current = _pendingSharedMedia.value
167− if (current.isEmpty()) return emptyList()
168− return if (_pendingSharedMedia.compareAndSet(current, emptyList())) current else emptyList()
169− }
170−
171− /**
172− * Set from an external "New session" trigger (launcher shortcut / QS tile). The nav host
173− * consumes it once connected, creating a fresh session and opening it. Uses a counter
174− * (not a boolean) so re-tapping the shortcut while a prior request is still pending
175− * increments the value and re-fires the LaunchedEffect — a boolean StateFlow wouldn't
176− * emit when set to the same value, making the request unrecoverable by re-tapping.
177− */
178− private val _pendingNewSession = MutableStateFlow(0)
179− open val pendingNewSession: StateFlow<Int> = _pendingNewSession.asStateFlow()
180− open fun requestNewSession() { _pendingNewSession.update { it + 1 } }
181− open fun consumePendingNewSession(): Boolean {
182− while (true) {
183− val current = _pendingNewSession.value
184− if (current == 0) return false
185− if (_pendingNewSession.compareAndSet(current, current - 1)) return true
186− }
187− }
188−
189− /** A one-shot signal to navigate to the Diagnostics screen (e.g. from the crash-relaunch
190− * prompt). Consumed by OpencodeApp's NavHost. */
191− private val _pendingDiagnostics = MutableStateFlow(false)
192− open val pendingDiagnostics: StateFlow<Boolean> = _pendingDiagnostics.asStateFlow()
193− open fun requestDiagnostics() { _pendingDiagnostics.value = true }
194− open fun consumePendingDiagnostics(): Boolean = _pendingDiagnostics.compareAndSet(true, false)
195−
196− /**
197− * A session id to open from an external trigger (a notification tap or a deep link),
198− * paired with the originating server's profile id (if known) so a tap after the user
199− * has switched servers routes back to the server that ran the session. The nav host
200− * consumes it once a connection is active (switching to [profileId] first if needed).
201− */
202− data class PendingOpenSession(val sessionId: String, val profileId: String?)
203−
204− private val _pendingOpenSession = MutableStateFlow<PendingOpenSession?>(null)
205− open val pendingOpenSession: StateFlow<PendingOpenSession?> = _pendingOpenSession.asStateFlow()
206− open fun requestOpenSession(id: String, profileId: String? = null) {
207− _pendingOpenSession.value = PendingOpenSession(id, profileId)
208− }
209− open fun consumePendingOpenSession(): PendingOpenSession? {
210− val current = _pendingOpenSession.value ?: return null
211− return if (_pendingOpenSession.compareAndSet(current, null)) current else null
212− }
213−
214− /**
215− * A file path requested to be opened (via deep link `opencode://file/{path}` or future
216− * entry points), consumed by the NavHost to navigate to the file viewer. Mirrors the
217− * session open-signal pattern: a StateFlow the NavHost observes, drained atomically.
218− */
219− private val _pendingOpenFile = MutableStateFlow<String?>(null)
220− open val pendingOpenFile: StateFlow<String?> = _pendingOpenFile.asStateFlow()
221− open fun requestOpenFile(path: String) { _pendingOpenFile.value = path }
222− open fun consumePendingOpenFile(): String? {
223− val current = _pendingOpenFile.value ?: return null
224− return if (_pendingOpenFile.compareAndSet(current, null)) current else null
225− }
226−
227− /**
228− * The session the user is currently viewing (or null when not in a chat). Drives the
229− * unread tracker: messages arriving for any *other* session mark it unread, and
230− * opening a session clears its unread state.
231− */
232− private val _currentSession = MutableStateFlow<String?>(null)
233− open val currentSession: StateFlow<String?> = _currentSession.asStateFlow()
234−
235− /** Session ids that received activity while not being viewed, mapped to the count
236− * of unread message events. A count (not just a presence set) lets the session
237− * list badge show "3 unread" instead of a bare dot, so the user can tell whether
238− * one reply or a whole burst arrived. */
239− private val _unread = MutableStateFlow<Map<String, Int>>(emptyMap())
240− open val unread: StateFlow<Map<String, Int>> = _unread.asStateFlow()
241−
242− /** Session ids the user has muted. A muted session doesn't badge unread (the count is
243− * still tracked internally so unmuting can restore it, but the badge and completion
244− * notification are suppressed). Persisted via SessionPrefsStore so the choice survives
245− * process death. */
246− private val _mutedSessions = MutableStateFlow<Set<String>>(emptySet())
247− open val mutedSessions: StateFlow<Set<String>> = _mutedSessions.asStateFlow()
248−
249− /** True when any assistant run is actively streaming across all sessions. Drives the
250− * disconnect confirmation on the session list (disconnecting mid-run kills it). */
251− private val _anyRunActive = MutableStateFlow(false)
252− open val anyRunActive: StateFlow<Boolean> = _anyRunActive.asStateFlow()
253−
254− /** Session ids currently streaming an assistant run, surfaced so the session list can
255− * badge the row whose run is active. Mirrors [activeRuns] as an immutable snapshot so
256− * Compose can skip recomposition when the set hasn't changed. */
257− private val _runningSessionIds = MutableStateFlow<Set<String>>(emptySet())
258− open val runningSessionIds: StateFlow<Set<String>> = _runningSessionIds.asStateFlow()
259−
260− /** Latest task-plan progress text for the active run (e.g. "Step 2 of 5"), surfaced in
261− * the foreground-service notification so the user can see what the agent is working on
262− * without opening the app. Null when no plan is available or no run is active. */
263− private val _runProgressText = MutableStateFlow<String?>(null)
264− open val runProgressText: StateFlow<String?> = _runProgressText.asStateFlow()
265−
266− /** Whether the device currently has network connectivity. Distinct from the SSE
267− * connection state so the UI can tell "you're offline" (device) from "server
268− * unreachable" (credentials/host). Updated by the [networkCallback]. */
269− private val _isOnline = MutableStateFlow(true)
270− open val isOnline: StateFlow<Boolean> = _isOnline.asStateFlow()
271−
272− /** Whether a foreground Activity is currently showing. Distinct from [currentSession],
273− * which stays set while the app is merely backgrounded (the chat screen isn't disposed
274− * when the user locks their phone). Permission/completion notifications need the real
275− * foreground signal so they still fire for a session the user "has open" but has walked
276− * away from — the core of the run-in-the-background use case. Set from MainActivity's
277− * onStart/onStop. */
278− private val _isForeground = MutableStateFlow(false)
279− open val isForeground: StateFlow<Boolean> = _isForeground.asStateFlow()
280− open fun setForeground(foreground: Boolean) { _isForeground.value = foreground }
281−
282− /** True when the user is actively looking at [sessionId] (app foregrounded AND that
283− * session is the one on screen), so an in-app affordance (the permission dialog) is
284− * handling it and a notification would be redundant. */
285− private fun isActivelyViewing(sessionId: String): Boolean =
286− _isForeground.value && sessionId == _currentSession.value
287−
288− open fun setCurrentSession(id: String?) {
289− _currentSession.value = id
290− if (id != null) {
291− _unread.update { it - id }
292− unreadMessageIds.remove(id)
293− appContext?.let {
294− SessionNotifications.cancel(it, id)
295− SessionNotifications.cancelPermission(it, id)
296− SessionNotifications.cancelError(it, id)
297− }
298− }
299− }
300−
301− /** Clear unread badge and dedup set for a deleted session so its stale count doesn't
302− * linger in the session list badge or leak memory until the next connect/disconnect. */
303− open fun clearUnread(id: String) {
304− _unread.update { it - id }
305− unreadMessageIds.remove(id)
306− }
307−
308− /** Mark a session as read (clear its unread badge) — the "Mark read" notification action. */
309− open fun markSessionRead(id: String) = clearUnread(id)
310−
311− /** Mark a session as unread with a count of 1 (or restore a prior count). Used by the
312− * session list's "Mark as unread" overflow action so a user can re-flag a conversation
313− * they want to revisit. No-op when the session is the one currently being viewed — a
314− * viewed session clears its own unread badge via [setCurrentSession], so marking it
315− * unread would race and immediately clear. Muted sessions are still marked (the count is
316− * tracked so unmuting restores it) but the list UI hides the badge while muted. */
317− open fun markSessionUnread(id: String, count: Int = 1) {
318− if (id == _currentSession.value) return
319− _unread.update { it + (id to count) }
320− }
321−
322− /** Toggle a session's mute state. A muted session suppresses the unread badge and the
323− * completion notification so a noisy conversation doesn't keep interrupting. Persisted
324− * via SessionPrefsStore so it survives process death. */
325− fun toggleSessionMute(id: String) {
326− val muted = id in _mutedSessions.value
327− val next = if (muted) _mutedSessions.value - id else _mutedSessions.value + id
328− _mutedSessions.value = next
329− appContext?.let {
330− appScope.launch {
331− runCatchingCancellable { sessionPrefsStore.setMuted(id, !muted) }
332− }
333− }
334− }
335−
336− /** True when [id] is muted (unread badge and completion notification suppressed). */
337− fun isSessionMuted(id: String): Boolean = id in _mutedSessions.value
338−
339− /** Clear every session's unread badge at once — the session list's "Mark all read" action. */
340− open fun clearAllUnread() {
341− _unread.update { emptyMap() }
342− }
343−
344− /** Restore a session's unread badge after a failed server switch reconnects.
345− * Preserves the prior [count] so a session badged with "5 unread" before the
346− * switch attempt still shows 5 (not 1) after the restore. No-op for the session
347− * the user is currently viewing, since a viewed session is never badged. */
348− open fun restoreUnread(id: String, count: Int) {
349− if (id != _currentSession.value) {
350− _unread.update { it + (id to count) }
351− }
352− }
353−
354− /** Resolve a localized string — view models reach resources through the container. */
355− open fun string(id: Int, vararg formatArgs: Any): String {
356− if (appContext == null) return ""
357− return if (formatArgs.isEmpty()) appContext.getString(id) else appContext.getString(id, *formatArgs)
358− }
359−
360− /**
361− * Convert a throwable into a user-facing message. Classifies the error by concrete
362− * type (network, timeout, HTTP status) rather than string-matching class names, so
363− * the message reflects what actually went wrong without leaking internal URLs/state.
364− */
365− open fun friendlyError(t: Throwable): String =
366− friendlyErrorFor(t, activeConnection.value?.profile?.baseUrl.orEmpty())
367−
368− /**
369− * Same classification as [friendlyError] but accepts an explicit base URL, so callers
370− * that aren't operating on the active connection (e.g. [probeServer]) can still
371− * produce a user-facing message with the right server address.
372− */
373− open fun friendlyErrorFor(t: Throwable, baseUrl: String): String =
374− when (classifyError(t)) {
375− ErrorKind.NOT_REACHABLE, ErrorKind.NETWORK ->
376− string(R.string.error_not_reachable, baseUrl)
377− ErrorKind.TIMEOUT -> string(R.string.error_timeout)
378− ErrorKind.SERVER -> string(R.string.error_server)
379− // Show only the HTTP status (e.g. 401, 404) — never the request URL,
380− // which a ClientRequestException carries in its message and which we
381− // promised not to leak (it can include auth or internal paths).
382− ErrorKind.CLIENT -> {
383− val code = responseStatusCode(t)
384− when (code) {
385− // Auth failures reuse the connection banner text: the request itself is
386− // fine, the credentials aren't, so the fix is re-editing the profile —
387− // not "request failed (401)" which implies an opaque program error.
388− 401, 403 -> string(R.string.connection_failed)
389− 404 -> string(R.string.error_not_found)
390− else -> code?.let { string(R.string.error_client_status, it) }
391− ?: string(R.string.error_generic)
392− }
393− }
394− ErrorKind.UNKNOWN -> string(R.string.error_generic)
395− }
396−
397− /**
398− * Drive the [RunForegroundService] from the process-lived [appScope] rather than from the
399− * Activity's composition. Previously the start/stop was wired to a
400− * `collectAsStateWithLifecycle` collector in the root composable, which pauses while the
401− * Activity is STOPPED — so a run *started while backgrounded* (e.g. via the notification
402− * inline-reply) never acquired foreground priority and its long-lived SSE stream could be
403− * killed by Doze, and a run that *ended* while backgrounded left the "working…"
404− * notification lingering until the app was reopened. Collecting here reacts to
405− * [anyRunActive] regardless of Activity state.
406− */
407− private fun observeRunForegroundService() {
408− val ctx = appContext ?: return
409− appScope.launch {
410− // Debounce so a run that starts then fails/idles almost immediately doesn't
411− // dispatch startForegroundService() then stopService() back-to-back — if the stop
412− // wins that race before the service calls startForeground(), Android raises the
413− // "did not then call startForeground()" crash ~5s later. Collapsing the window
414− // emits only the settled state; distinctUntilChanged drops a no-op re-emit when a
415− // brief true→false→true flurry settles back to the value already applied.
416− anyRunActive
417− .debounce(NetworkConfig.runForegroundDebounceMs)
418− .distinctUntilChanged()
419− .collect { active ->
420− if (active) {
421− // When exactly one run is active, resolve its title (and id, for the
422− // Stop action) so the notification identifies which session is running
423− // and can be aborted from the notification. Multiple concurrent runs
424− // fall back to the generic title (naming one would be misleading).
425− val activeId = synchronized(activeRuns) {
426− activeRuns.toList().singleOrNull()
427− }
428− val title = activeId?.let { sid ->
429− runCatchingCancellable {
430− activeConnection.value?.repository?.listSessions()
431− ?.firstOrNull { it.id == sid }?.displayTitle
432− }.getOrNull()
433− }
434− RunForegroundService.start(ctx, title, activeId, _runProgressText.value)
435− } else {
436− RunForegroundService.stop(ctx)
437− }
438− }
439− }
440− // Separate collector: update the FGS notification's progress text ("Step 2 of 5")
441− // as the agent works through its task plan. Re-sends the service intent with the
442− // updated progress, which the service uses to rebuild the notification.
443− appScope.launch {
444− _runProgressText
445− .drop(1) // skip initial value — the anyRunActive collector handles the first start
446− .distinctUntilChanged()
447− .collect { progress ->
448− if (_anyRunActive.value) {
449− val activeId = synchronized(activeRuns) { activeRuns.toList().singleOrNull() }
450− val title = activeId?.let { sid ->
451− runCatchingCancellable {
452− activeConnection.value?.repository?.listSessions()
453− ?.firstOrNull { it.id == sid }?.displayTitle
454− }.getOrNull()
455− }
456− RunForegroundService.start(ctx, title, activeId, progress)
457− }
458− }
459− }
460− }
461−
462− /**
463− * Post a system notification when the SSE stream hits a non-retryable failure
464− * ([Failed]/[AuthFailed]) while the app is backgrounded during an active run, so a
465− * backgrounded user is signaled that their run is stranded (the in-app banner isn't
466− * visible). The notification is cancelled when the stream reconnects. This closes the
467− * gap where a user who kicks off a run and backgrounds the app returns hours later to
468− * find nothing happened and no signal why — the stream parked on a 4xx mid-run and the
469− * in-app banner was never seen.
470− */
471− private fun observeBackgroundedConnectionFailures() {
472− val ctx = appContext ?: return
473− appScope.launch {
474− activeConnection.collectLatest { conn ->
475− if (conn == null) return@collectLatest
476− conn.events.state.collect { state ->
477− when (state) {
478− EventStreamClient.ConnectionState.Failed,
479− EventStreamClient.ConnectionState.AuthFailed -> {
480− // Only notify when the app is backgrounded AND a run was recently
481− // active (or still is) — a foregrounded user sees the banner, and
482− // a failure with no run is less actionable.
483− if (!_isForeground.value && _anyRunActive.value) {
484− runCatchingCancellable {
485− SessionNotifications.postConnectionLost(
486− ctx, conn.profile.displayLabel, conn.profile.id,
487− )
488− }.onFailure {
489− Log.w("AppContainer", "connection-lost notification failed: ${safeExceptionSummary(it)}")
490− }
491− }
492− }
493− EventStreamClient.ConnectionState.Connected -> {
494− runCatchingCancellable { SessionNotifications.cancelConnectionLost(ctx) }
495− }
496− else -> {}
497− }
498− }
499− }
500− }
501− }
502−
503− /**
504− * Reconcile active-run tracking on an SSE *reconnect*. A run that completes during a stream
505− * outage never delivers its `SessionIdle`, so its id would stay in [activeRuns] and pin
506− * [anyRunActive] (and the foreground service + "working…" notification) on indefinitely. On a
507− * reconnect we clear the tracking and let live streaming events re-populate it: a genuinely
508− * in-progress run re-adds itself within moments via [isLiveRunActivity], while a run that
509− * finished during the outage produces no further live events (its completion arrives only via
510− * the REST re-seed), so it correctly stays cleared. The first connect of a connection is not a
511− * reconnect; `connect()` already resets [activeRuns], so only subsequent Connected transitions
512− * trigger the sweep.
513− */
514− private fun observeRunReconcileOnReconnect() {
515− appScope.launch {
516− activeConnection.collectLatest { conn ->
517− if (conn == null) return@collectLatest
518− var hasConnectedBefore = false
519− conn.events.state.collect { state ->
520− if (state == EventStreamClient.ConnectionState.Connected) {
521− if (hasConnectedBefore) {
522− synchronized(activeRuns) {
523− activeRuns.clear()
524− publishRunState()
525− }
526− }
527− hasConnectedBefore = true
528− }
529− }
530− }
531− }
532− }
533−
534− /**
535− * Flush the offline outbox whenever there's an active connection and the device is
536− * online (and on any manual [flushOutbox] nudge). Queued messages are only sent to the
537− * server they were composed for (matched by profile id), so a reconnect to a different
538− * server never misfires them against a session id that doesn't exist there. Uses a plain
539− * `collect` (not collectLatest) so an in-flight send is never cancelled mid-flight and
540− * send order is preserved; each message carries a stable idempotency key (its persistent
541− * outbox id) so even a re-send across flushes is deduplicated server-side.
542− */
543− private fun observeOutbox() {
544− appScope.launch {
545− combine(activeConnection, isOnline, _outboxFlushTrigger) { conn, online, _ -> conn to online }
546− .collect { (conn, online) ->
547− if (conn == null || !online) return@collect
548− flushOutboxNow(conn)
549− }
550− }
551− }
552−
553− private suspend fun flushOutboxNow(conn: OpencodeConnection) {
554− val pending = outboxStore.messages.value
555− .filter { it.profileId == conn.profile.id }
556− .sortedBy { it.createdAt }
557− if (pending.isEmpty()) return
558− _outboxSending.value = true
559− try {
560− for (msg in pending) {
561− val result = runCatchingCancellable {
562− conn.repository.sendPrompt(
563− msg.sessionId,
564− msg.text,
565− attachments = msg.attachments.map {
566− FilePromptPart(mime = it.mime, url = it.url, filename = it.filename)
567− },
568− model = msg.model,
569− agent = msg.agent,
570− // Reuse the persistent outbox id as a stable idempotency key so a
571− // later flush of a message whose earlier POST reached the server (but
572− // whose response was lost) is deduplicated server-side instead of
573− // starting a duplicate agent run.
574− idempotencyKey = msg.id,
575− )
576− }.onFailure {
577− Log.w("AppContainer", "Outbox flush failed for ${msg.sessionId}: ${safeExceptionSummary(it)}")
578− }
579− if (result.isSuccess) {
580− outboxStore.remove(msg.id)
581− continue
582− }
583− // A permanently-undeliverable message (a non-408/429 4xx — e.g. the target
584− // session was deleted server-side, yielding a 404) must be dropped, not left at
585− // the head of the queue. The loop stops at the first failure to preserve send
586− // order, so a poison message would otherwise block every later queued message
587− // for this profile forever. Transient failures (offline again, 5xx, 408/429)
588− // keep the queue intact and retry on the next trigger.
589− // 401/403 (bad/expired credentials) are NOT permanent: the message itself is
590− // deliverable once the user fixes the profile. Dropping it would silently lose
591− // the user's composed offline prompt on a recoverable auth failure. They stay
592− // in the queue and retry on the next flush after auth is restored.
593− val status = result.exceptionOrNull()?.let { responseStatusCode(it) }
594− // Permanent = a non-408/429/401/403 4xx, matching withRetry's non-retryable rule
595− // except for auth failures, which are recoverable by re-editing the profile.
596− val permanent = when (status) {
597− null, 408, 429, 401, 403 -> false
598− in 400..499 -> true
599− else -> false
600− }
601− if (permanent) {
602− Log.w(
603− "AppContainer",
604− "Dropping undeliverable outbox message ${msg.id} for ${msg.sessionId} (HTTP $status): ${string(R.string.outbox_dropped_text)}",
605− )
606− outboxStore.remove(msg.id)
607− // Surface the dropped reply on the ERROR channel with a distinct title
608− // ("Message not delivered") so the user understands a queued reply
609− // couldn't be delivered — not that a run failed (which postError
610− // implies). Tap routes back to the originating profile's session.
611− val ctx = appContext
612− if (ctx != null) {
613− val title = resolveSessionTitle(msg.sessionId, conn.repository)
614− runCatchingCancellable {
615− SessionNotifications.postOutboxDropped(
616− ctx, msg.sessionId,
617− title,
618− conn.profile.id,
619− )
620− }.onFailure {
621− Log.w("AppContainer", "outbox drop notification failed: ${safeExceptionSummary(it)}")
622− }
623− }
624− } else {
625− break
626− }
627− }
628− } finally {
629− _outboxSending.value = false
630− }
631− }
632−
633− /** Release resources held for the process lifetime (network callback, app scope). */
634− open fun shutdown() {
635− // Cancel the app scope first so any coroutine holding the connection mutex
636− // (e.g. a connect() suspended on profileStore) is cancelled and releases the
637− // mutex. Otherwise the runBlocking below would deadlock waiting for a coroutine
638− // that can't be cancelled until after the runBlocking completes.
639− appScope.cancel()
640− // Bounded runBlocking so a stuck mutex or a slow close() can't ANR the app.
641− // 2 seconds is generous: appScope.cancel() already triggered cancellation of
642− // any coroutine holding the mutex; we're just waiting for it to unwind.
643− kotlinx.coroutines.runBlocking {
644− withTimeoutOrNull(2_000) {
645− connectionMutex.withLock {
646− runCatching { _activeConnection.value?.close() }
647− _activeConnection.value = null
648− }
649− }
650− // If the timeout fired, force-clear the connection so it isn't left dangling.
651− _activeConnection.value = null
652− }
653− val cm = appContext?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
654− networkCallback?.let { runCatching { cm?.unregisterNetworkCallback(it) } }
655− if (!skipInit) soy.iko.opencode.data.repo.CrashLogger.get(appContext!!).shutdown()
656− if (!skipInit) draftStore.shutdown()
657− }
658−
659− /**
660− * Watch the SSE bus for new message activity and badge any session that isn't
661− * currently open. This powers the unread dot on the session list so the user can
662− * tell which conversations got a reply while they were elsewhere.
663− *
664− * Uses [flatMapLatest] so a server switch (which replaces the active connection)
665− * re-subscribes to the new event stream and drops the old one.
666− */
667− @OptIn(ExperimentalCoroutinesApi::class)
668− private fun observeMessageActivity() {
669− appScope.launch {
670− // Retry the observer if it fails for any reason (transient flow exception,
671− // cancellation due to scope issues). Without this, a single failure would
672− // permanently disable unread tracking and completion notifications.
673− while (isActive) {
674− runCatchingCancellable {
675− activeConnection
676− .flatMapLatest { conn ->
677− // Capture the originating connection so notification coroutines
678− // resolve titles and route permission responses against THIS
679− // server, not whichever happens to be active when they resume.
680− // A server switch during a listSessions() round-trip would
681− // otherwise resolve the title (or POST the permission reply)
682− // against the new server, where the session/permission doesn't
683− // exist — showing an opaque id or silently losing the reply.
684− conn?.events?.events?.map { conn to it } ?: emptyFlow()
685− }
686− .collect { (conn, event) ->
687− // A permission request needs the user's approval. Post a heads-up
688− // notification (with Allow/Reject actions) unless the user is actively
689− // viewing this session, where the in-app permission dialog handles it.
690− if (event is PermissionUpdated) {
691− val psid = event.properties.sessionID.takeIf { it.isNotBlank() } ?: return@collect
692− if (!isActivelyViewing(psid)) appScope.launch { notifyPermission(event.properties, conn) }
693− return@collect
694− }
695− // The permission was answered (in-app, from the notification, or
696− // auto-resolved): clear its heads-up notification.
697− if (event is PermissionReplied) {
698− val psid = event.properties.sessionID?.takeIf { it.isNotBlank() } ?: return@collect
699− appContext?.let { SessionNotifications.cancelPermission(it, psid) }
700− return@collect
701− }
702− // A run failed. Clear its active-run tracking (an error isn't always
703− // followed by a SessionIdle) and notify unless it's being viewed.
704− if (event is SessionError) {
705− val esid = event.properties.sessionID ?: return@collect
706− val wasRunning = synchronized(activeRuns) {
707− activeRuns.remove(esid).also { removed ->
708− if (removed) publishRunState()
709− }
710− }
711− if (wasRunning && !isActivelyViewing(esid)) {
712− appScope.launch { notifySessionError(esid, conn.repository, conn.profile.id) }
713− }
714− return@collect
715− }
716− // SessionIdle is not "message activity" (don't badge as unread)
717− // but signals a run finished — fire a completion notification if the
718− // session isn't currently being viewed and was actively streaming.
719− if (event is SessionIdle) {
720− val idleSid = event.properties.sessionID ?: return@collect
721− // Clear the run state unconditionally — even for the session on
722− // screen. Gating the removal on `idleSid != currentSession` (as
723− // this once did) leaks the id in activeRuns and pins anyRunActive
724− // true forever whenever a run finishes while being viewed. Only
725− // the completion *notification* is suppressed for the viewed one.
726− val wasRunning = synchronized(activeRuns) {
727− activeRuns.remove(idleSid).also { removed ->
728− if (removed) publishRunState()
729− }
730− }
731− // Clear the progress text when the run finishes.
732− _runProgressText.value = null
733− if (wasRunning && !isActivelyViewing(idleSid)) {
734− // Fire this off the collector's coroutine: notifySessionCompleted
735− // does a network listSessions() to resolve the title, and blocking
736− // the shared-event collector here would stall the SharedFlow,
737− // overflowing its DROP_OLDEST buffer and silently dropping live
738− // parts/updates for every other subscriber (e.g. the message reducer).
739− appScope.launch { notifySessionCompleted(idleSid, conn.repository, conn.profile.id) }
740− }
741− return@collect
742− }
743− // Track the agent's task-plan progress (from todowrite tool calls) so the
744− // foreground-service notification can show "Step 2 of 5" instead of just a
745− // chronometer. The todowrite tool sends the full plan on every call, so the
746− // latest call's input is a complete snapshot.
747− if (event is MessagePartUpdated) {
748− val part = event.properties.part
749− if (part is ToolPart && part.tool.equals(TODO_WRITE_TOOL, ignoreCase = true)) {
750− val todos = parseTodos(part.state.inputElement())
751− if (todos.isNotEmpty()) {
752− val completed = todos.count { it.statusEnum() == TodoStatus.COMPLETED }
753− _runProgressText.value = appContext?.getString(
754− soy.iko.opencode.R.string.notif_running_progress,
755− completed + 1,
756− todos.size,
757− )
758− }
759− }
760− }
761− val sid = sessionOf(event) ?: return@collect
762− // Re-read currentSession here, right before mutating the badge state:
763− // the user may have opened this session between when this event was
764− // enqueued and now (setCurrentSession clears its badge and dedup set).
765− // A stale earlier check would race a badge — and a dedup entry — back
766− // in for the session that's actually on screen.
767− if (sid != _currentSession.value) {
768− // Skip the unread badge for muted sessions — the count is still tracked
769− // in unreadMessageIds (so unmuting can't re-count the same messages),
770− // but the visible badge is suppressed so a muted conversation doesn't
771− // interrupt. The completion notification is also gated on isSessionMuted
772− // (see notifySessionCompleted).
773− if (sid !in _mutedSessions.value) {
774− // Increment the unread count once per distinct *message*, not per
775− // event: a single reply emits many message.updated / message.part.
776− // updated events (one per streamed token, plus cost/token refreshes),
777− // which would otherwise inflate the badge into the dozens/hundreds.
778− val messageId = messageIdOfEvent(event)
779− val counted = unreadMessageIds.getOrPut(sid) {
780− java.util.Collections.synchronizedSet(mutableSetOf())
781− }
782− if (messageId == null || counted.add(messageId)) {
783− _unread.update { current ->
784− // Guard again inside the atomic update lambda so a retry
785− // (or an open that landed just now) can't reintroduce the
786− // badge for the session on screen.
787− if (sid == _currentSession.value) current
788− else current + (sid to (current[sid] ?: 0) + 1)
789− }
790− }
791− }
792− }
793− // Track sessions actively streaming so we know which idle events
794− // represent a finished run worth notifying about.
795− if (isLiveRunActivity(event)) {
796− // The add-under-lock is required both for thread-safety and for the
797− // access-order refresh (keeps a continuously-streaming session from
798− // being evicted), so it runs per event.
799− synchronized(activeRuns) {
800− activeRuns.add(sid)
801− // Derive the flag from the set state *inside* the same lock that
802− // guards the set, so a concurrent reconnect sweep (which clears
803− // both under this lock) can't interleave and leave the flag pinned
804− // true with an empty set — a stuck foreground service + "working…".
805− publishRunState()
806− }
807− }
808− } }.onFailure { Log.w("AppContainer", "Message activity observer failed, will retry: ${safeExceptionSummary(it)}") }
809− if (!isActive) break
810− delay(NetworkConfig.observerRetryDelayMs)
811− }
812− }
813− }
814−
815− /** True if [event] is live streaming activity worth tracking as an active run. A
816− * trailing message.updated that lands *after* the run finished (final cost/token totals,
817− * carrying a completion time) is NOT live streaming: with no further SessionIdle to
818− * follow it, re-adding the session would pin anyRunActive true indefinitely. */
819− private fun isLiveRunActivity(event: BusEvent): Boolean {
820− if (event !is MessagePartUpdated && event !is MessageUpdated) return false
821− // For MessageUpdated, only an in-flight *assistant* message counts as live activity.
822− // A UserMessage or UnknownMessage update (e.g. a metadata refresh of an existing user
823− // message) would otherwise add the session to activeRuns with no following SessionIdle
824− // to clear it — pinning anyRunActive true and the foreground notification indefinitely.
825− // Mirrors SessionRepository.isRunActivity's guard exactly.
826− if (event is MessageUpdated) {
827− val info = event.properties.info
828− return info is AssistantMessage && !info.isComplete && info.error == null
829− }
830− // A step-finish part is the trailing completion marker for a run (it carries the
831− // final cost/token totals) and arrives after the last stream delta. Like a completed
832− // message.updated, treating it as live would re-add the session to activeRuns with no
833− // following SessionIdle to clear it — pinning anyRunActive true indefinitely when such
834− // a part is replayed/reordered after the run already went idle.
835− val part = (event as MessagePartUpdated).properties.part
836− return part !is StepFinishPart
837− }
838−
839− /** Snapshot [activeRuns] into [_runningSessionIds] and derive [_anyRunActive] from it.
840− * MUST be called under the [activeRuns] monitor so the published flag and snapshot can't
841− * diverge from the set a concurrent SSE add()/remove() is mutating — the same invariant
842− * [connectLocked]/[teardownActiveLocked] rely on. */
843− private fun publishRunState() {
844− _anyRunActive.value = activeRuns.isNotEmpty()
845− _runningSessionIds.value = activeRuns.toSet()
846− }
847−
848− /** Session ids currently streaming an assistant run (best-effort, in-process). Backed by
849− * an access-order [java.util.LinkedHashMap] so re-adding an already-present id on each
850− * streaming event refreshes its recency (a plain LinkedHashSet.add is a no-op that does
851− * NOT reorder). Entries are drained by [SessionIdle] (and cleared wholesale on reconnect
852− * reconcile); we intentionally do NOT cap the set, because evicting the eldest would drop
853− * its completion notification when its SessionIdle eventually arrives — a busy server
854− * with many concurrent runs is still bounded by the server's own concurrency, so growth
855− * is not unbounded in practice. */
856− private val activeRuns: MutableSet<String> = java.util.Collections.synchronizedSet(
857− java.util.Collections.newSetFromMap(java.util.LinkedHashMap<String, Boolean>(16, 0.75f, true)),
858− )
859−
860− /** Per non-viewed session, the set of message ids already reflected in its unread
861− * count. De-duplicates the many streaming events that share one message id so the
862− * badge counts messages, not deltas. Cleared when a session is viewed or on connect. */
863− private val unreadMessageIds = java.util.concurrent.ConcurrentHashMap<String, MutableSet<String>>()
864−
865− /** Guards connect/disconnect so concurrent callers can't leak an old connection. */
866− private val connectionMutex = Mutex()
867−
868− /** Only persist the `lastUsed` timestamp if it's older than this, to avoid
869− * a DataStore + encrypted-prefs write on every rapid reconnect. */
870− private companion object {
871− const val LAST_USED_SAVE_THRESHOLD_MS = 60_000L
872− }
873−
874− /** Resolve the human-readable title for [sessionId] (best-effort), falling back to the id.
875− * Uses [originRepo] — the repository of the connection that emitted the event — so a
876− * server switch during the listSessions() round-trip doesn't resolve the title against
877− * an unrelated server (showing an opaque id, or worse, a colliding session's title). */
878− private suspend fun resolveSessionTitle(sessionId: String, originRepo: SessionRepository): String =
879− runCatchingCancellable {
880− originRepo.listSessions()?.firstOrNull { it.id == sessionId }?.displayTitle
881− }.getOrNull() ?: sessionId
882−
883− /** Resolve the title for [sessionId] (best-effort) and post a completion notification.
884− * [originProfileId] is the id of the server that ran the session; it's embedded in the
885− * inline-reply action so a follow-up routes back to THIS server even after the user switches
886− * connections (mirrors [notifyPermission]). */
887− private suspend fun notifySessionCompleted(sessionId: String, originRepo: SessionRepository, originProfileId: String) {
888− val title = resolveSessionTitle(sessionId, originRepo)
889− // Re-check viewing right before posting: the call site checks !isActivelyViewing(sid)
890− // at event time, but resolveSessionTitle() suspends on a listSessions() round-trip.
891− // If the user opened the session in that gap, setCurrentSession already cancelled the
892− // prior notification — posting a fresh one here would leave a "session ready" heads-up
893− // lingering while they're already looking at the finished run.
894− if (isActivelyViewing(sessionId)) return
895− // Suppress the completion notification for muted sessions — the whole point of muting
896− // is that a noisy conversation doesn't interrupt.
897− if (sessionId in _mutedSessions.value) return
898− appContext?.let { SessionNotifications.postCompleted(it, sessionId, title, originProfileId) }
899− }
900−
901− /** Post a heads-up permission notification for [permission], resolving its session title.
902− * [originConn] is the connection that emitted the permission event — its profile id is
903− * embedded in the notification so the receiver routes the response back to THIS server. */
904− private suspend fun notifyPermission(permission: Permission, originConn: OpencodeConnection) {
905− val sessionId = permission.sessionID.takeIf { it.isNotBlank() } ?: return
906− val title = resolveSessionTitle(sessionId, originConn.repository)
907− // Re-check viewing just before posting — see notifySessionCompleted for the race.
908− if (isActivelyViewing(sessionId)) return
909− appContext?.let { SessionNotifications.postPermission(it, permission, title, originConn.profile.id) }
910− }
911−
912− /** Post an error notification for a failed background run. [originProfileId] is embedded
913− * in the tap intent so the session opens under the server that ran it, not whichever
914− * is active when the user taps — mirroring [notifySessionCompleted]. */
915− private suspend fun notifySessionError(sessionId: String, originRepo: SessionRepository, originProfileId: String) {
916− val title = resolveSessionTitle(sessionId, originRepo)
917− // Re-check viewing just before posting — see notifySessionCompleted for the race.
918− if (isActivelyViewing(sessionId)) return
919− appContext?.let { SessionNotifications.postError(it, sessionId, title, originProfileId) }
920− }
921−
922− /** Respond to a permission from a notification action (Allow once / Always / Reject),
923− * off any UI. Runs on the process-lived app scope; [onDone] fires when the call resolves
924− * so the receiver's goAsync() result can finish. Its Boolean is true only when a live
925− * connection existed AND respondPermission succeeded — the receiver uses it to decide
926− * whether to dismiss the notification. A missing connection makes the respond a no-op,
927− * so it must report failure (not success) rather than let the notification vanish with
928− * the tool left unanswered.
929− *
930− * [profileId] is the id of the server that posted the permission request (embedded in
931− * the notification's PendingIntent). If it doesn't match the currently active
932− * connection's profile, the response is NOT sent: posting it to a different server
933− * would 404 (treated as "already resolved" success by respondPermission), dismissing
934− * the notification while the original server's tool stays paused forever. Reporting
935− * failure instead leaves the notification up so the user can switch back and retry. */
936− open fun respondToPermissionFromNotification(
937− sessionId: String,
938− permissionId: String,
939− response: PermissionResponse,
940− profileId: String?,
941− onDone: (Boolean) -> Unit,
942− ) {
943− appScope.launch {
944− // Guarantee onDone (so the BroadcastReceiver's goAsync() finishes) even if the
945− // scope is cancelled mid-call (process shutdown cancels appScope first). Without
946− // this, a cancelled scope leaves pending.finish() never called → a receiver ANR
947− // and the permission response silently lost.
948− var success = false
949− try {
950− success = runCatchingCancellable {
951− val conn = activeConnection.value ?: return@runCatchingCancellable false
952− // Route to the originating server only. A mismatch means the user
953− // switched servers while the permission was pending; sending the reply
954− // to the wrong server would be silently swallowed as a 404-success.
955− if (profileId != null && conn.profile.id != profileId) return@runCatchingCancellable false
956− conn.api.respondPermission(sessionId, permissionId, response)
957− true
958− }.onFailure {
959− Log.w("AppContainer", "notif permission respond failed: ${safeExceptionSummary(it)}")
960− }.getOrDefault(false)
961− } finally {
962− onDone(success)
963− }
964− }
965− }
966−
967− /** Send a follow-up prompt from a notification's inline reply, off any UI. Uses the
968− * server's default model/agent. Routes through the durable [outboxStore] — the same path
969− * the in-app composer uses ([soy.iko.opencode.ui.chat.ChatViewModel.enqueueOffline]) —
970− * rather than a direct repository send, so a reply composed while disconnected survives to
971− * be flushed on reconnect instead of being silently dropped. [flushOutbox] nudges an
972− * immediate send when a connection is live, so an online reply still goes out now. [onDone]
973− * reports whether the reply was durably enqueued so the receiver only dismisses the
974− * notification on success. */
975− open fun sendPromptFromNotification(sessionId: String, text: String, originProfileId: String?, onDone: (Boolean) -> Unit) {
976− appScope.launch {
977− // Guarantee onDone (so the BroadcastReceiver's goAsync() finishes) even if the
978− // scope is cancelled mid-call — see respondToPermissionFromNotification above.
979− var enqueued = false
980− try {
981− // Attribute to the profile that POSTED the notification (embedded in the reply
982− // intent) so the follow-up is always enqueued against the server that owns
983− // [sessionId] — never whichever server happens to be active now, which would POST
984− // A's session id to B, 404, and silently drop the reply. Fall back to the active/
985− // most-recent profile only for a legacy intent that predates the embedded id.
986− val profileId = originProfileId
987− ?: activeConnection.value?.profile?.id
988− ?: runCatchingCancellable { profileStore.profiles.first().firstOrNull()?.id }.getOrNull()
989− enqueued = if (profileId == null) {
990− false
991− } else {
992− runCatchingCancellable {
993− outboxStore.enqueue(
994− OutboxMessage(
995− id = java.util.UUID.randomUUID().toString(),
996− profileId = profileId,
997− sessionId = sessionId,
998− text = text,
999− model = null,
1000− createdAt = System.currentTimeMillis(),
1001− ),
1002− )
1003− }.onFailure {
1004− Log.w("AppContainer", "notif reply enqueue failed: ${safeExceptionSummary(it)}")
1005− }.isSuccess
1006− }
1007− if (enqueued) flushOutbox()
1008− } finally {
1009− onDone(enqueued)
1010− }
1011− }
1012− }
1013−
1014− /** Abort the active run for [sessionId] from a notification Stop action. Routes to the
1015− * originating profile (or the active connection) so the abort reaches the server that
1016− * owns the session. Runs on the app scope so it survives the BroadcastReceiver's lifetime. */
1017− open fun abortRunFromNotification(sessionId: String, originProfileId: String?, onDone: (Boolean) -> Unit) {
1018− appScope.launch {
1019− var success = false
1020− try {
1021− val conn = activeConnection.value?.takeIf {
1022− originProfileId == null || it.profile.id == originProfileId
1023− } ?: activeConnection.value
1024− if (conn != null) {
1025− success = runCatchingCancellable { conn.repository.abort(sessionId) }.isSuccess
1026− }
1027− } finally {
1028− onDone(success)
1029− }
1030− }
1031− }
1032−
1033− /**
1034− * Retry the last user prompt for [sessionId] from an error notification's "Retry last"
1035− * action. Fetches the session's messages, re-sends the most recent user prompt, and
1036− * cancels the error notification on success. Routes to the originating profile's
1037− * connection (falling back to the active one) so the send reaches the server that owns
1038− * the session. A no-op (reported as false) when there's no connection or no prior prompt.
1039− */
1040− open fun retryLastFromNotification(sessionId: String, originProfileId: String?, onDone: (Boolean) -> Unit) {
1041− appScope.launch {
1042− var success = false
1043− try {
1044− val conn = activeConnection.value?.takeIf {
1045− originProfileId == null || it.profile.id == originProfileId
1046− } ?: activeConnection.value
1047− if (conn != null) {
1048− success = runCatchingCancellable {
1049− val messages = conn.api.listMessages(sessionId)
1050− val lastPrompt = messages
1051− .lastOrNull { it.info is soy.iko.opencode.data.model.UserMessage }
1052− ?.parts
1053− ?.filterIsInstance<soy.iko.opencode.data.model.TextPart>()
1054− ?.joinToString("\n\n") { it.text }
1055− ?.takeIf { it.isNotBlank() }
1056− if (lastPrompt != null) {
1057− // model=null lets the server reuse the session's current model; we
1058− // don't know the originally-selected model from a notification context.
1059− conn.repository.sendPrompt(sessionId, lastPrompt, model = null)
1060− true
1061− } else {
1062− false
1063− }
1064− }.isSuccess
1065− }
1066− } finally {
1067− onDone(success)
1068− }
1069− }
1070− }
1071−
1072− /** Extract the session id an event pertains to, for message-activity events. */
1073− private fun sessionOf(event: BusEvent): String? = sessionOfEvent(event)
1074−
1075− /**
1076− * On cold start, transparently reconnect to the most recently used server so a
1077− * returning user lands in their session list instead of the empty server screen.
1078− */
1079− private suspend fun autoConnect() {
1080− val recent = runCatchingCancellable { profileStore.profiles.first() }
1081− .getOrDefault(emptyList())
1082− .firstOrNull() ?: return
1083− // The profile read above suspends on DataStore. A manual connect() to a different
1084− // server during that window establishes a connection the user explicitly chose; we must
1085− // not clobber it by connecting to `recent` on top. connectIfIdle() checks "is anything
1086− // active?" and connects atomically under connectionMutex, returning null if the cold-start
1087− // slot was already taken — closing the TOCTOU window an unlocked null-check plus connect()'s
1088− // unconditional close would leave. (disconnectIf below similarly guards the failed-ping
1089− // teardown by identity.)
1090− _reconnecting.value = true
1091− var conn: OpencodeConnection? = null
1092− try {
1093− val ok = runCatchingCancellable {
1094− conn = connectIfIdle(recent) ?: return@runCatchingCancellable false
1095− conn!!.api.ping()
1096− true
1097− }.getOrDefault(false)
1098− when {
1099− conn == null -> Unit // slot already taken by a manual connect — leave it be
1100− ok -> _autoConnectDone.value = true
1101− else -> disconnectIf(conn!!)
1102− }
1103− } finally {
1104− // Reset in a finally so a CancellationException (e.g. scope cancelled during
1105− // shutdown) can't leave the flag pinned true — runCatchingCancellable rethrows it,
1106− // skipping the line below the try block.
1107− _reconnecting.value = false
1108− }
1109− }
1110−
1111− /**
1112− * When the device regains connectivity, nudge the active SSE stream to reconnect
1113− * immediately instead of waiting out the exponential backoff.
1114− */
1115− private val networkCallback: ConnectivityManager.NetworkCallback? = registerNetworkMonitor()
1116−
1117− private fun registerNetworkMonitor(): ConnectivityManager.NetworkCallback? {
1118− if (appContext == null) return null
1119− val cm = appContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
1120− ?: return null
1121− // Seed the online state from the current active network so the indicator is
1122− // correct on cold start rather than defaulting to "online" until a callback fires.
1123− _isOnline.value = runCatching { cm.activeNetwork != null }.getOrDefault(true)
1124− val callback = object : ConnectivityManager.NetworkCallback() {
1125− override fun onAvailable(network: Network) { _isOnline.value = true; activeConnection.value?.events?.triggerReconnect() }
1126− // A matched (internet-capable) network was lost. Don't eagerly flip offline: during a
1127− // Wi-Fi→cellular handoff onLost(WiFi) fires before onAvailable(cellular) and
1128− // cm.activeNetwork is transiently null in that window — flashing offline there would
1129− // skip outbox flushing and blink the indicator. Instead re-check activeNetwork after a
1130− // short grace period and only report offline if there's still no active network.
1131− //
1132− // This MUST live in onLost, not onUnavailable: onUnavailable is delivered only for
1133− // requestNetwork() with a timeout, never for registerNetworkCallback() — relying on it
1134− // (as this once did) meant offline was never detected after the first onAvailable.
1135− override fun onLost(network: Network) {
1136− appScope.launch {
1137− delay(NetworkConfig.networkOfflineGraceMs)
1138− _isOnline.value = runCatching { cm.activeNetwork != null }.getOrDefault(true)
1139− }
1140− }
1141− }
1142− // Only match networks that actually provide internet — a capability-less request
1143− // fires onAvailable for transports that can't reach the server (and would trigger
1144− // spurious reconnects), so require NET_CAPABILITY_INTERNET.
1145− val request = NetworkRequest.Builder()
1146− .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
1147− .build()
1148− runCatching { cm.registerNetworkCallback(request, callback) }
1149− .onFailure { Log.w("AppContainer", "Failed to register network callback", it) }
1150− return callback
1151− }
1152−
1153− /** Open (or re-open) a connection to [profile], replacing any current one.
1154− * Only persists the updated `lastUsed` timestamp if it's stale (older than a
1155− * minute), so rapid reconnect storms don't each trigger a DataStore write. */
1156− open suspend fun connect(profile: ServerProfile): OpencodeConnection =
1157− connectionMutex.withLock { connectLocked(profile) }
1158−
1159− /** Connect to the profile with [profileId], looking it up from [profileStore]. Returns
1160− * true on success, false if the profile wasn't found or connect threw. Used by the
1161− * notification body-tap path to route a session open back to the originating server. */
1162− open suspend fun connectByProfileId(profileId: String): Boolean {
1163− val profile = profileStore.profiles.first().find { it.id == profileId } ?: return false
1164− return runCatchingCancellable { connect(profile) }.isSuccess
1165− }
1166−
1167− /** Connect to [profile] only if nothing is currently active, checking-and-connecting
1168− * atomically under [connectionMutex]. Returns null (touching nothing) when a connection is
1169− * already active, so autoConnect() can't clobber a manual connect() the user made during its
1170− * suspending profile read — closing the TOCTOU window an unlocked null-check would leave. */
1171− private suspend fun connectIfIdle(profile: ServerProfile): OpencodeConnection? =
1172− connectionMutex.withLock {
1173− if (_activeConnection.value != null) null else connectLocked(profile)
1174− }
1175−
1176− /** Build and install a connection to [profile], replacing any current one. Caller MUST hold
1177− * [connectionMutex]. */
1178− private suspend fun connectLocked(profile: ServerProfile): OpencodeConnection {
1179− // Capture the previous profile id before closing, so we can preserve unread badges
1180− // when reconnecting to the same server — a brief network blip or manual reconnect
1181− // shouldn't erase "5 unread". Only a genuine server switch clears them.
1182− val previousProfileId = _activeConnection.value?.profile?.id
1183− _activeConnection.value?.close()
1184− _activeConnection.value = null
1185− // Mutate the run set and its derived flag together under activeRuns' monitor: the SSE
1186− // event handler adds ids under the same lock, so an unlocked clear() here could
1187− // interleave with an add()+flag=true and leave _anyRunActive pinned true with a torn-
1188− // down connection and no SessionIdle to clear it — a stuck foreground service.
1189− synchronized(activeRuns) {
1190− activeRuns.clear()
1191− publishRunState()
1192− }
1193− if (previousProfileId != profile.id) {
1194− _unread.value = emptyMap()
1195− unreadMessageIds.clear()
1196− }
1197− val now = System.currentTimeMillis()
1198− val resolved = profileStore.resolve(profile)
1199− val needsSave = (now - resolved.lastUsed) > LAST_USED_SAVE_THRESHOLD_MS
1200− val finalProfile = if (needsSave) resolved.copy(lastUsed = now) else resolved
1201− if (needsSave) profileStore.save(finalProfile)
1202− return OpencodeConnection(finalProfile, messageCacheStore).also { _activeConnection.value = it }
1203− }
1204−
1205− open suspend fun disconnect() {
1206− // Acquire the connection mutex so disconnect is serialized with connect().
1207− // Previously this was fire-and-forget (launch on appScope), which raced with
1208− // a subsequent connect(): connect() could acquire the mutex, create a new
1209− // connection, and then the pending disconnect() would close it.
1210− connectionMutex.withLock { teardownActiveLocked() }
1211− }
1212−
1213− /** Tear down [expected] only if it is still the active connection, with the identity
1214− * check performed *under* the mutex. A caller that checks `activeConnection.value === x`
1215− * itself and then calls [disconnect] has a TOCTOU race: a concurrent connect() to a
1216− * different server can replace the active connection in the gap, and [disconnect] would
1217− * then close that new connection. autoConnect()'s failed-ping teardown uses this. */
1218− private suspend fun disconnectIf(expected: OpencodeConnection) {
1219− connectionMutex.withLock {
1220− if (_activeConnection.value === expected) teardownActiveLocked()
1221− }
1222− }
1223−
1224− /** Close and reset the active connection. Caller MUST hold [connectionMutex]. */
1225− private suspend fun teardownActiveLocked() {
1226− _activeConnection.value?.close()
1227− _activeConnection.value = null
1228− // Reset run/unread state on disconnect too. With no SSE stream there's no
1229− // SessionIdle to drain activeRuns, so without this the working indicator
1230− // (anyRunActive) and unread badges would stay pinned until the next connect().
1231− // Mutate under activeRuns' monitor (see connect()) so a concurrent SSE add() can't
1232− // re-pin _anyRunActive after the clear.
1233− synchronized(activeRuns) {
1234− activeRuns.clear()
1235− publishRunState()
1236− }
1237− _unread.value = emptyMap()
1238− unreadMessageIds.clear()
1239− }
1240−
1241− /** Deferred profile deletions keyed by id, run on the process-lived [appScope] (not a
1242− * ViewModel scope) so navigating away during the undo window still commits the delete
1243− * instead of silently cancelling it — mirroring [CrashLogger.scheduleDelete]. */
1244− private val pendingProfileDeletes = java.util.concurrent.ConcurrentHashMap<String, Job>()
1245−
1246− /**
1247− * Schedule the profile [id] for deletion after [delayMs], cancellable via
1248− * [cancelProfileDelete] (the Undo action). [onDeleted]/[onError] run on [appScope]
1249− * after the delete resolves so the caller can clear its optimistic-hide state. A
1250− * repeated schedule for the same id replaces the prior timer.
1251− */
1252− open fun scheduleProfileDelete(
1253− id: String,
1254− delayMs: Long,
1255− onDeleted: () -> Unit,
1256− onError: (Throwable) -> Unit,
1257− ) {
1258− val job = appScope.launch {
1259− delay(delayMs)
1260− // Claim the delete by removing our own entry BEFORE committing it — the atomic
1261− // remove is the sync point with cancelProfileDelete. Losing the race (an undo
1262− // removed us first) means we skip, honouring cancel's `true`; deleting first
1263− // would let a cancel land in the gap and falsely report undo of a gone profile.
1264− // remove(id, thisJob) also no-ops for a stale job after a reschedule.
1265− val claimed = coroutineContext[Job]?.let { pendingProfileDeletes.remove(id, it) } == true
1266− if (!claimed) return@launch
1267− runCatchingCancellable { profileStore.delete(id) }
1268− .onSuccess { onDeleted() }
1269− .onFailure { onError(it) }
1270− }
1271− pendingProfileDeletes[id]?.cancel()
1272− pendingProfileDeletes[id] = job
1273− }
1274−
1275− /** Cancel a pending deferred profile delete (the Undo action). Returns true if it was
1276− * still pending (undo succeeded), false if the delete had already fired. */
1277− open fun cancelProfileDelete(id: String): Boolean {
1278− val job = pendingProfileDeletes.remove(id) ?: return false
1279− job.cancel()
1280− return true
1281− }
1282−
1283− /** Deferred session deletions keyed by id, run on the process-lived [appScope] (not a
1284− * ViewModel scope) so navigating away during the undo window still commits the delete
1285− * instead of silently cancelling it (which would leave the session deleted-in-UI but
1286− * alive on the server, reappearing on the next refresh). */
1287− private val pendingSessionDeletes = java.util.concurrent.ConcurrentHashMap<String, Job>()
1288−
1289− /** One-shot events carrying the id of a session scheduled for deferred deletion from
1290− * outside the session list (e.g. from the chat screen's Delete). The SessionListScreen
1291− * collects these to show an Undo snackbar, mirroring its own VM-level undo events. */
1292− private val _externalSessionUndoEvents = MutableSharedFlow<String>(
1293− extraBufferCapacity = NetworkConfig.snackbarEventBufferCapacity,
1294− onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
1295− )
1296− val externalSessionUndoEvents: SharedFlow<String> = _externalSessionUndoEvents.asSharedFlow()
1297−
1298− /** Emit an undo event for a session delete initiated outside the session list (e.g.
1299− * from the chat screen). The SessionListScreen collects these to show an Undo snackbar. */
1300− fun emitExternalSessionUndo(sessionId: String) {
1301− _externalSessionUndoEvents.tryEmit(sessionId)
1302− }
1303−
1304− /**
1305− * Schedule session [id] for deletion after [delayMs], cancellable via [cancelSessionDelete]
1306− * (the Undo action). Also clears the session's stored draft on a successful delete.
1307− * [onDeleted]/[onError] run on [appScope] after the delete resolves so the caller can update
1308− * its optimistic-hide state. A repeated schedule for the same id replaces the prior timer.
1309− *
1310− * The owning connection is captured now, at schedule time — NOT re-resolved when the timer
1311− * fires. Otherwise a server switch during the undo window would send the delete to whichever
1312− * server happens to be active at fire time: the original session would never be deleted (its
1313− * row reappears on the next refresh) and, in the rare id-collision case, an unrelated session
1314− * on the new server could be deleted instead. A disconnect closes the captured connection's
1315− * HTTP client, so a delete deferred across a disconnect fails and is surfaced via [onError]
1316− * (the session cannot be deleted on a server we're no longer connected to). No-ops (as an
1317− * error) if there is no active connection at schedule time.
1318− */
1319− open fun scheduleSessionDelete(
1320− id: String,
1321− delayMs: Long,
1322− onDeleted: () -> Unit,
1323− onError: (Throwable) -> Unit,
1324− ) {
1325− val conn = _activeConnection.value
1326− val job = appScope.launch {
1327− delay(delayMs)
1328− // Claim the delete by removing our own entry BEFORE committing it — the atomic
1329− // remove is the sync point with cancelSessionDelete. Losing the race (an undo
1330− // removed us first) means we skip, honouring cancel's `true`; deleting first
1331− // would let a cancel land in the gap and falsely report undo of a gone session.
1332− // remove(id, thisJob) also no-ops for a stale job after a reschedule.
1333− val claimed = coroutineContext[Job]?.let { pendingSessionDeletes.remove(id, it) } == true
1334− if (!claimed) return@launch
1335− if (conn == null) {
1336− onError(IllegalStateException("No active connection"))
1337− } else {
1338− runCatchingCancellable { conn.repository.deleteSession(id) }
1339− .onSuccess {
1340− draftStore.remove(id)
1341− attachmentDraftStore.remove(id)
1342− sessionPrefsStore.forget(id)
1343− messageCacheStore.remove(conn.profile.id, id)
1344− outboxStore.removeForSession(id)
1345− clearUnread(id)
1346− onDeleted()
1347− }
1348− .onFailure { onError(it) }
1349− }
1350− }
1351− pendingSessionDeletes[id]?.cancel()
1352− pendingSessionDeletes[id] = job
1353− }
1354−
1355− /** Cancel a pending deferred session delete (the Undo action). Returns true if it was
1356− * still pending (undo succeeded), false if the delete had already fired. */
1357− open fun cancelSessionDelete(id: String): Boolean {
1358− val job = pendingSessionDeletes.remove(id) ?: return false
1359− job.cancel()
1360− return true
1361− }
1362−
1363− /**
1364− * Probe a server URL (without credentials) to check reachability and detect whether
1365− * the server requires authentication. Builds a short-lived HTTP client with the same
1366− * base URL normalization as [connect] but no auth, calls the health endpoint, and
1367− * classifies the outcome:
1368− *
1369− * - 2xx → [ProbeResult.Reachable] (no auth needed)
1370− * - 401/403 → [ProbeResult.NeedsAuth]
1371− * - anything else → [ProbeResult.Unreachable] with a user-facing message
1372− *
1373− * The probe client is always closed afterwards so no resources linger. This does not
1374− * touch the active connection or the profile store.
1375− */
1376− open suspend fun probeServer(baseUrl: String, requireHttps: Boolean, certPin: String?): ProbeResult {
1377− return probeWithProfile(ServerProfile(
1378− id = "probe",
1379− label = "",
1380− baseUrl = baseUrl.trim(),
1381− username = null,
1382− password = null,
1383− // Probe the same effective URL save()/connect() will use: HttpClientFactory upgrades
1384− // http->https and installs the cert pinner when these are set, so a probe without them
1385− // would validate a plain-http endpoint the real connection never talks to.
1386− requireHttps = requireHttps,
1387− certPin = certPin,
1388− ))
1389− }
1390−
1391− /**
1392− * Probe a server URL *with* credentials to validate them. Returns true if the
1393− * server accepts the credentials (ping succeeds), false on 401/403, and throws
1394− * on other failures (unreachable, timeout) so the caller can surface a friendly
1395− * message. Mirrors [probeServer]'s short-lived-client pattern.
1396− */
1397− open suspend fun probeWithCredentials(
1398− baseUrl: String,
1399− username: String,
1400− password: String,
1401− requireHttps: Boolean,
1402− certPin: String?,
1403− ): Boolean {
1404− val probeProfile = ServerProfile(
1405− id = "probe-auth",
1406− label = "",
1407− baseUrl = baseUrl.trim(),
1408− username = username.trim().takeIf { it.isNotBlank() },
1409− password = password.trim().takeIf { it.isNotEmpty() },
1410− // Match the effective URL/pinning save()/connect() will use (see probeServer).
1411− requireHttps = requireHttps,
1412− certPin = certPin,
1413− )
1414− val client = HttpClientFactory.create(probeProfile)
1415− return try {
1416− val api = OpencodeApiClient(client)
1417− api.ping()
1418− true
1419− } catch (c: kotlinx.coroutines.CancellationException) {
1420− throw c
1421− } catch (e: Exception) {
1422− val status = responseStatusCode(e)
1423− if (status == 401 || status == 403) false else throw e
1424− } finally {
1425− runCatching { client.close() }
1426− }
1427− }
1428−
1429− private suspend fun probeWithProfile(profile: ServerProfile): ProbeResult {
1430− val client = HttpClientFactory.create(profile)
1431− return try {
1432− val api = OpencodeApiClient(client)
1433− api.ping()
1434− ProbeResult.Reachable
1435− } catch (c: kotlinx.coroutines.CancellationException) {
1436− throw c
1437− } catch (e: Exception) {
1438− val status = responseStatusCode(e)
1439− if (status == 401 || status == 403) {
1440− ProbeResult.NeedsAuth
1441− } else {
1442− ProbeResult.Unreachable(friendlyErrorFor(e, profile.baseUrl))
1443− }
1444− } finally {
1445− runCatching { client.close() }
1446− }
1447− }
1448−
1449− // Declared last so every property above is fully initialized before these observers start.
1450− // They only launch coroutines into appScope (Dispatchers.IO) — nothing here runs
1451− // synchronously during construction — so placing init at the end removes any dependence on
1452− // the textual declaration order of the fields those observers reference.
1453− init {
1454− if (!skipInit) {
1455− NotificationChannels.create(appContext!!)
1456− observeMessageActivity()
1457− observeRunReconcileOnReconnect()
1458− observeRunForegroundService()
1459− observeBackgroundedConnectionFailures()
1460− // Load the persisted muted-sessions set so isSessionMuted() reflects the choice
1461− // immediately on cold start (before any session list composition).
1462− appScope.launch {
1463− runCatchingCancellable {
1464− sessionPrefsStore.muted.collect { ids -> _mutedSessions.value = ids }
1465− }
1466− }
1467− // Flush right after load() populates the queue. observeOutbox()'s combine is keyed
1468− // on activeConnection/isOnline/_outboxFlushTrigger — NOT on outboxStore.messages — so
1469− // if connect() sets activeConnection before load() finishes reading a (possibly
1470− // multi-MB) outbox.json, the connect-triggered flush sees an empty queue and nothing
1471− // re-triggers it. Nudging the flush here guarantees a loaded queue is sent.
1472− appScope.launch {
1473− runCatchingCancellable { outboxStore.load() }
1474− flushOutbox()
1475− }
1476− observeOutbox()
1477− appScope.launch { autoConnect() }
1478− }
1479− }
1480−}
1481−
1482−/**
1483− * Extract the session id a message-activity event pertains to, or null for events that
1484− * don't describe message activity. This drives the unread badge: any session that
1485− * receives activity while it isn't the currently-viewed one gets badged. Extracted as
1486− * a top-level `internal` function so the rule is unit-testable without an Android
1487− * [Context] (the surrounding [AppContainer] needs one).
1488− */
1489−internal fun sessionOfEvent(event: BusEvent): String? = when (event) {
1490− is MessageUpdated -> event.properties.info.sessionID
1491− is MessagePartUpdated -> event.properties.part.sessionID ?: event.properties.sessionID
1492− else -> null
1493−}
1494−
1495−/**
1496− * The message id a message-activity event pertains to, used to de-duplicate the unread
1497− * badge so a reply's many streaming events count once. Null for events that carry no
1498− * message id (those fall back to being counted individually).
1499− */
1500−internal fun messageIdOfEvent(event: BusEvent): String? = when (event) {
1501− is MessageUpdated -> event.properties.info.id
1502− is MessagePartUpdated -> event.properties.messageID ?: event.properties.part.messageID
1503− else -> null
1504−}
app/src/main/java/soy/iko/opencode/di/OpencodeConnection.ktdeleted−47
@@ -1,47 +0,0 @@
1−package soy.iko.opencode.di
2−
3−import soy.iko.opencode.data.model.ServerProfile
4−import soy.iko.opencode.data.network.EventStreamClient
5−import soy.iko.opencode.data.network.HttpClientFactory
6−import soy.iko.opencode.data.network.OpencodeApiClient
7−import soy.iko.opencode.data.repo.MessageCacheStore
8−import soy.iko.opencode.data.repo.SessionRepository
9−import kotlinx.coroutines.CoroutineScope
10−import kotlinx.coroutines.Dispatchers
11−import kotlinx.coroutines.SupervisorJob
12−import kotlinx.coroutines.cancel
13−
14−/**
15− * An active connection to one opencode server. Bundles the Ktor client, REST API,
16− * SSE event stream, and the reducing repository, all sharing a connection-scoped
17− * coroutine scope that is cancelled on [close].
18− */
19−open class OpencodeConnection(
20− val profile: ServerProfile,
21− // Optional on-disk message cache, supplied by AppContainer, so conversations render
22− // instantly and stay readable offline. Null in the test constructor.
23− private val messageCache: MessageCacheStore? = null,
24−) {
25−
26− protected constructor() : this(ServerProfile(id = "", label = "", baseUrl = "http://localhost"), null)
27−
28− private val scopeJob = SupervisorJob()
29− private val scope by lazy { CoroutineScope(scopeJob + Dispatchers.IO) }
30− private val client by lazy { HttpClientFactory.create(profile) }
31−
32− open val api: OpencodeApiClient by lazy { OpencodeApiClient(client) }
33− open val events: EventStreamClient by lazy { EventStreamClient(client, scope) }
34− open val repository: SessionRepository by lazy { SessionRepository(api, events, messageCache, profile.id) }
35−
36− /**
37− * Cancel the coroutine scope and wait for in-flight work (including the SSE reader)
38− * to wind down before closing the HTTP client. Calling client.close() while the SSE
39− * coroutine is still mid-request produces a spurious "stream error, will retry"
40− * warning during normal teardown.
41− */
42− open suspend fun close() {
43− scope.cancel()
44− scopeJob.join()
45− runCatching { client.close() }
46− }
47−}
app/src/main/java/soy/iko/opencode/notification/NotificationActionReceiver.ktdeleted−195
@@ -1,195 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.content.BroadcastReceiver
4−import android.content.Context
5−import android.content.Intent
6−import androidx.core.app.RemoteInput
7−import soy.iko.opencode.OpencodeApp
8−import soy.iko.opencode.R
9−import soy.iko.opencode.data.model.PermissionResponse
10−import soy.iko.opencode.data.network.NetworkConfig
11−import java.util.concurrent.atomic.AtomicBoolean
12−
13−/**
14− * Handles the action buttons on the app's notifications so the user can respond without
15− * opening the app — the core of the "kick it off and walk away" flow:
16− *
17− * - [ACTION_PERMISSION] with a [PermissionResponse] → replies to a paused tool's permission
18− * request (Allow once / Always / Reject) via the active connection.
19− * - [ACTION_REPLY] with a [RemoteInput] text payload → sends a follow-up prompt to a session
20− * that just finished a run.
21− *
22− * The receiver is not exported (see the manifest); the [PendingIntent]s that target it are
23− * created by the app itself. Work is done on the process-lived app scope via [OpencodeApp]'s
24− * container, and [goAsync] keeps the receiver alive until the (network) call resolves.
25− *
26− * A watchdog finishes the [PendingResult] within [NetworkConfig.notificationReceiverTimeoutMs]
27− * so a slow network call (e.g. a permission respond retried with exponential backoff) can't
28− * ANR the receiver. The underlying call keeps running on the app scope; only the receiver's
29− * lifetime is bounded. [finishOnce] guards against a double finish() (which would throw).
30− */
31−class NotificationActionReceiver : BroadcastReceiver() {
32−
33− override fun onReceive(context: Context, intent: Intent) {
34− val container = (context.applicationContext as? OpencodeApp)?.container ?: return
35− if (intent.action == ACTION_STOP_RUN) {
36− handleStopRun(context, container, intent)
37− return
38− }
39− val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() } ?: return
40− when (intent.action) {
41− ACTION_MARK_READ -> {
42− // "Mark read" from a completion notification — clear the unread badge and
43− // dismiss the notification without opening the session.
44− container.markSessionRead(sessionId)
45− SessionNotifications.cancel(context, sessionId)
46− return
47− }
48− ACTION_PERMISSION -> {
49− val permissionId = intent.getStringExtra(EXTRA_PERMISSION_ID)?.takeIf { it.isNotBlank() } ?: return
50− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
51− val response = PermissionResponse.entries.firstOrNull {
52− it.wire == intent.getStringExtra(EXTRA_RESPONSE)
53− } ?: return
54− val pending = goAsync()
55− val finished = AtomicBoolean(false)
56− var watchdogThread: Thread? = null
57− val finishOnce = {
58− if (finished.compareAndSet(false, true)) {
59− watchdogThread?.interrupt()
60− pending.finish()
61− }
62− }
63− watchdogThread = watchdog(finishOnce)
64− container.respondToPermissionFromNotification(sessionId, permissionId, response, profileId) { success ->
65− // Only dismiss the notification once the tool was actually answered. If
66− // there was no live connection (respond is a no-op) or the call failed,
67− // leave it up so the user can retry — otherwise it vanishes with the
68− // permission request left unanswered.
69− if (success) SessionNotifications.cancelPermission(context, sessionId)
70− finishOnce()
71− }
72− }
73− ACTION_REPLY -> {
74− val text = RemoteInput.getResultsFromIntent(intent)
75− ?.getCharSequence(KEY_REPLY_TEXT)?.toString()?.trim()
76− ?.takeIf { it.isNotEmpty() }
77− if (text == null) {
78− // The RemoteInput fired but the reply was empty/whitespace. SystemUI locks the
79− // inline field in a "sending…" state until the notification is updated or
80− // cancelled — cancel it so the field doesn't stay stuck with nothing to send.
81− SessionNotifications.cancel(context, sessionId)
82− return
83− }
84− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
85− val pending = goAsync()
86− val finished = AtomicBoolean(false)
87− var watchdogThread: Thread? = null
88− val finishOnce = {
89− if (finished.compareAndSet(false, true)) {
90− watchdogThread?.interrupt()
91− pending.finish()
92− }
93− }
94− watchdogThread = watchdog(finishOnce)
95− container.sendPromptFromNotification(sessionId, text, profileId) { enqueued ->
96− // The reply is durably queued (and flushed now if online). Show a brief
97− // "Sent" confirmation by updating the completion notification's text, then
98− // let it auto-cancel on tap — instead of vanishing silently. If the enqueue
99− // failed, post a "reply not sent" error: leaving the completion notification
100− // up strands SystemUI's RemoteInput field in a permanent "sending…" spinner
101− // that can't be resubmitted, so "leave it up to retry" doesn't actually let
102− // the user retry.
103− if (enqueued) {
104− SessionNotifications.postReplySent(context, sessionId)
105− } else {
106− SessionNotifications.postReplyFailed(context, sessionId, profileId)
107− }
108− finishOnce()
109− }
110− }
111− ACTION_RETRY_LAST -> {
112− // "Retry last" from an error notification: re-send the most recent user prompt
113− // for this session without opening the app. Cancels the error notification on
114− // success so the user sees the retry took effect.
115− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
116− val pending = goAsync()
117− val finished = AtomicBoolean(false)
118− var watchdogThread: Thread? = null
119− val finishOnce = {
120− if (finished.compareAndSet(false, true)) {
121− watchdogThread?.interrupt()
122− pending.finish()
123− }
124− }
125− watchdogThread = watchdog(finishOnce)
126− container.retryLastFromNotification(sessionId, profileId) { success ->
127− if (success) SessionNotifications.cancel(context, sessionId)
128− finishOnce()
129− }
130− }
131− }
132− }
133−
134− /** Handle the Stop action from the foreground-service notification. Extracted from
135− * [onReceive] to keep that function's cyclomatic complexity under detekt's threshold. */
136− private fun handleStopRun(context: Context, container: soy.iko.opencode.di.AppContainer, intent: Intent) {
137− // The session id may be absent if multiple runs were active (generic notification);
138− // in that case we can't target a specific run — just let it ride.
139− val sessionId = intent.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() } ?: return
140− val profileId = intent.getStringExtra(EXTRA_PROFILE_ID)?.takeIf { it.isNotBlank() }
141− val pending = goAsync()
142− val finished = AtomicBoolean(false)
143− var watchdogThread: Thread? = null
144− val finishOnce = {
145− if (finished.compareAndSet(false, true)) {
146− watchdogThread?.interrupt()
147− pending.finish()
148− }
149− }
150− watchdogThread = watchdog(finishOnce)
151− container.abortRunFromNotification(sessionId, profileId) { success ->
152− // On a failed abort (transient network error), the run continues but the FGS
153− // notification will disappear once anyRunActive clears — leaving the user with
154− // no signal that their Stop tap didn't take. Post a quick "couldn't stop"
155− // notification so they know to open the app. On success, the FGS disappearing
156− // is sufficient feedback.
157− if (!success) {
158− SessionNotifications.postError(
159− context, sessionId,
160− context.getString(R.string.couldnt_stop_run),
161− profileId,
162− )
163− }
164− finishOnce()
165− }
166− }
167−
168− /** Schedule a deadline after which the receiver's [PendingResult] is finished even if
169− * the network call hasn't resolved, so the system can't ANR the receiver. The
170− * underlying work continues on the app scope. Returns the watchdog thread so the
171− * caller can [interrupt][Thread.interrupt] it when work completes early, releasing
172− * the sleeping thread immediately instead of leaving it for the full timeout. */
173− private fun watchdog(finishOnce: () -> Unit): Thread =
174− Thread {
175− try {
176− Thread.sleep(NetworkConfig.notificationReceiverTimeoutMs)
177− } catch (_: InterruptedException) {
178− return@Thread
179− }
180− finishOnce()
181− }.apply { isDaemon = true; name = "notif-receiver-watchdog"; start() }
182−
183− companion object {
184− const val ACTION_PERMISSION = "soy.iko.opencode.action.PERMISSION"
185− const val ACTION_REPLY = "soy.iko.opencode.action.REPLY"
186− const val ACTION_STOP_RUN = "soy.iko.opencode.action.STOP_RUN"
187− const val ACTION_MARK_READ = "soy.iko.opencode.action.MARK_READ"
188− const val ACTION_RETRY_LAST = "soy.iko.opencode.action.RETRY_LAST"
189− const val EXTRA_SESSION_ID = "soy.iko.opencode.extra.SESSION_ID"
190− const val EXTRA_PERMISSION_ID = "soy.iko.opencode.extra.PERMISSION_ID"
191− const val EXTRA_PROFILE_ID = "soy.iko.opencode.extra.PROFILE_ID"
192− const val EXTRA_RESPONSE = "soy.iko.opencode.extra.RESPONSE"
193− const val KEY_REPLY_TEXT = "soy.iko.opencode.key.REPLY_TEXT"
194− }
195−}
app/src/main/java/soy/iko/opencode/notification/NotificationChannels.ktdeleted−65
@@ -1,65 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.app.NotificationChannel
4−import android.app.NotificationManager
5−import android.content.Context
6−import soy.iko.opencode.R
7−
8−/**
9− * The app's notification channels. Created once at startup (idempotent — recreating an
10− * existing channel is a no-op). Two channels keep user control granular:
11− *
12− * - [STATUS]: low-importance, no sound. Used by the foreground service's persistent
13− * "agent running" indicator.
14− * - [COMPLETED]: default importance. Used when a background session finishes a run.
15− * - [PERMISSION]: high importance (heads-up + sound). Used when a paused tool run needs
16− * the user's approval — the whole point is to reach the user who has walked away, so it
17− * interrupts rather than sitting silently in the shade.
18− * - [ERROR]: default importance. Used when a background run fails.
19− */
20−object NotificationChannels {
21− const val STATUS = "run_status"
22− const val COMPLETED = "session_completed"
23− const val PERMISSION = "permission_request"
24− const val ERROR = "session_error"
25− const val UNREAD = "unread_badge"
26−
27− fun create(context: Context) {
28− val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
29− nm.createNotificationChannel(
30− NotificationChannel(STATUS, context.getString(R.string.notif_channel_status), NotificationManager.IMPORTANCE_LOW).apply {
31− description = context.getString(R.string.notif_channel_status_desc)
32− setShowBadge(false)
33− },
34− )
35− nm.createNotificationChannel(
36− NotificationChannel(COMPLETED, context.getString(R.string.notif_channel_completed), NotificationManager.IMPORTANCE_DEFAULT).apply {
37− description = context.getString(R.string.notif_channel_completed_desc)
38− },
39− )
40− nm.createNotificationChannel(
41− NotificationChannel(PERMISSION, context.getString(R.string.notif_channel_permission), NotificationManager.IMPORTANCE_HIGH).apply {
42− description = context.getString(R.string.notif_channel_permission_desc)
43− },
44− )
45− nm.createNotificationChannel(
46− // HIGH importance so a failed run stands out from a completed one by
47− // sound/vibration — both are actionable, but a failure is time-sensitive.
48− NotificationChannel(ERROR, context.getString(R.string.notif_channel_error), NotificationManager.IMPORTANCE_HIGH).apply {
49− description = context.getString(R.string.notif_channel_error_desc)
50− },
51− )
52− // A silent, badge-only channel that carries the launcher icon's unread count (the only
53− // way to badge the launcher icon on Android is via a notification on a badge-enabled
54− // channel). Low importance + no sound/vibration so it never alerts; setShowBadge(true)
55− // so its number renders on the launcher icon.
56− nm.createNotificationChannel(
57− NotificationChannel(UNREAD, context.getString(R.string.notif_channel_unread), NotificationManager.IMPORTANCE_MIN).apply {
58− description = context.getString(R.string.notif_channel_unread_desc)
59− setShowBadge(true)
60− setSound(null, null)
61− enableVibration(false)
62− },
63− )
64− }
65−}
app/src/main/java/soy/iko/opencode/notification/RunForegroundService.ktdeleted−210
@@ -1,210 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.app.Notification
4−import android.app.PendingIntent
5−import android.app.Service
6−import android.content.Context
7−import android.content.Intent
8−import android.content.pm.ServiceInfo
9−import android.os.Build
10−import android.os.IBinder
11−import android.util.Log
12−import android.annotation.SuppressLint
13−import androidx.core.app.NotificationCompat
14−import androidx.core.app.NotificationManagerCompat
15−import androidx.core.app.ServiceCompat
16−import soy.iko.opencode.MainActivity
17−import soy.iko.opencode.R
18−
19−/**
20− * A foreground service kept alive while an opencode agent is actively running. Holding a
21− * foreground priority lets the long-lived SSE `/event` subscription survive backgrounding
22− * (Doze/app-standby would otherwise choke the socket and stall streaming mid-run).
23− *
24− * The service is started when a run begins ([start]) and stopped when it goes idle
25− * ([stop]). It shows a low-importance "Agent is working…" notification in [NotificationChannels.STATUS].
26− * Started/stopped via Compose from the chat screen based on the `running` state.
27− */
28−class RunForegroundService : Service() {
29−
30− override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
31− // The session title (when a single run is active) is passed via the intent extra so
32− // the notification can identify which session is running, instead of a generic
33− // "Agent is working…". Null/blank falls back to the generic title.
34− val sessionTitle = intent?.getStringExtra(EXTRA_SESSION_TITLE)?.takeIf { it.isNotBlank() }
35− val sessionId = intent?.getStringExtra(EXTRA_SESSION_ID)?.takeIf { it.isNotBlank() }
36− val progress = intent?.getStringExtra(EXTRA_PROGRESS)?.takeIf { it.isNotBlank() }
37− // The service is re-started per progress update (AppContainer re-sends the intent on
38− // each _runProgressText change). Capture the wall-clock start of the *first* intent
39− // of this run and reuse it across rebuilds so the chronometer's base doesn't jump
40− // back to 0:00 every time the agent advances a step. Reset to 0 in onDestroy once
41− // the run ends (stop() → onDestroy) so the next run starts fresh.
42− if (runStartMillis == 0L) runStartMillis = System.currentTimeMillis()
43− val notification = buildNotification(sessionTitle, sessionId, progress)
44− // startForeground can throw ForegroundServiceStartNotAllowedException on
45− // Android 12+ if the app is in the background when the service starts. Wrap
46− // it so a backgrounded start (e.g. the user navigates away at the wrong
47− // moment) doesn't crash the app — the SSE stream will just continue without
48− // foreground priority and may be killed by the system sooner.
49− runCatching {
50− ServiceCompat.startForeground(
51− this,
52− NOTIF_ID,
53− notification,
54− if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
55− ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
56− } else {
57− 0
58− },
59− )
60− }.onFailure {
61− Log.w(TAG, "startForeground failed; running without foreground priority", it)
62− stopSelf()
63− }
64− return START_NOT_STICKY
65− }
66−
67− private fun mainContentIntent(): PendingIntent {
68− // Tapping the notification opens the app so the user can see the running session.
69− val openIntent = Intent(this, MainActivity::class.java).apply {
70− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
71− }
72− return PendingIntent.getActivity(
73− this, 0, openIntent,
74− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
75− )
76− }
77−
78− private fun buildNotification(sessionTitle: String?, sessionId: String?, progress: String? = null): Notification {
79− val pendingIntent = mainContentIntent()
80− val contentText = progress ?: sessionTitle ?: getString(R.string.notif_running_text)
81− val builder = NotificationCompat.Builder(this, NotificationChannels.STATUS)
82− .setSmallIcon(R.drawable.ic_stat_notify)
83− .setColor(brandColor(this))
84− .setContentTitle(getString(R.string.notif_running_title))
85− .setContentText(contentText)
86− .setContentIntent(pendingIntent)
87− .setOngoing(true)
88− // Show a live elapsed timer so the user can see how long the current run has
89− // been going — no per-tick plumbing needed; the system renders the chronometer.
90− // runStartMillis is captured once at the start of the run (see onStartCommand)
91− // and reused across progress-driven rebuilds so the chronometer base is stable.
92− .setWhen(runStartMillis)
93− .setUsesChronometer(true)
94− .setShowWhen(true)
95− .setPriority(NotificationCompat.PRIORITY_LOW)
96− .setCategory(NotificationCompat.CATEGORY_PROGRESS)
97− // An indeterminate progress bar so the notification reads as actively "in progress"
98− // at a glance (alongside the chronometer), matching the conventional run affordance.
99− .setProgress(0, 0, true)
100− // Add a Stop action so the user can cancel the run without opening the app — the
101− // core of the "kick it off and walk away" flow. Only when a specific session is
102− // known (multiple concurrent runs can't be targeted individually).
103− if (sessionId != null) {
104− val stopIntent = Intent(this, NotificationActionReceiver::class.java).apply {
105− action = NotificationActionReceiver.ACTION_STOP_RUN
106− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
107− }
108− val stopPending = PendingIntent.getBroadcast(
109− this, sessionId.hashCode(), stopIntent,
110− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
111− )
112− builder.addAction(
113− R.drawable.ic_action_stop,
114− getString(R.string.notif_action_stop),
115− stopPending,
116− )
117− }
118− return builder.build()
119− }
120−
121− // Android 14+ can time out a foreground service (notably the ~6h/day cumulative cap on
122− // dataSync in Android 15) and calls onTimeout expecting a prompt stop; not stopping risks
123− // the system force-stopping/ANR-ing the app. Stop cleanly — a still-active run just
124− // continues without foreground priority. Post a low-priority notification so the user
125− // knows their long-running task may be paused in the background, rather than silently
126− // losing foreground priority. Both overloads are covered (the 2-arg form is API 35+).
127− override fun onTimeout(startId: Int) {
128− Log.w(TAG, "Foreground service timed out; stopping")
129− postTimeoutNotification()
130− stopSelf()
131− }
132−
133− override fun onTimeout(startId: Int, fgsType: Int) {
134− Log.w(TAG, "Foreground service timed out (type=$fgsType); stopping")
135− postTimeoutNotification()
136− stopSelf()
137− }
138−
139− /** Post a low-priority notification informing the user that the foreground service was
140− * timed out by the system — the run continues but may be killed by Doze without warning. */
141− @SuppressLint("MissingPermission")
142− private fun postTimeoutNotification() {
143− runCatching {
144− val notification = NotificationCompat.Builder(this, NotificationChannels.STATUS)
145− .setSmallIcon(R.drawable.ic_stat_notify)
146− .setColor(brandColor(this))
147− .setContentTitle(getString(R.string.notif_running_title))
148− .setContentText(getString(R.string.notif_fg_timeout_text))
149− .setContentIntent(mainContentIntent())
150− .setAutoCancel(true)
151− .setPriority(NotificationCompat.PRIORITY_LOW)
152− .build()
153− NotificationManagerCompat.from(this).notify(NOTIF_TIMEOUT_ID, notification)
154− }
155− }
156−
157− override fun onDestroy() {
158− // Safety net: if the process is being killed while a run is in progress,
159− // ensure the notification is removed rather than lingering.
160− ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
161− // Reset the run start so the next run's chronometer begins fresh instead of
162− // inheriting the previous run's elapsed base.
163− runStartMillis = 0L
164− super.onDestroy()
165− }
166−
167− override fun onBind(intent: Intent?): IBinder? = null
168−
169− companion object {
170− private const val TAG = "RunForegroundService"
171− private const val NOTIF_ID = 1
172− private const val NOTIF_TIMEOUT_ID = 2
173− // Wall-clock time the current run started, captured on the first onStartCommand of
174− // the run and reused across progress-driven notification rebuilds so the chronometer
175− // base is stable. Reset to 0 in onDestroy when the run ends.
176− @Volatile private var runStartMillis: Long = 0L
177− // Brand accent for the foreground notifications' small-icon tint circle. Resolved
178− // from resources (R.color.notif_brand) so it follows the app theme (light/dark)
179− // instead of a hardcoded constant. Lazily computed on first use from the app context.
180− private var brandColorCache: Int = 0
181− private fun brandColor(context: Context): Int {
182− if (brandColorCache == 0) {
183− brandColorCache = androidx.core.content.ContextCompat.getColor(context, R.color.notif_brand)
184− }
185− return brandColorCache
186− }
187− const val EXTRA_SESSION_TITLE = "soy.iko.opencode.extra.SESSION_TITLE"
188− const val EXTRA_SESSION_ID = "soy.iko.opencode.extra.SESSION_ID"
189− const val EXTRA_PROGRESS = "soy.iko.opencode.extra.PROGRESS"
190−
191− fun start(context: Context, sessionTitle: String? = null, sessionId: String? = null, progress: String? = null) {
192− // startForegroundService can throw ForegroundServiceStartNotAllowedException
193− // on Android 12+ if the app is in the background. Wrap it so a backgrounded
194− // start (e.g. the user navigates away at the wrong moment) doesn't crash.
195− runCatching {
196− val intent = Intent(context, RunForegroundService::class.java)
197− sessionTitle?.let { intent.putExtra(EXTRA_SESSION_TITLE, it) }
198− sessionId?.let { intent.putExtra(EXTRA_SESSION_ID, it) }
199− progress?.let { intent.putExtra(EXTRA_PROGRESS, it) }
200− context.startForegroundService(intent)
201− }.onFailure {
202− Log.w(TAG, "startForegroundService failed; running without foreground priority", it)
203− }
204− }
205−
206− fun stop(context: Context) {
207− context.stopService(Intent(context, RunForegroundService::class.java))
208− }
209− }
210−}
app/src/main/java/soy/iko/opencode/notification/SessionNotifications.ktdeleted−527
@@ -1,527 +0,0 @@
1−package soy.iko.opencode.notification
2−
3−import android.annotation.SuppressLint
4−import android.app.Notification
5−import android.app.NotificationManager
6−import android.app.PendingIntent
7−import android.content.Context
8−import android.content.Intent
9−import android.os.Build
10−import android.util.Log
11−import androidx.core.app.NotificationCompat
12−import androidx.core.app.NotificationManagerCompat
13−import androidx.core.app.RemoteInput
14−import soy.iko.opencode.MainActivity
15−import soy.iko.opencode.R
16−import soy.iko.opencode.data.model.Permission
17−import soy.iko.opencode.data.model.PermissionResponse
18−import java.security.MessageDigest
19−
20−/**
21− * Builds and posts the app's session notifications:
22− *
23− * - [postCompleted]: a "session ready" notification when a background run finishes, with an
24− * inline [RemoteInput] Reply action so a follow-up can be sent without opening the app.
25− * - [postPermission]: a heads-up notification when a paused tool needs approval, with
26− * Allow once / Always / Reject action buttons handled by [NotificationActionReceiver].
27− * - [postError]: a notification when a background run fails.
28− *
29− * Tapping a notification body opens the session via [MainActivity] with an
30− * [MainActivity.EXTRA_SESSION_ID] extra. Notification posting is guarded for Android 13+
31− * runtime permission: if the user hasn't granted POST_NOTIFICATIONS, the post is silently
32− * skipped rather than throwing.
33− */
34−object SessionNotifications {
35−
36− private const val NOTIF_ID_PREFIX = 4000
37− private const val TAG = "SessionNotifications"
38− private const val UNREAD_BADGE_ID = NOTIF_ID_PREFIX + 9999
39−
40− // Distinct namespaces so a session can have a completion, a permission, and an error
41− // notification outstanding at once without their ids colliding.
42− private const val NS_COMPLETED = "done"
43− private const val NS_PERMISSION = "perm"
44− private const val NS_ERROR = "err"
45−
46− private val notifIdRegex = Regex("[^A-Za-z0-9_-]")
47−
48− /** Derive a stable, collision-resistant notification id from a namespace + session id.
49− * String.hashCode() can collide for different inputs; a SHA-256 truncated to 31
50− * bits makes accidental collisions astronomically unlikely. The namespace keeps the
51− * three notification kinds for one session in separate id spaces. */
52− private fun notifId(namespace: String, sessionId: String): Int {
53− val digest = runCatching { MessageDigest.getInstance("SHA-256") }
54− .getOrNull()?.digest("$namespace:$sessionId".toByteArray()) ?: return NOTIF_ID_PREFIX
55− // Take the first 4 bytes, mask to 31 bits (always positive) to fit an Int id.
56− // Kotlin's shl/or/and are equal-precedence infix functions evaluated strictly
57− // left-to-right, so the shifts MUST be parenthesized individually — otherwise
58− // `a shl 24 or b shl 16` parses as `((a shl 24) or b) shl 16`, shifting the first
59− // byte out of the Int entirely and collapsing the id's entropy.
60− val hash = (((digest[0].toInt() and 0xFF) shl 24) or
61− ((digest[1].toInt() and 0xFF) shl 16) or
62− ((digest[2].toInt() and 0xFF) shl 8) or
63− (digest[3].toInt() and 0xFF)).and(0x7FFFFFFF)
64− // Offset by NOTIF_ID_PREFIX, staying within the positive Int range.
65− // Using modulo ensures the prefix is preserved without Int overflow.
66− return NOTIF_ID_PREFIX + (hash % (0x7FFFFFFF - NOTIF_ID_PREFIX))
67− }
68−
69− /** Respect the POST_NOTIFICATIONS runtime permission (Android 13+): if the user denied
70− * it, callers should skip posting instead of throwing. Foreground-service notifications
71− * are exempt, so the running indicator still shows during a run. */
72− private fun canPost(context: Context): Boolean =
73− Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
74− androidx.core.content.ContextCompat.checkSelfPermission(
75− context, android.Manifest.permission.POST_NOTIFICATIONS,
76− ) == android.content.pm.PackageManager.PERMISSION_GRANTED
77−
78− /** A PendingIntent that opens [sessionId] in the app when the notification body is tapped.
79− * [profileId] (the originating server) is embedded so a tap after the user has switched
80− * servers routes back to the server that ran the session, not whichever is active —
81− * mirroring the Reply and permission action intents. */
82− private fun openSessionIntent(
83− context: Context, sessionId: String, requestCode: Int, profileId: String?,
84− ): PendingIntent {
85− // Sanitize the session id before embedding it in the deep-link URI so characters like
86− // /, ?, # can't inject path segments or query parameters.
87− val safeId = notifIdRegex.replace(sessionId, "")
88− val openIntent = Intent(context, MainActivity::class.java).apply {
89− action = Intent.ACTION_VIEW
90− data = android.net.Uri.parse("opencode://session/$safeId")
91− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
92− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
93− }
94− return PendingIntent.getActivity(
95− context, requestCode, openIntent,
96− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
97− )
98− }
99−
100− // canPost() checks POST_NOTIFICATIONS before every notify(); lint can't follow the
101− // check through the helper, so suppress its MissingPermission flag on these posts.
102− @SuppressLint("MissingPermission")
103− fun postCompleted(context: Context, sessionId: String, title: String, profileId: String?) {
104− if (!canPost(context)) return
105− val notifId = notifId(NS_COMPLETED, sessionId)
106−
107− // Inline reply: a RemoteInput-backed action that broadcasts the typed follow-up to
108− // NotificationActionReceiver. The PendingIntent MUST be mutable so the system can
109− // fill in the RemoteInput results before delivering it. [profileId] is embedded so the
110− // receiver enqueues the reply against the server that ran the session, not whichever
111− // server is active when the user taps (mirrors postPermission).
112− val remoteInput = RemoteInput.Builder(NotificationActionReceiver.KEY_REPLY_TEXT)
113− .setLabel(context.getString(R.string.notif_reply_hint))
114− .build()
115− val replyIntent = Intent(context, NotificationActionReceiver::class.java).apply {
116− action = NotificationActionReceiver.ACTION_REPLY
117− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
118− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
119− }
120− val replyPending = PendingIntent.getBroadcast(
121− context, notifId, replyIntent,
122− PendingIntent.FLAG_UPDATE_CURRENT or mutableFlag(),
123− )
124− val replyAction = NotificationCompat.Action.Builder(
125− R.drawable.ic_action_reply,
126− context.getString(R.string.notif_action_reply),
127− replyPending,
128− ).addRemoteInput(remoteInput).setAllowGeneratedReplies(true).build()
129−
130− // "Mark read" action so the user can triage a completion without opening the session.
131− val markReadIntent = Intent(context, NotificationActionReceiver::class.java).apply {
132− action = NotificationActionReceiver.ACTION_MARK_READ
133− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
134− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
135− }
136− val markReadPending = PendingIntent.getBroadcast(
137− context, notifId + 100, markReadIntent,
138− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
139− )
140− val markReadAction = NotificationCompat.Action.Builder(
141− R.drawable.ic_action_check,
142− context.getString(R.string.notif_action_mark_read),
143− markReadPending,
144− ).build()
145−
146− val notification = NotificationCompat.Builder(context, NotificationChannels.COMPLETED)
147− .setSmallIcon(R.drawable.ic_stat_notify)
148− .setContentTitle(context.getString(R.string.notif_completed_title))
149− // No % escaping here: getString(id, arg) inserts the argument verbatim and
150− // never re-scans it for format specifiers, so escaping the title would show
151− // literal doubled percent signs (e.g. a "50% done" title as "50%% done").
152− .setContentText(context.getString(R.string.notif_completed_text, title))
153− .setAutoCancel(true)
154− .setOnlyAlertOnce(true)
155− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
156− .addAction(replyAction)
157− .addAction(markReadAction)
158− .setCategory(NotificationCompat.CATEGORY_MESSAGE)
159− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
160− // Group notifications from the same server so multiple completions collapse into
161− // a stackable group on Android 7+ instead of filling the shade with individual entries.
162− .setGroup(GROUP_COMPLETED)
163− .build()
164−
165− runCatching {
166− NotificationManagerCompat.from(context).notify(notifId, notification)
167− // Post a summary notification so the group has a single top-level entry in the shade.
168− postCompletedSummary(context)
169− }.onFailure { Log.w(TAG, "Failed to post completion notification", it) }
170− }
171−
172− /** Post (or update) a summary notification for the completed-sessions group so multiple
173− * completions collapse into one stackable entry instead of filling the shade. */
174− @SuppressLint("MissingPermission")
175− private fun postCompletedSummary(context: Context) {
176− val summary = NotificationCompat.Builder(context, NotificationChannels.COMPLETED)
177− .setSmallIcon(R.drawable.ic_stat_notify)
178− .setContentTitle(context.getString(R.string.notif_completed_title))
179− .setContentText(context.getString(R.string.app_name))
180− .setSmallIcon(R.drawable.ic_stat_notify)
181− .setAutoCancel(true)
182− .setCategory(NotificationCompat.CATEGORY_MESSAGE)
183− .setGroup(GROUP_COMPLETED)
184− .setGroupSummary(true)
185− .build()
186− runCatching {
187− NotificationManagerCompat.from(context).notify(SUMMARY_COMPLETED_ID, summary)
188− }.onFailure { Log.w(TAG, "Failed to post completion summary notification", it) }
189− }
190−
191− /** Post a heads-up notification for a permission request with Allow once / Always /
192− * Reject action buttons. [sessionTitle] labels the notification; [permission]'s title/
193− * pattern/type supplies the detail line. [profileId] is embedded in the action intents
194− * so the receiver routes the response back to the server that posted the request, not
195− * whichever server happens to be active when the user taps. */
196− @SuppressLint("MissingPermission")
197− fun postPermission(context: Context, permission: Permission, sessionTitle: String, profileId: String?) {
198− if (!canPost(context)) return
199− val sessionId = permission.sessionID.takeIf { it.isNotBlank() } ?: return
200− val notifId = notifId(NS_PERMISSION, sessionId)
201− val detail = permission.title?.takeIf { it.isNotBlank() }
202− ?: permission.patternText?.takeIf { it.isNotBlank() }
203− ?: permission.type?.takeIf { it.isNotBlank() }
204− ?: context.getString(R.string.notif_permission_fallback)
205−
206− val builder = NotificationCompat.Builder(context, NotificationChannels.PERMISSION)
207− .setSmallIcon(R.drawable.ic_stat_notify)
208− .setContentTitle(context.getString(R.string.notif_permission_title, sessionTitle))
209− .setContentText(detail)
210− .setStyle(NotificationCompat.BigTextStyle().bigText(detail))
211− .setAutoCancel(true)
212− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
213− .setPriority(NotificationCompat.PRIORITY_HIGH)
214− .setGroup(GROUP_PERMISSION)
215− .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
216− .setPublicVersion(
217− NotificationCompat.Builder(context, NotificationChannels.PERMISSION)
218− .setSmallIcon(R.drawable.ic_stat_notify)
219− .setContentTitle(context.getString(R.string.notif_permission_public))
220− .build(),
221− )
222−
223− // One action per response. Each PendingIntent needs a distinct request code or
224− // FLAG_UPDATE_CURRENT would collapse them into one (the last extras win).
225− listOf(
226− Triple(PermissionResponse.ONCE, R.string.notif_action_allow_once, R.drawable.ic_action_check),
227− Triple(PermissionResponse.ALWAYS, R.string.notif_action_always, R.drawable.ic_action_check),
228− Triple(PermissionResponse.REJECT, R.string.notif_action_reject, R.drawable.ic_action_block),
229− ).forEach { (response, labelRes, iconRes) ->
230− val intent = Intent(context, NotificationActionReceiver::class.java).apply {
231− action = NotificationActionReceiver.ACTION_PERMISSION
232− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
233− putExtra(NotificationActionReceiver.EXTRA_PERMISSION_ID, permission.id)
234− putExtra(NotificationActionReceiver.EXTRA_RESPONSE, response.wire)
235− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
236− }
237− val pending = PendingIntent.getBroadcast(
238− context, notifId + response.ordinal + 1, intent,
239− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
240− )
241− builder.addAction(iconRes, context.getString(labelRes), pending)
242− }
243−
244− runCatching { NotificationManagerCompat.from(context).notify(notifId, builder.build()) }
245− .onFailure { Log.w(TAG, "Failed to post permission notification", it) }
246− // Group permission notifications so a multi-session burst collapses into a stackable
247− // group instead of filling the shade — mirroring the completed-sessions grouping.
248− runCatching { postGroupSummary(context, NotificationChannels.PERMISSION, GROUP_PERMISSION, SUMMARY_PERMISSION_ID) }
249− .onFailure { Log.w(TAG, "Failed to post permission summary notification", it) }
250− }
251−
252− /** Post a notification when a permission prompt auto-rejected on timeout. A user who
253− * walked away from an in-app prompt returns to find the run stopped with no on-screen
254− * record of why; this leaves a persistent trace in the shade explaining the stop and
255− * offering to re-open the session. Uses the permission channel (heads-up) so it's seen. */
256− @SuppressLint("MissingPermission")
257− fun postPermissionAutoRejected(context: Context, sessionId: String, sessionTitle: String, profileId: String?) {
258− if (!canPost(context)) return
259− val notifId = notifId(NS_PERMISSION, sessionId) + 1 // distinct from the live prompt
260− val detail = context.getString(R.string.notif_permission_auto_rejected_text)
261− val builder = NotificationCompat.Builder(context, NotificationChannels.PERMISSION)
262− .setSmallIcon(R.drawable.ic_stat_notify)
263− .setContentTitle(context.getString(R.string.notif_permission_auto_rejected_title, sessionTitle))
264− .setContentText(detail)
265− .setStyle(NotificationCompat.BigTextStyle().bigText(detail))
266− .setAutoCancel(true)
267− .setOnlyAlertOnce(true)
268− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
269− .setCategory(NotificationCompat.CATEGORY_STATUS)
270− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
271− .setGroup(GROUP_PERMISSION)
272− .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
273− runCatching { NotificationManagerCompat.from(context).notify(notifId, builder.build()) }
274− .onFailure { Log.w(TAG, "Failed to post permission auto-reject notification", it) }
275− runCatching { postGroupSummary(context, NotificationChannels.PERMISSION, GROUP_PERMISSION, SUMMARY_PERMISSION_ID) }
276− .onFailure { Log.w(TAG, "Failed to post permission summary notification", it) }
277− }
278−
279− /** Post a notification when a background run fails. */
280− @SuppressLint("MissingPermission")
281− fun postError(context: Context, sessionId: String, title: String, profileId: String? = null) {
282− if (!canPost(context)) return
283− val notifId = notifId(NS_ERROR, sessionId)
284− val builder = NotificationCompat.Builder(context, NotificationChannels.ERROR)
285− .setSmallIcon(R.drawable.ic_stat_notify)
286− .setContentTitle(context.getString(R.string.notif_error_title))
287− .setContentText(context.getString(R.string.notif_error_text, title))
288− .setAutoCancel(true)
289− .setOnlyAlertOnce(true)
290− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
291− .setCategory(NotificationCompat.CATEGORY_ERROR)
292− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
293− // Group error notifications so a burst of failures collapses into a stackable group.
294− .setGroup(GROUP_ERROR)
295− .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
296− .setPublicVersion(
297− NotificationCompat.Builder(context, NotificationChannels.ERROR)
298− .setSmallIcon(R.drawable.ic_stat_notify)
299− .setContentTitle(context.getString(R.string.notif_error_public))
300− .build(),
301− )
302− // A "Retry last" action lets the user re-run the failed prompt straight from the shade
303− // without opening the app — a failed run is exactly when a one-tap retry is most useful.
304− val retryIntent = Intent(context, NotificationActionReceiver::class.java).apply {
305− action = NotificationActionReceiver.ACTION_RETRY_LAST
306− putExtra(NotificationActionReceiver.EXTRA_SESSION_ID, sessionId)
307− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
308− }
309− val retryPending = PendingIntent.getBroadcast(
310− context, notifId + 10, retryIntent,
311− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
312− )
313− builder.addAction(R.drawable.ic_action_refresh, context.getString(R.string.retry_last), retryPending)
314− val notification = builder.build()
315− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
316− .onFailure { Log.w(TAG, "Failed to post error notification", it) }
317− runCatching { postGroupSummary(context, NotificationChannels.ERROR, GROUP_ERROR, SUMMARY_ERROR_ID) }
318− .onFailure { Log.w(TAG, "Failed to post error summary notification", it) }
319− }
320−
321− /** Update the completion notification to show a brief "Sent" confirmation after a
322− * successful inline reply, replacing the completion notification's content. Auto-cancels
323− * on tap so it doesn't linger. */
324− @SuppressLint("MissingPermission")
325− fun postReplySent(context: Context, sessionId: String) {
326− if (!canPost(context)) {
327− cancel(context, sessionId)
328− return
329− }
330− val notifId = notifId(NS_COMPLETED, sessionId)
331− val notification = NotificationCompat.Builder(context, NotificationChannels.COMPLETED)
332− .setSmallIcon(R.drawable.ic_stat_notify)
333− .setContentTitle(context.getString(R.string.notif_reply_sent))
334− .setAutoCancel(true)
335− .setPriority(NotificationCompat.PRIORITY_LOW)
336− .setGroup(GROUP_COMPLETED)
337− .build()
338− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
339− .onFailure { Log.w(TAG, "Failed to post reply-sent notification", it) }
340− }
341−
342− /** An inline reply couldn't be durably enqueued (no resolvable profile, or the outbox write
343− * threw). Cancel the completion notification so SystemUI's RemoteInput field doesn't stay
344− * stuck in the "sending…" spinner — a stuck field can't be resubmitted — and post an error
345− * notification so the reply isn't silently lost and the user can reopen the session to retry. */
346− @SuppressLint("MissingPermission")
347− fun postReplyFailed(context: Context, sessionId: String, profileId: String? = null) {
348− NotificationManagerCompat.from(context).cancel(notifId(NS_COMPLETED, sessionId))
349− maybeCancelSummary(context, GROUP_COMPLETED, SUMMARY_COMPLETED_ID)
350− if (!canPost(context)) return
351− val notifId = notifId(NS_ERROR, sessionId)
352− val notification = NotificationCompat.Builder(context, NotificationChannels.ERROR)
353− .setSmallIcon(R.drawable.ic_stat_notify)
354− .setContentTitle(context.getString(R.string.notif_reply_failed_title))
355− .setContentText(context.getString(R.string.notif_reply_failed_text))
356− .setAutoCancel(true)
357− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
358− .setCategory(NotificationCompat.CATEGORY_ERROR)
359− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
360− .build()
361− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
362− .onFailure { Log.w(TAG, "Failed to post reply-failed notification", it) }
363− }
364−
365− /** A queued outbox message was permanently undeliverable (e.g. the target session was
366− * deleted server-side → 404). Distinct from [postError] (which is titled "Run failed"):
367− * no run failed — a queued reply couldn't be delivered. Uses a distinct title/body so the
368− * user understands the failure mode and recovery action (open the session and re-send). */
369− @SuppressLint("MissingPermission")
370− fun postOutboxDropped(context: Context, sessionId: String, sessionTitle: String, profileId: String? = null) {
371− if (!canPost(context)) return
372− val notifId = notifId(NS_ERROR, sessionId)
373− val notification = NotificationCompat.Builder(context, NotificationChannels.ERROR)
374− .setSmallIcon(R.drawable.ic_stat_notify)
375− .setContentTitle(context.getString(R.string.message_not_delivered))
376− .setContentText(context.getString(R.string.message_not_delivered_body, sessionTitle))
377− .setAutoCancel(true)
378− .setOnlyAlertOnce(true)
379− .setContentIntent(openSessionIntent(context, sessionId, notifId, profileId))
380− .setCategory(NotificationCompat.CATEGORY_ERROR)
381− .setPriority(NotificationCompat.PRIORITY_DEFAULT)
382− .setGroup(GROUP_ERROR)
383− .build()
384− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
385− .onFailure { Log.w(TAG, "Failed to post outbox-dropped notification", it) }
386− runCatching { postGroupSummary(context, NotificationChannels.ERROR, GROUP_ERROR, SUMMARY_ERROR_ID) }
387− .onFailure { Log.w(TAG, "Failed to post error summary notification", it) }
388− }
389−
390− /** The SSE stream hit a non-retryable failure (Failed/AuthFailed) while the app was
391− * backgrounded during an active run, so the in-app banner isn't visible and the run is
392− * effectively stranded. Posts a low-priority notification so a backgrounded user is
393− * signaled that their run is stalled and can tap to reconnect. Distinct from [postError]
394− * (a run error) — this is a connection loss, not a run failure. */
395− @SuppressLint("MissingPermission")
396− fun postConnectionLost(context: Context, profileLabel: String, profileId: String?) {
397− if (!canPost(context)) return
398− val notifId = NOTIF_ID_PREFIX + 7000
399− // Tap reopens the app at the server list so the user can reconnect / fix credentials.
400− val openIntent = Intent(context, MainActivity::class.java).apply {
401− flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
402− profileId?.let { putExtra(NotificationActionReceiver.EXTRA_PROFILE_ID, it) }
403− }
404− val openPending = PendingIntent.getActivity(
405− context, notifId, openIntent,
406− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
407− )
408− val notification = NotificationCompat.Builder(context, NotificationChannels.ERROR)
409− .setSmallIcon(R.drawable.ic_stat_notify)
410− .setContentTitle(context.getString(R.string.connection_lost, profileLabel))
411− .setContentText(context.getString(R.string.connection_lost_tap))
412− .setAutoCancel(true)
413− .setOnlyAlertOnce(true)
414− .setContentIntent(openPending)
415− .setCategory(NotificationCompat.CATEGORY_STATUS)
416− .setPriority(NotificationCompat.PRIORITY_LOW)
417− .build()
418− runCatching { NotificationManagerCompat.from(context).notify(notifId, notification) }
419− .onFailure { Log.w(TAG, "Failed to post connection-lost notification", it) }
420− }
421−
422− /** Cancel a previously-posted [postConnectionLost] notification (e.g. on reconnect). */
423− fun cancelConnectionLost(context: Context) {
424− NotificationManagerCompat.from(context).cancel(NOTIF_ID_PREFIX + 7000)
425− }
426−
427− /** FLAG_MUTABLE where required (Android 12+) so RemoteInput results can be injected. */
428− private fun mutableFlag(): Int =
429− if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
430−
431− /** Cancel a session's completion notification (e.g. when the user opens it). */
432− fun cancel(context: Context, sessionId: String) {
433− NotificationManagerCompat.from(context).cancel(notifId(NS_COMPLETED, sessionId))
434− maybeCancelSummary(context, GROUP_COMPLETED, SUMMARY_COMPLETED_ID)
435− }
436−
437− /**
438− * Reflect the total number of unread sessions as a launcher-icon badge. Android only badges
439− * the launcher icon via a notification on a badge-enabled channel, so this posts a silent,
440− * min-importance notification with [.setNumber] on the [NotificationChannels.UNREAD] channel
441− * when [totalUnread] > 0, and cancels it when it drops to 0. Skipped entirely without
442− * POST_NOTIFICATIONS permission (Android 13+) — the badge just won't show, no error.
443− */
444− @SuppressLint("MissingPermission")
445− fun updateUnreadBadge(context: Context, totalUnread: Int) {
446− val nm = NotificationManagerCompat.from(context)
447− if (totalUnread <= 0) {
448− nm.cancel(UNREAD_BADGE_ID)
449− return
450− }
451− if (!canPost(context)) return
452− val notification = NotificationCompat.Builder(context, NotificationChannels.UNREAD)
453− .setSmallIcon(R.drawable.ic_stat_notify)
454− .setContentTitle(context.getString(R.string.app_name))
455− .setContentText(context.resources.getQuantityString(R.plurals.unread_sessions, totalUnread, totalUnread))
456− .setNumber(totalUnread.coerceAtMost(999))
457− .setOnlyAlertOnce(true)
458− .setSilent(true)
459− .setShowWhen(false)
460− .setPriority(NotificationCompat.PRIORITY_MIN)
461− .build()
462− runCatching { nm.notify(UNREAD_BADGE_ID, notification) }
463− .onFailure { Log.w(TAG, "Failed to post unread badge notification", it) }
464− }
465−
466− /** Cancel a session's permission notification (on reply, or when the user opens it). */
467− fun cancelPermission(context: Context, sessionId: String) {
468− NotificationManagerCompat.from(context).cancel(notifId(NS_PERMISSION, sessionId))
469− maybeCancelSummary(context, GROUP_PERMISSION, SUMMARY_PERMISSION_ID)
470− }
471−
472− /** Cancel a session's error notification (e.g. when the user opens it). Without this a
473− * stale "run failed" notification lingers when the session is opened by any route other
474− * than tapping the notification itself (setAutoCancel only clears it on a direct tap). */
475− fun cancelError(context: Context, sessionId: String) {
476− NotificationManagerCompat.from(context).cancel(notifId(NS_ERROR, sessionId))
477− maybeCancelSummary(context, GROUP_ERROR, SUMMARY_ERROR_ID)
478− }
479−
480− /** Build the lock-screen (public) version of a notification: only a generic title, no
481− * detail line, so sensitive file paths / commands in the real content aren't revealed
482− * while the device is locked. */
483− /** When the last child of a group is dismissed, cancel its lingering summary so it
484− * doesn't sit empty in the shade. NotificationManagerCompat lacks getActiveNotifications,
485− * so reach for the platform NotificationManager. The children/summary are posted without
486− * a tag, so matching by [android.app.Notification.getGroup] (plus excluding the summary
487− * id) is the reliable way to tell if any child remains. */
488− private fun maybeCancelSummary(context: Context, group: String, summaryId: Int) {
489− val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
490− ?: return
491− val active = try {
492− nm.activeNotifications
493− } catch (e: Exception) {
494− Log.w(TAG, "Failed to query active notifications for summary cleanup", e)
495− return
496− }
497− val hasChild = active.any { it.id != summaryId && it.notification?.group == group }
498− if (!hasChild) {
499− runCatching { NotificationManagerCompat.from(context).cancel(summaryId) }
500− .onFailure { Log.w(TAG, "Failed to cancel empty group summary", it) }
501− }
502− }
503−
504− private const val GROUP_COMPLETED = "soy.iko.opencode.COMPLETED"
505− private const val GROUP_PERMISSION = "soy.iko.opencode.PERMISSION"
506− private const val GROUP_ERROR = "soy.iko.opencode.ERROR"
507− private const val SUMMARY_COMPLETED_ID = -1
508− private const val SUMMARY_PERMISSION_ID = -2
509− private const val SUMMARY_ERROR_ID = -3
510−
511− /** Post a summary notification for a group so multiple entries collapse into one stackable
512− * entry in the shade instead of filling it. */
513− @SuppressLint("MissingPermission")
514− private fun postGroupSummary(context: Context, channelId: String, group: String, summaryId: Int) {
515− if (!canPost(context)) return
516− val summary = NotificationCompat.Builder(context, channelId)
517− .setSmallIcon(R.drawable.ic_stat_notify)
518− .setContentTitle(context.getString(R.string.app_name))
519− .setAutoCancel(true)
520− .setGroup(group)
521− .setGroupSummary(true)
522− .build()
523− runCatching {
524− NotificationManagerCompat.from(context).notify(summaryId, summary)
525− }.onFailure { Log.w(TAG, "Failed to post group summary notification", it) }
526− }
527−}
app/src/main/java/soy/iko/opencode/platform/AppShortcuts.ktdeleted−58
@@ -1,58 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.content.Context
4−import android.content.Intent
5−import android.net.Uri
6−import androidx.core.content.pm.ShortcutInfoCompat
7−import androidx.core.content.pm.ShortcutManagerCompat
8−import androidx.core.graphics.drawable.IconCompat
9−import soy.iko.opencode.MainActivity
10−import soy.iko.opencode.R
11−import soy.iko.opencode.data.repo.RecentSession
12−
13−/**
14− * Maintains the app's dynamic launcher shortcuts (long-press the icon): "New session" and
15− * "Resume last". Rebuilt whenever the recent-session list changes so "Resume last" points at
16− * the most recent conversation via the existing `opencode://session/{id}` deep link.
17− */
18−object AppShortcuts {
19−
20− private const val ID_NEW = "new_session"
21− private const val ID_RESUME = "resume_last"
22− private val idRegex = Regex("[^A-Za-z0-9_-]")
23−
24− fun update(context: Context, lastSession: RecentSession?) {
25− val ctx = context.applicationContext
26− val shortcuts = mutableListOf<ShortcutInfoCompat>()
27−
28− shortcuts += ShortcutInfoCompat.Builder(ctx, ID_NEW)
29− .setShortLabel(ctx.getString(R.string.shortcut_new_short))
30− .setLongLabel(ctx.getString(R.string.shortcut_new_long))
31− .setIcon(IconCompat.createWithResource(ctx, R.drawable.ic_launcher_foreground))
32− .setIntent(
33− Intent(ctx, MainActivity::class.java).apply { action = MainActivity.ACTION_NEW_SESSION },
34− )
35− .build()
36−
37− if (lastSession != null) {
38− val safeId = idRegex.replace(lastSession.id, "")
39− if (safeId.isNotEmpty()) {
40− shortcuts += ShortcutInfoCompat.Builder(ctx, ID_RESUME)
41− .setShortLabel(ctx.getString(R.string.shortcut_resume_short))
42− .setLongLabel(
43− lastSession.title.ifBlank { ctx.getString(R.string.shortcut_resume_long) }.take(40),
44− )
45− .setIcon(IconCompat.createWithResource(ctx, R.drawable.ic_launcher_foreground))
46− .setIntent(
47− Intent(ctx, MainActivity::class.java).apply {
48− action = Intent.ACTION_VIEW
49− data = Uri.parse("opencode://session/$safeId")
50− },
51− )
52− .build()
53− }
54− }
55−
56− runCatching { ShortcutManagerCompat.setDynamicShortcuts(ctx, shortcuts) }
57− }
58−}
app/src/main/java/soy/iko/opencode/platform/NewSessionTileService.ktdeleted−33
@@ -1,33 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.app.PendingIntent
4−import android.content.Intent
5−import android.os.Build
6−import android.service.quicksettings.TileService
7−import soy.iko.opencode.MainActivity
8−
9−/**
10− * Quick-settings tile that starts a new opencode session. Tapping launches [MainActivity]
11− * with [MainActivity.ACTION_NEW_SESSION]; the app creates and opens a fresh session once
12− * connected. On Android 14+ [startActivityAndCollapse] requires a PendingIntent.
13− */
14−class NewSessionTileService : TileService() {
15−
16− override fun onClick() {
17− super.onClick()
18− val intent = Intent(this, MainActivity::class.java).apply {
19− action = MainActivity.ACTION_NEW_SESSION
20− addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
21− }
22− if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
23− val pending = PendingIntent.getActivity(
24− this, 0, intent,
25− PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
26− )
27− startActivityAndCollapse(pending)
28− } else {
29− @Suppress("DEPRECATION", "StartActivityAndCollapseDeprecated")
30− startActivityAndCollapse(intent)
31− }
32− }
33−}
app/src/main/java/soy/iko/opencode/platform/SessionsWidgetProvider.ktdeleted−83
@@ -1,83 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.app.PendingIntent
4−import android.appwidget.AppWidgetManager
5−import android.appwidget.AppWidgetProvider
6−import android.content.ComponentName
7−import android.content.Context
8−import android.content.Intent
9−import android.net.Uri
10−import android.os.Build
11−import android.widget.RemoteViews
12−import soy.iko.opencode.MainActivity
13−import soy.iko.opencode.R
14−
15−/**
16− * Home-screen widget listing recent opencode sessions (fed by
17− * [soy.iko.opencode.data.repo.RecentSessionsStore]) with a "New session" action. Each row deep-links
18− * into its session; the header opens the app. The list is backed by [SessionsWidgetService].
19− */
20−class SessionsWidgetProvider : AppWidgetProvider() {
21−
22− override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
23− for (id in appWidgetIds) render(context, appWidgetManager, id)
24− }
25−
26− companion object {
27− /** Re-render all widgets and tell them to reload their list data (call after the
28− * recent-session list changes). No-op when no widget is placed. */
29− fun refresh(context: Context) {
30− val manager = AppWidgetManager.getInstance(context) ?: return
31− val ids = runCatching {
32− manager.getAppWidgetIds(ComponentName(context, SessionsWidgetProvider::class.java))
33− }.getOrNull() ?: return
34− if (ids.isEmpty()) return
35− for (id in ids) render(context, manager, id)
36− manager.notifyAppWidgetViewDataChanged(ids, R.id.widget_list)
37− }
38−
39− private fun render(context: Context, manager: AppWidgetManager, widgetId: Int) {
40− val views = RemoteViews(context.packageName, R.layout.widget_sessions)
41−
42− // Header: title opens the app; the "+" starts a new session.
43− views.setOnClickPendingIntent(
44− R.id.widget_title,
45− activityPending(context, requestCode = 2, Intent(context, MainActivity::class.java)),
46− )
47− views.setOnClickPendingIntent(
48− R.id.widget_new,
49− activityPending(
50− context, requestCode = 1,
51− Intent(context, MainActivity::class.java).apply { action = MainActivity.ACTION_NEW_SESSION },
52− ),
53− )
54−
55− // Bind the list to the RemoteViewsService. A unique data Uri per widget id keeps
56− // the framework from reusing one adapter across widgets.
57− val serviceIntent = Intent(context, SessionsWidgetService::class.java).apply {
58− putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
59− data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))
60− }
61− views.setRemoteAdapter(R.id.widget_list, serviceIntent)
62− views.setEmptyView(R.id.widget_list, R.id.widget_empty)
63−
64− // Template intent filled in per row (fill-in carries EXTRA_SESSION_ID). Must be
65− // mutable on Android 12+ so the row's fill-in can be merged.
66− val templateIntent = Intent(context, MainActivity::class.java).apply { action = Intent.ACTION_VIEW }
67− val mutableFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
68− val templatePending = PendingIntent.getActivity(
69− context, 3, templateIntent, PendingIntent.FLAG_UPDATE_CURRENT or mutableFlag,
70− )
71− views.setPendingIntentTemplate(R.id.widget_list, templatePending)
72−
73− manager.updateAppWidget(widgetId, views)
74− manager.notifyAppWidgetViewDataChanged(widgetId, R.id.widget_list)
75− }
76−
77− private fun activityPending(context: Context, requestCode: Int, intent: Intent): PendingIntent =
78− PendingIntent.getActivity(
79− context, requestCode, intent,
80− PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
81− )
82− }
83−}
app/src/main/java/soy/iko/opencode/platform/SessionsWidgetService.ktdeleted−68
@@ -1,68 +0,0 @@
1−package soy.iko.opencode.platform
2−
3−import android.content.Context
4−import android.content.Intent
5−import android.widget.RemoteViews
6−import android.widget.RemoteViewsService
7−import soy.iko.opencode.MainActivity
8−import soy.iko.opencode.R
9−import soy.iko.opencode.data.repo.RecentSession
10−import soy.iko.opencode.data.repo.RecentSessionsStore
11−import java.security.MessageDigest
12−
13−/** Serves the list rows for [SessionsWidgetProvider] from [RecentSessionsStore]. */
14−class SessionsWidgetService : RemoteViewsService() {
15− override fun onGetViewFactory(intent: Intent): RemoteViewsFactory =
16− SessionsWidgetFactory(applicationContext)
17−}
18−
19−private class SessionsWidgetFactory(private val context: Context) : RemoteViewsService.RemoteViewsFactory {
20−
21− private var items: List<RecentSession> = emptyList()
22−
23− override fun onCreate() { items = RecentSessionsStore.read(context) }
24−
25− // Re-read from disk whenever the app signals the data changed (notifyAppWidgetViewDataChanged).
26− override fun onDataSetChanged() { items = RecentSessionsStore.read(context) }
27−
28− override fun onDestroy() { items = emptyList() }
29−
30− override fun getCount(): Int = items.size
31−
32− override fun getViewAt(position: Int): RemoteViews {
33− val row = RemoteViews(context.packageName, R.layout.widget_session_item)
34− val session = items.getOrNull(position) ?: return row
35− row.setTextViewText(R.id.widget_item_title, session.title.ifBlank { context.getString(R.string.session) })
36− // Fill-in intent merged into the list's template: carries the session id the app opens.
37− row.setOnClickFillInIntent(
38− R.id.widget_item_root,
39− Intent().putExtra(MainActivity.EXTRA_SESSION_ID, session.id),
40− )
41− return row
42− }
43−
44− override fun getLoadingView(): RemoteViews? = null
45− override fun getViewTypeCount(): Int = 1
46− // Derive a stable id from the session id via a collision-resistant SHA-256 digest
47− // (truncated to 63 bits) rather than String.hashCode(), whose 32-bit output can
48− // collide for distinct session ids — with hasStableIds=true the RemoteViews framework
49− // would then mis-recycle two sessions' row content. Mirrors SessionNotifications.notifId.
50− // Falls back to the position for an out-of-range index.
51− override fun getItemId(position: Int): Long {
52− val id = items.getOrNull(position)?.id ?: return position.toLong()
53− val digest = runCatching { MessageDigest.getInstance("SHA-256").digest(id.toByteArray()) }
54− .getOrNull() ?: return position.toLong()
55− // Take the first 8 bytes, mask to 63 bits (always positive) to fit a Long id.
56− // The shl/or/and infix precedence requires parenthesizing each shift individually
57− // (see SessionNotifications.notifId for the rationale).
58− return (((digest[0].toLong() and 0xFF) shl 56) or
59− ((digest[1].toLong() and 0xFF) shl 48) or
60− ((digest[2].toLong() and 0xFF) shl 40) or
61− ((digest[3].toLong() and 0xFF) shl 32) or
62− ((digest[4].toLong() and 0xFF) shl 24) or
63− ((digest[5].toLong() and 0xFF) shl 16) or
64− ((digest[6].toLong() and 0xFF) shl 8) or
65− (digest[7].toLong() and 0xFF)).and(0x7FFFFFFFFFFFFFFF)
66− }
67− override fun hasStableIds(): Boolean = true
68−}
app/src/main/java/soy/iko/opencode/ui/AppLockGate.ktdeleted−302
@@ -1,302 +0,0 @@
1−package soy.iko.opencode.ui
2−
3−import android.content.Context
4−import android.content.ContextWrapper
5−import android.os.Build
6−import androidx.biometric.BiometricManager
7−import androidx.biometric.BiometricPrompt
8−import androidx.compose.foundation.clickable
9−import androidx.compose.foundation.layout.Arrangement
10−import androidx.compose.foundation.layout.Column
11−import androidx.compose.foundation.layout.Spacer
12−import androidx.compose.foundation.layout.fillMaxSize
13−import androidx.compose.foundation.layout.padding
14−import androidx.compose.foundation.layout.size
15−import androidx.compose.material.icons.Icons
16−import androidx.compose.material.icons.filled.Fingerprint
17−import androidx.compose.material.icons.filled.Lock
18−import androidx.compose.material3.Button
19−import androidx.compose.material3.Icon
20−import androidx.compose.material3.MaterialTheme
21−import androidx.compose.material3.Surface
22−import androidx.compose.material3.Text
23−import androidx.compose.runtime.Composable
24−import androidx.compose.runtime.DisposableEffect
25−import androidx.compose.runtime.LaunchedEffect
26−import androidx.compose.runtime.getValue
27−import androidx.compose.runtime.mutableStateOf
28−import androidx.compose.runtime.remember
29−import androidx.compose.runtime.saveable.rememberSaveableStateHolder
30−import androidx.compose.runtime.setValue
31−import androidx.compose.ui.Alignment
32−import androidx.compose.ui.Modifier
33−import androidx.compose.ui.platform.LocalContext
34−import androidx.compose.ui.res.stringResource
35−import androidx.compose.ui.semantics.LiveRegionMode
36−import androidx.compose.ui.semantics.Role
37−import androidx.compose.ui.semantics.liveRegion
38−import androidx.compose.ui.semantics.semantics
39−import androidx.compose.ui.unit.dp
40−import androidx.core.content.ContextCompat
41−import androidx.fragment.app.FragmentActivity
42−import androidx.lifecycle.Lifecycle
43−import androidx.lifecycle.LifecycleEventObserver
44−import androidx.lifecycle.compose.LocalLifecycleOwner
45−import soy.iko.opencode.R
46−import soy.iko.opencode.ui.components.LoadingSize
47−import soy.iko.opencode.ui.components.LoadingSpinner
48−
49−/**
50− * The set of authenticators the app lock accepts. Device credential (PIN/pattern/password)
51− * can only be combined with a biometric class from Android 11 (API 30) on; on 26–29 we ask
52− * for a strong biometric alone, so the lock is only offered (in Settings) when one is enrolled.
53− */
54−private val lockAuthenticators: Int
55− get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
56− BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL
57− } else {
58− BiometricManager.Authenticators.BIOMETRIC_STRONG
59− }
60−
61−/** Whether device authentication is currently possible, so Settings can gate the toggle. */
62−fun canAuthenticateForAppLock(context: Context): Boolean =
63− BiometricManager.from(context).canAuthenticate(lockAuthenticators) == BiometricManager.BIOMETRIC_SUCCESS
64−
65−/**
66− * Whether app-lock auth is *permanently* impossible on this device (no hardware, nothing
67− * enrolled, or a pending security update). Only these states may fail the gate open. A transient
68− * error (sensor busy / temporarily unavailable) must NOT fail open — that would unlock the app on
69− * a momentary glitch — so the gate stays locked and lets the user retry.
70− */
71−private fun appLockPermanentlyUnavailable(context: Context): Boolean =
72− when (BiometricManager.from(context).canAuthenticate(lockAuthenticators)) {
73− BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED,
74− BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,
75− BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> true
76− else -> false
77− }
78−
79−/** Unwrap a [FragmentActivity] from a (possibly wrapped) Compose [Context]. */
80−private fun Context.findFragmentActivity(): FragmentActivity? {
81− var ctx: Context? = this
82− while (ctx is ContextWrapper) {
83− if (ctx is FragmentActivity) return ctx
84− ctx = ctx.baseContext
85− }
86− return null
87−}
88−
89−/**
90− * Gates [content] behind device authentication when [enabled]. The content stays composed
91− * underneath an opaque lock overlay (so navigation state survives a re-lock), and the app
92− * re-locks whenever it's sent to the background. If no [FragmentActivity] is available or the
93− * device can't authenticate, the gate is a no-op — the setting is only offered when
94− * [canAuthenticateForAppLock] is true, so this fallback just prevents a hard lock-out.
95− */
96−@Composable
97−fun AppLockGate(enabled: Boolean, reLockDelaySeconds: Int = 0, content: @Composable () -> Unit) {
98− if (!enabled) {
99− content()
100− return
101− }
102− val context = LocalContext.current
103− val activity = remember(context) { context.findFragmentActivity() }
104− if (activity == null) {
105− content()
106− return
107− }
108− // Fail open only if device authentication is *permanently* impossible (e.g. the user enabled
109− // app-lock while a credential was enrolled and later removed their PIN/biometric): authenticate()
110− // would otherwise always hit onAuthenticationError and strand the user on a permanent lockout.
111− // A transient authenticator error keeps the lock up (the user retries) rather than unlocking.
112− if (appLockPermanentlyUnavailable(context)) {
113− // Surface a one-time warning so the user knows their app-lock setting is on but isn't
114− // actually protecting the app — without this they'd have to discover it by opening
115− // Settings and seeing the "unavailable" state. A Toast (not a snackbar) because the
116− // gate sits above the Scaffold/SnackbarHost; the warning is informational, not an action.
117− LaunchedEffect(Unit) {
118− android.widget.Toast.makeText(
119− context,
120− context.getString(R.string.app_lock_disabled_warning),
121− android.widget.Toast.LENGTH_LONG,
122− ).show()
123− }
124− content()
125− return
126− }
127−
128− // Deliberately NOT rememberSaveable: the unlocked flag must never be persisted into the
129− // saved-instance-state Bundle. On API 26-27 onSaveInstanceState runs *before* onStop, so a
130− // saveable `true` would be written to the Bundle before ON_STOP resets it; after a background
131− // process-kill and restore the app would come back unlocked with no biometric prompt — an
132− // app-lock bypass. Rotation is handled by the activity's configChanges (no recreation), so a
133− // plain remember still avoids re-prompting on rotation while re-locking on real recreation.
134− var unlocked by remember { mutableStateOf(false) }
135− // Wall-clock time of the most recent ON_STOP. Used with [reLockDelaySeconds] so a quick
136− // app-switch (e.g. glancing at another app for a few seconds) doesn't re-prompt — the most
137− // common reason users disable biometric locks. A killed process resets unlocked anyway, so the
138− // grace period only governs the in-memory re-lock decision across a surviving background stint.
139− val lastStopTimeMs = remember { longArrayOf(0L) }
140− val reLockDelayMs = reLockDelaySeconds * 1000L
141−
142− val title = stringResource(R.string.app_lock_prompt_title)
143− val subtitle = stringResource(R.string.app_lock_prompt_subtitle)
144−
145− // Track an in-flight prompt so a recomposition (or the retry button) can't stack two
146− // BiometricPrompts, which throws.
147− var authInFlight by remember { mutableStateOf(false) }
148− // Monotonic id for the current prompt. The system dismisses an in-flight BiometricPrompt when
149− // the app backgrounds and posts its onAuthenticationError asynchronously; without this, that
150− // stale error could land after ON_START already started a NEW prompt and clear authInFlight
151− // mid-prompt — letting a recomposition or the "Unlock" button (enabled = !authInFlight) stack
152− // a second prompt. Each prompt captures its id and only mutates state while it's still current.
153− val promptId = remember { intArrayOf(0) }
154−
155− fun authenticate() {
156− if (authInFlight || unlocked) return
157− authInFlight = true
158− val myPrompt = ++promptId[0]
159− val executor = ContextCompat.getMainExecutor(activity)
160− val callback = object : BiometricPrompt.AuthenticationCallback() {
161− override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
162− if (myPrompt != promptId[0]) return
163− authInFlight = false
164− unlocked = true
165− }
166−
167− override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
168− // User cancelled / lockout / hardware error: stay locked and let them retry
169− // via the button rather than looping the system prompt. Ignore a stale error
170− // from a prompt already superseded by a newer one (see promptId above).
171− if (myPrompt != promptId[0]) return
172− authInFlight = false
173− }
174−
175− override fun onAuthenticationFailed() {
176− // A single non-matching attempt; the system UI lets the user try again.
177− }
178− }
179− val info = BiometricPrompt.PromptInfo.Builder()
180− .setTitle(title)
181− .setSubtitle(subtitle)
182− .setAllowedAuthenticators(lockAuthenticators)
183− .build()
184− runCatching { BiometricPrompt(activity, executor, callback).authenticate(info) }
185− .onFailure { if (myPrompt == promptId[0]) authInFlight = false }
186− }
187−
188− // Re-lock when the app is backgrounded, and re-prompt when it returns to the foreground.
189− // The re-prompt fires on ON_START rather than by keying an effect on `unlocked`: ON_STOP
190− // already cleared `unlocked` while backgrounded, so an effect keyed on it would see no
191− // change on return and never re-fire, stranding the user on the manual "Unlock" button.
192− // addObserver also delivers the current state's ON_START to a freshly-added observer, so
193− // this covers the initial prompt on first show too; the authInFlight/unlocked guards in
194− // authenticate() make the overlapping triggers safe.
195− val lifecycleOwner = LocalLifecycleOwner.current
196− DisposableEffect(lifecycleOwner) {
197− val observer = LifecycleEventObserver { _, event ->
198− when (event) {
199− Lifecycle.Event.ON_STOP -> {
200− // Record the stop time but DON'T clear unlocked yet — the re-lock decision is
201− // made on the next ON_START, so a brief background stint under the grace period
202− // returns the user straight to their session without a re-prompt. authInFlight
203− // is still cleared because the system dismisses an in-flight prompt on background.
204− lastStopTimeMs[0] = System.currentTimeMillis()
205− authInFlight = false
206− }
207− Lifecycle.Event.ON_START -> {
208− // Only re-lock (and re-prompt) if more than the grace period elapsed since the
209− // last ON_STOP, or the app is freshly starting (lastStopTimeMs == 0).
210− val elapsed = System.currentTimeMillis() - lastStopTimeMs[0]
211− if (unlocked && lastStopTimeMs[0] != 0L && elapsed < reLockDelayMs) {
212− // Within the grace period — stay unlocked, no re-prompt.
213− } else {
214− unlocked = false
215− authenticate()
216− }
217− }
218− else -> {}
219− }
220− }
221− lifecycleOwner.lifecycle.addObserver(observer)
222− onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
223− }
224−
225− // Compose content ONLY while unlocked. Drawing the lock as an overlay *over* a still-composed
226− // content() cannot cover a Dialog / ModalBottomSheet / DropdownMenu / Popup: those render in
227− // separate windows z-ordered above the Activity content, so an open permission dialog or picker
228− // sheet would stay visible and interactive above the lock — an authentication bypass. Not
229− // composing content while locked removes those sub-windows entirely. The SaveableStateHolder
230− // preserves navigation/scroll/input state across the re-lock so unlocking returns the user where
231− // they were, replacing the previous "keep composed underneath" approach.
232− val stateHolder = rememberSaveableStateHolder()
233− if (unlocked) {
234− stateHolder.SaveableStateProvider(APP_LOCK_CONTENT_KEY) { content() }
235− } else {
236− // A Fingerprint glyph hints at the primary unlock method when a biometric is enrolled;
237− // fall back to the generic lock on credential-only setups. Computed once: enrollment
238− // doesn't change while the gate is shown, and re-prompting on each frame is wasteful.
239− val biometricAvailable = remember(context) {
240− BiometricManager.from(context)
241− .canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) ==
242− BiometricManager.BIOMETRIC_SUCCESS
243− }
244− val unlockLabel = stringResource(R.string.app_unlock)
245− Surface(
246− modifier = Modifier.fillMaxSize(),
247− color = MaterialTheme.colorScheme.background,
248− ) {
249− // The whole surface is tappable to re-trigger the prompt (in addition to the button),
250− // so a user who dismissed the system prompt can retry by tapping anywhere — not just
251− // by finding the Unlock button.
252− Column(
253− modifier = Modifier
254− .fillMaxSize()
255− .clickable(
256− enabled = !authInFlight,
257− role = Role.Button,
258− onClickLabel = unlockLabel,
259− ) { authenticate() }
260− .padding(32.dp),
261− horizontalAlignment = Alignment.CenterHorizontally,
262− verticalArrangement = Arrangement.Center,
263− ) {
264− Icon(
265− if (biometricAvailable) Icons.Filled.Fingerprint else Icons.Filled.Lock,
266− contentDescription = null,
267− modifier = Modifier.size(56.dp),
268− tint = MaterialTheme.colorScheme.primary,
269− )
270− Text(
271− stringResource(R.string.app_locked),
272− style = MaterialTheme.typography.titleMedium,
273− modifier = Modifier
274− .padding(top = 16.dp)
275− .semantics { liveRegion = LiveRegionMode.Polite },
276− )
277− Text(
278− stringResource(R.string.app_locked_hint),
279− style = MaterialTheme.typography.bodyMedium,
280− color = MaterialTheme.colorScheme.onSurfaceVariant,
281− modifier = Modifier.padding(top = 4.dp),
282− )
283− Button(
284− onClick = { authenticate() },
285− enabled = !authInFlight,
286− modifier = Modifier.padding(top = 24.dp),
287− ) {
288− if (authInFlight) {
289− LoadingSpinner(
290− size = LoadingSize.Small,
291− color = MaterialTheme.colorScheme.primary,
292− )
293− Spacer(Modifier.size(8.dp))
294− }
295− Text(unlockLabel)
296− }
297− }
298− }
299− }
300−}
301−
302−private const val APP_LOCK_CONTENT_KEY = "app_lock_content"
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+90−583
@@ -1,617 +1,124 @@
11package soy.iko.opencode.ui
22
3−import androidx.compose.animation.EnterTransition
4−import androidx.compose.animation.ExitTransition
5−import androidx.compose.animation.core.tween
6−import androidx.compose.animation.fadeIn
7−import androidx.compose.animation.fadeOut
3+import androidx.activity.compose.BackHandler
4+import androidx.compose.animation.AnimatedContent
85import androidx.compose.animation.slideInHorizontally
96import androidx.compose.animation.slideOutHorizontally
10−import androidx.compose.foundation.layout.Box
11−import androidx.compose.foundation.layout.BoxWithConstraints
12−import androidx.compose.foundation.layout.Row
13−import androidx.compose.foundation.layout.fillMaxHeight
7+import androidx.compose.animation.togetherWith
148import 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
1517import androidx.compose.runtime.Composable
16−import androidx.compose.runtime.CompositionLocalProvider
1718import androidx.compose.runtime.LaunchedEffect
1819import androidx.compose.runtime.getValue
1920import androidx.compose.runtime.mutableStateOf
2021import androidx.compose.runtime.remember
21−import androidx.compose.runtime.rememberCoroutineScope
22−import androidx.compose.runtime.saveable.rememberSaveable
2322import androidx.compose.runtime.setValue
2423import androidx.compose.ui.Modifier
25−import androidx.compose.ui.input.key.Key
26−import androidx.compose.ui.input.key.KeyEventType
27−import androidx.compose.ui.input.key.isCtrlPressed
28−import androidx.compose.ui.input.key.isAltPressed
29−import androidx.compose.ui.input.key.key
30−import androidx.compose.ui.input.key.onPreviewKeyEvent
31−import androidx.compose.ui.input.key.type
32−import androidx.compose.ui.platform.LocalContext
33−import androidx.compose.ui.platform.LocalDensity
34−import androidx.compose.ui.unit.dp
35−import androidx.compose.ui.unit.LayoutDirection
36−import androidx.compose.ui.platform.LocalLayoutDirection
37−import androidx.navigation.NavType
38−import androidx.navigation.NavGraph.Companion.findStartDestination
39−import androidx.navigation.compose.NavHost
40−import androidx.navigation.compose.composable
41−import androidx.navigation.compose.currentBackStackEntryAsState
42−import androidx.navigation.compose.rememberNavController
43−import androidx.navigation.navArgument
44−import androidx.lifecycle.compose.collectAsStateWithLifecycle
45−import kotlinx.coroutines.launch
46−import soy.iko.opencode.di.AppContainer
47−import soy.iko.opencode.data.network.NetworkConfig
48−import soy.iko.opencode.ui.chat.ChatScreen
49−import soy.iko.opencode.ui.file.FileBrowserScreen
50−import soy.iko.opencode.ui.file.FileViewScreen
51−import soy.iko.opencode.ui.file.TwoPaneFileBrowser
52−import soy.iko.opencode.ui.server.ServerEditScreen
53−import soy.iko.opencode.ui.server.ServerListScreen
54−import soy.iko.opencode.ui.search.GlobalSearchScreen
55−import androidx.compose.ui.platform.LocalHapticFeedback
56−import soy.iko.opencode.ui.components.LargeScreenNavRail
57−import soy.iko.opencode.ui.components.CompactNavBar
58−import soy.iko.opencode.ui.components.LocalChatTextScale
59−import soy.iko.opencode.ui.components.LocalCodeWrap
60−import soy.iko.opencode.ui.components.LocalReducedMotion
61−import soy.iko.opencode.ui.components.isReducedMotion
62−import soy.iko.opencode.ui.components.rememberGatedHaptics
63−import soy.iko.opencode.ui.session.SessionListScreen
64−import soy.iko.opencode.ui.session.TwoPaneSessionChat
65−import soy.iko.opencode.ui.settings.DiagnosticsScreen
66−import soy.iko.opencode.ui.settings.SettingsScreen
67−import soy.iko.opencode.ui.usage.UsageScreen
68−import soy.iko.opencode.ui.mcp.McpScreen
69−import soy.iko.opencode.util.findActivity
70−import soy.iko.opencode.util.runCatchingCancellable
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
7130
7231@Composable
73−fun OpencodeApp(container: AppContainer) {
74− val navController = rememberNavController()
75− val scope = rememberCoroutineScope()
76− val pendingShare by container.pendingShare.collectAsStateWithLifecycle()
77− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
78− val pendingOpenSession by container.pendingOpenSession.collectAsStateWithLifecycle()
79− val pendingNewSession by container.pendingNewSession.collectAsStateWithLifecycle()
80− val pendingOpenFile by container.pendingOpenFile.collectAsStateWithLifecycle()
81− val pendingDiagnostics by container.pendingDiagnostics.collectAsStateWithLifecycle()
82− val connection by container.activeConnection.collectAsStateWithLifecycle()
83− // Chat presentation preferences, provided to the whole nav graph so the markdown/code
84− // renderers honor the user's text-size and code-wrap choices everywhere.
85− val chatTextScale by container.settingsStore.chatTextScale.collectAsStateWithLifecycle(initialValue = 1f)
86− val codeWrap by container.settingsStore.codeWrap.collectAsStateWithLifecycle(initialValue = false)
87− // Haptics gating: collected once at the root so the in-app toggle can disable all
88− // performHapticFeedback calls everywhere via a single CompositionLocalProvider, instead
89− // of each call site needing to read the setting. Defaults true (the prior behavior) so
90− // the brief window before DataStore loads still haptics as before.
91− val hapticsEnabled by container.settingsStore.hapticsEnabled.collectAsStateWithLifecycle(initialValue = true)
92−
93− // The foreground service that holds priority while any run is active is driven from the
94− // process-lived AppContainer scope (see AppContainer.observeRunForegroundService), not
95− // from here — a composition-scoped collector pauses while backgrounded, which is exactly
96− // when a run started via the notification reply needs the service to start.
97−
98− // When text is shared into the app, surface the session list so the user can pick
99− // (or create) a conversation to drop it into. The chosen session's draft is set
100− // in [onOpenSession] below. Keyed on `connection` too so a share that arrives
101− // before auto-reconnect completes is retried once the connection is established.
102− // Track the last-handled share payloads (there's no share nonce on the container) so a
103− // *new* share arriving while already connected — a warm start where onNewIntent re-fires
104− // setPendingShare under an unchanged connection id — still navigates, while a re-trigger
105− // carrying no new share (a bare server switch, which routes through a null connection, or
106− // a share the user already navigated for) leaves them where they are.
107− //
108− // Reset the remembered media when the pending list is drained (the chosen ChatScreen
109− // consumes it via consumePendingSharedMedia). Without this, re-sharing the *same* images
110− // after consumption compares equal structurally ([A,B] == [A,B]) and would be treated as
111− // "already handled", silently skipping the session-list navigation the second time.
112− //
113− // rememberSaveable (not remember) so a process-kill restore doesn't reset the dedup
114− // state and re-navigate to SESSIONS for a share the user already handled before the kill.
115− var handledShareText by rememberSaveable { mutableStateOf<String?>(null) }
116− var handledSharedMedia by rememberSaveable { mutableStateOf<List<String>>(emptyList()) }
117− LaunchedEffect(pendingShare, pendingSharedMedia, connection) {
118− // Reset the remembered handled state for each channel independently as it drains,
119− // so re-sharing the same payload after consumption is still recognized as new. A
120− // joint reset (only when both are empty) would drop a text-only re-share that
121− // follows a text+media share of the same text: the text channel matches its
122− // remembered value while the media channel is empty (not "new"), so neither clause
123− // fires and the share is silently swallowed.
124− if (pendingShare == null) handledShareText = null
125− if (pendingSharedMedia.isEmpty()) handledSharedMedia = emptyList()
126− if (pendingShare == null && pendingSharedMedia.isEmpty()) return@LaunchedEffect
127− if (connection == null) return@LaunchedEffect
128− val newShare = (pendingShare != null && pendingShare != handledShareText) ||
129− (pendingSharedMedia.isNotEmpty() && pendingSharedMedia != handledSharedMedia)
130− if (!newShare) return@LaunchedEffect
131− handledShareText = pendingShare
132− handledSharedMedia = pendingSharedMedia
133− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
134− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
135− }
136− }
137−
138− // Crash-relaunch prompt: navigate to the Diagnostics screen when the user taps
139− // "View report" on the cold-start crash dialog. Doesn't require a connection.
140− LaunchedEffect(pendingDiagnostics) {
141− if (!pendingDiagnostics) return@LaunchedEffect
142− container.consumePendingDiagnostics()
143− navController.navigate(Routes.DIAGNOSTICS) { launchSingleTop = true }
144− }
145−
146− // "New session" from a launcher shortcut / QS tile: once connected, create a fresh
147− // session and open it. The pending counter is consumed only *after* createSession
148− // succeeds, so a transient failure leaves the request pending to retry (on the next
149− // connection change or a re-tap that increments the counter) instead of silently
150− // dropping the tap.
151− LaunchedEffect(pendingNewSession, connection) {
152− if (pendingNewSession == 0) return@LaunchedEffect
153− val conn = connection ?: return@LaunchedEffect
154− val session = runCatchingCancellable { conn.repository.createSession() }.getOrNull()
155− ?: return@LaunchedEffect
156− if (!container.consumePendingNewSession()) return@LaunchedEffect
157− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
158− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
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)
15946 }
160− navController.navigate(Routes.chat(session.id)) { launchSingleTop = true }
161− }
162−
163− // The chat text-size preference multiplies on top of the OS font scale (sp already
164− // honors the system setting), so a large system size × large app size can reach ~2×
165− // and break tight layouts. Clamp the provided app scale so the product with the OS
166− // fontScale never exceeds NetworkConfig.maxCombinedFontScale, while never scaling
167− // below the user's chosen value's intent (floor of 1× app scale is preserved when the
168− // system size alone already exceeds the cap).
169− val systemFontScale = LocalDensity.current.fontScale
170− val clampedChatTextScale = if (systemFontScale <= 0f) {
171− chatTextScale
172− } else {
173− chatTextScale.coerceAtMost(
174− (NetworkConfig.maxCombinedFontScale / systemFontScale).coerceAtLeast(1f)
175− )
17647 }
17748
178− // Capture the reduced-motion preference once (in the composable scope) so the
179− // non-composable NavHost transition lambdas can use it to skip animations, and provide
180− // it via LocalReducedMotion so in-composition animations (chat row placement, banners,
181− // image zoom) honor the same accessibility preference.
182− val reducedMotion = isReducedMotion()
183− CompositionLocalProvider(
184− LocalChatTextScale provides clampedChatTextScale,
185− LocalCodeWrap provides codeWrap,
186− LocalReducedMotion provides reducedMotion,
187− LocalHapticFeedback provides rememberGatedHaptics(hapticsEnabled),
188− ) {
189− // Slide direction for push/pop transitions, mirrored in RTL so the animation reads
190− // naturally instead of "going the wrong way". +1 = LTR (push from right), -1 = RTL.
191− val slideDir = if (LocalLayoutDirection.current == LayoutDirection.Rtl) -1 else 1
192− // Adaptive: on wide screens (tablets / unfolded foldables) show the session list and
193− // the open conversation side by side instead of a single-pane back stack.
194− // Posture-aware: a foldable in HALF_OPENED (tabletop/book) mode has a hinge across the
195− // content area — splitting there would place the list/detail boundary on the hinge, which
196− // is hard to read and interact with. Detect a FoldingFeature and suppress two-pane in
197− // those postures so the app falls back to a single-pane layout that respects the fold.
198− val windowContext = LocalContext.current
199− var foldState by remember { mutableStateOf<androidx.window.layout.FoldingFeature?>(null) }
200− androidx.compose.runtime.LaunchedEffect(windowContext) {
201− val activity = windowContext.findActivity()
202− if (activity != null) {
203− androidx.window.layout.WindowInfoTracker.getOrCreate(windowContext)
204− .windowLayoutInfo(activity)
205− .collect { info ->
206− foldState = info.displayFeatures
207− .filterIsInstance<androidx.window.layout.FoldingFeature>()
208− .firstOrNull()
209− }
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
21056 }
21157 }
212− val isHalfOpened = foldState?.state == androidx.window.layout.FoldingFeature.State.HALF_OPENED
213− BoxWithConstraints(
214− modifier = Modifier.onPreviewKeyEvent { ev ->
215− // Global keyboard shortcuts for hardware-keyboard users (tablets, DeX, Chromebook):
216− // Ctrl+1..6 switches between top-level destinations. Only fires on KeyDown so a
217− // held Ctrl doesn't re-trigger on every repeat. Per-screen shortcuts (Ctrl+K palette,
218− // Esc stop, Ctrl+F find) are handled in each screen's own onPreviewKeyEvent and take
219− // precedence (they're closer to the focused composable in the tree).
220− if (ev.type != KeyEventType.KeyDown || !ev.isCtrlPressed) {
221− // Alt+Left (a familiar desktop "Back" gesture) pops the back stack. Not gated
222− // on Ctrl so it works as a standalone modifier. Per-screen shortcuts (Esc
223− // stop, Ctrl+F find, Ctrl+K palette) register their own onPreviewKeyEvent
224− // closer to the focused composable and consume first, so this only pops when
225− // nothing nearer handled the key — avoiding conflicts with open dialogs and
226− // text fields. Esc is deliberately NOT mapped to back here for that reason.
227− if (ev.type == KeyEventType.KeyDown &&
228− ev.key == Key.DirectionLeft &&
229− ev.isAltPressed
230− ) {
231− if (navController.previousBackStackEntry != null) {
232− navController.popBackStack()
233− return@onPreviewKeyEvent true
234− }
235− }
236− return@onPreviewKeyEvent false
237− }
238− val route = when (ev.key) {
239− Key.NumPad1, Key.One -> Routes.SESSIONS
240− Key.NumPad2, Key.Two -> Routes.SEARCH
241− Key.NumPad3, Key.Three -> Routes.FILES
242− Key.NumPad4, Key.Four -> Routes.USAGE
243− Key.NumPad5, Key.Five -> Routes.MCP
244− Key.NumPad6, Key.Six -> Routes.SETTINGS
245− // Ctrl+7 navigates to the server list (the 7th nav-rail destination).
246− // Previously Ctrl+1..6 covered the other destinations but Servers was
247− // missing, an inconsistency since the nav rail shows 7 destinations.
248− Key.NumPad7, Key.Seven -> Routes.SERVERS
249− else -> null
250− }
251− if (route != null) {
252− // Servers is reachable even without an active connection (it's the start
253− // destination and handles the not-connected state); the other routes
254− // require a connection to be meaningful.
255− if (route == Routes.SERVERS || connection != null) {
256− navController.navigate(route) {
257− popUpTo(navController.graph.findStartDestination().id) { saveState = true }
258− launchSingleTop = true
259− restoreState = true
260− }
261− true
262− } else false
263− } else false
264− },
265− ) {
266− val isTwoPane = maxWidth >= NetworkConfig.twoPaneWidthThresholdDp.dp &&
267− connection != null &&
268− !isHalfOpened
269− // On large screens, surface a navigation rail alongside the content so top-level
270− // destinations (Sessions, Files, Search, …) are one tap away instead of buried in a
271− // screen's overflow menu. Mirrors the standard large-screen M3 layout.
272− val showNavRail = maxWidth >= NetworkConfig.navigationRailThresholdDp.dp
273− // Observe the current destination reactively so the rail's selected item tracks navigation
274− // (reading currentDestination once would go stale after the first composition).
275− val currentEntry by navController.currentBackStackEntryAsState()
276− val currentRoute = currentEntry?.destination?.route
277−
278− // Open a session requested by a notification tap or deep link, once connected.
279− LaunchedEffect(pendingOpenSession, connection, isTwoPane) {
280− val pending = pendingOpenSession ?: return@LaunchedEffect
281− if (connection == null) return@LaunchedEffect
282− // If the notification body-tap carries a profile id from a different server,
283− // switch to it first so the session opens under the server that ran it, not
284− // whichever is active. The effect re-runs when connection changes (keyed on it),
285− // so on the second run the profile matches and the open proceeds.
286− if (pending.profileId != null && connection?.profile?.id != pending.profileId) {
287− if (!container.connectByProfileId(pending.profileId)) return@LaunchedEffect
288− return@LaunchedEffect // re-run on the new connection
289− }
290− // In two-pane mode the detail pane (TwoPaneSessionChat, hosted on the SESSIONS
291− // route) consumes the request and opens it in the detail pane. But it only
292− // exists while the NavHost is on SESSIONS, so if the user is currently on
293− // Files/Settings/FileView bring SESSIONS back to front first — otherwise the
294− // pending request is never consumed and the session never opens. Don't consume
295− // here; let TwoPaneSessionChat's effect do it once it's composed.
296− if (isTwoPane) {
297− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
298− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
299− }
300− return@LaunchedEffect
301− }
302− container.consumePendingOpenSession()
303− // Ensure SESSIONS sits on the back stack below the chat destination so backing
304− // out of the chat lands on the session list (not the server list). Bring SESSIONS
305− // to front (or push it if a cold-start deep link left only SERVERS on the stack),
306− // then push chat on top — yielding SERVERS -> SESSIONS -> chat.
307− if (!navController.popBackStack(Routes.SESSIONS, inclusive = false)) {
308− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
309− }
310− navController.navigate(Routes.chat(pending.sessionId)) { launchSingleTop = true }
311− }
31258
313− // Deep-linked file open (opencode://file/{path}): navigate to the file viewer once a
314− // connection exists (the viewer fetches content from the server). Path comes pre-validated
315− // by MainActivity's deep-link guard. In two-pane mode the detail pane (TwoPaneFileBrowser,
316− // hosted on the FILES route) consumes the request into its detail pane, mirroring how
317− // session deep links are routed — so don't consume or push the full-screen viewer here.
318− LaunchedEffect(pendingOpenFile, connection, isTwoPane) {
319− val path = pendingOpenFile ?: return@LaunchedEffect
320− if (connection == null) return@LaunchedEffect
321− if (isTwoPane) {
322− if (!navController.popBackStack(Routes.FILES, inclusive = false)) {
323− navController.navigate(Routes.FILES) { launchSingleTop = true }
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")
32471 }
325− return@LaunchedEffect
326− }
327− container.consumePendingOpenFile()
328− if (!navController.popBackStack(Routes.FILES, inclusive = false)) {
329− navController.navigate(Routes.FILES) { launchSingleTop = true }
330− }
331− navController.navigate(Routes.fileView(path)) { launchSingleTop = true }
332− }
333−
334− val navHost = @Composable {
335− NavHost(
336− modifier = Modifier.fillMaxSize(),
337− navController = navController,
338− startDestination = Routes.SERVERS,
339− // Motion-aware transitions: respect the user's reduced-motion setting
340− // (Developer Options → animator scale 0) by skipping animations entirely.
341− // Per-destination tuning: a chat→chat navigation (switching peer conversations
342− // within the same surface) crossfades instead of sliding, so it reads as a peer
343− // switch rather than drilling into a new section. Top-level destinations and
344− // detail pushes keep the horizontal slide.
345− enterTransition = {
346− if (reducedMotion) {
347− EnterTransition.None
348− } else if (targetState.destination.route?.startsWith("${Routes.CHAT}/") == true) {
349− fadeIn(tween(NetworkConfig.motionFadeDurationMs))
350− } else {
351− slideInHorizontally(animationSpec = tween(NetworkConfig.motionSlideDurationMs)) { it * slideDir } +
352− fadeIn(tween(NetworkConfig.motionFadeDurationMs))
72+ },
73+ dismissButton = {
74+ TextButton(onClick = { showStopConfirm = false }) {
75+ Text("Stay")
35376 }
35477 },
355− exitTransition = {
356− if (reducedMotion) {
357− ExitTransition.None
358− } else {
359− fadeOut(tween(NetworkConfig.motionFadeDurationMs))
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")
36092 }
36193 },
362− popEnterTransition = {
363− if (reducedMotion) {
364− EnterTransition.None
365− } else {
366− fadeIn(tween(NetworkConfig.motionFadeDurationMs))
94+ dismissButton = {
95+ TextButton(onClick = { showDisconnectConfirm = false }) {
96+ Text("Cancel")
36797 }
36898 },
369− popExitTransition = {
370− if (reducedMotion) {
371− ExitTransition.None
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 }
372111 } else {
373− slideOutHorizontally(animationSpec = tween(NetworkConfig.motionSlideDurationMs)) { it * slideDir } +
374− fadeOut(tween(NetworkConfig.motionFadeDurationMs))
112+ slideInHorizontally { -it } togetherWith slideOutHorizontally { it }
375113 }
376114 },
377− ) {
378−
379− composable(Routes.SERVERS) {
380− ServerListScreen(
381− container = container,
382− onConnected = {
383− // Only leave the server list if we're still on it. A pending deep-link /
384− // notification open sets activeConnection (which drives the open-session
385− // effect: SERVERS -> SESSIONS -> chat) *before* autoConnectDone fires this
386− // callback, so a blind navigate(SESSIONS) here would slam a second SESSIONS
387− // on top of the chat it just opened, burying it. Order-independent: if the
388− // deep link already navigated away from SERVERS, this is a no-op.
389− if (navController.currentDestination?.route == Routes.SERVERS) {
390− navController.navigate(Routes.SESSIONS) { launchSingleTop = true }
391− }
392− },
393− onAddProfile = { navController.navigate(Routes.serverEdit()) },
394− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
395− onDuplicateProfile = { id -> navController.navigate(Routes.serverEditDuplicate(id)) },
396− )
397− }
398−
399− composable(
400− route = "${Routes.SERVER_EDIT}?id={id}&dup={dup}",
401− arguments = listOf(
402− navArgument("id") { type = NavType.StringType; nullable = true; defaultValue = null },
403− navArgument("dup") { type = NavType.StringType; nullable = true; defaultValue = null },
404− ),
405− ) { entry ->
406− ServerEditScreen(
407− container = container,
408− profileId = entry.arguments?.getString("id"),
409− sourceId = entry.arguments?.getString("dup"),
410− onDone = { navController.popBackStack() },
411− )
412− }
413−
414− composable(Routes.SESSIONS) {
415− if (isTwoPane) {
416− TwoPaneSessionChat(
417− container = container,
418− onOpenFiles = { navController.navigate(Routes.FILES) },
419− onOpenFile = { path -> navController.navigate(Routes.fileView(path)) },
420− onOpenSettings = { navController.navigate(Routes.SETTINGS) },
421− onOpenSearch = { navController.navigate(Routes.SEARCH) },
422− onDisconnect = {
423− scope.launch { runCatchingCancellable { container.disconnect() } }
424− navController.popBackStack(Routes.SERVERS, inclusive = false)
425− },
426− onAddServer = { navController.navigate(Routes.serverEdit()) },
427− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
428− )
429− } else {
430− SessionListScreen(
431− container = container,
432− onOpenSession = { id ->
433− // Set the draft synchronously in-memory before navigating so the
434− // ChatScreen sees it on first composition. The async persistence
435− // to disk happens in the background via draftStore.set.
436− container.consumePendingShare()?.let { shareText ->
437− container.draftStore.setImmediate(id, shareText)
438− scope.launch { runCatchingCancellable { container.draftStore.set(id, shareText) } }
439− }
440− navController.navigate(Routes.chat(id))
441− },
442− onDisconnect = {
443− scope.launch { runCatchingCancellable { container.disconnect() } }
444− navController.popBackStack(Routes.SERVERS, inclusive = false)
445− },
446− onOpenFiles = { navController.navigate(Routes.FILES) },
447− onOpenSettings = { navController.navigate(Routes.SETTINGS) },
448− onOpenSearch = { navController.navigate(Routes.SEARCH) },
449− onAddServer = { navController.navigate(Routes.serverEdit()) },
450− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
451− )
452− }
453− }
454−
455− composable(
456− route = "${Routes.CHAT}/{sessionId}?focus={focus}",
457− arguments = listOf(
458− navArgument("sessionId") { type = NavType.StringType },
459− navArgument("focus") { type = NavType.StringType; nullable = true; defaultValue = null },
460− ),
461− ) { entry ->
462− ChatScreen(
463− container = container,
464− sessionId = entry.arguments?.getString("sessionId").orEmpty(),
465− focusMessageId = entry.arguments?.getString("focus"),
466− onBack = { navController.popBackStack() },
467− onOpenFile = { path -> navController.navigate(Routes.fileView(path)) },
468− onOpenSession = { id ->
469− navController.navigate(Routes.chat(id)) {
470− // Prevent the same chat from being pushed twice when re-tapping a
471− // session deep link, and keep the back stack bounded when chaining
472− // chat → linked chat → … (otherwise every hop piles a new entry).
473− launchSingleTop = true
474− }
475− },
476− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
477− )
478− }
479−
480− composable(Routes.FILES) {
481− if (isTwoPane) {
482− TwoPaneFileBrowser(
483− container = container,
484− onBack = { navController.popBackStack() },
485− )
486− } else {
487− FileBrowserScreen(
488− container = container,
489− onOpenFile = { path, line -> navController.navigate(Routes.fileView(path, line)) },
490− onBack = { navController.popBackStack() },
491− )
492− }
493− }
494−
495− composable(
496− route = "${Routes.FILE_VIEW}?path={path}&line={line}",
497− arguments = listOf(
498− navArgument("path") { type = NavType.StringType; defaultValue = "" },
499− navArgument("line") { type = NavType.IntType; defaultValue = -1 },
500− ),
501− ) { entry ->
502− val line = entry.arguments?.getInt("line") ?: -1
503− FileViewScreen(
504− container = container,
505− path = entry.arguments?.getString("path").orEmpty(),
506− initialLine = line.takeIf { it > 0 },
507− onBack = { navController.popBackStack() },
508− )
509− }
510−
511− composable(Routes.SETTINGS) {
512− SettingsScreen(
513− container = container,
514− onBack = { navController.popBackStack() },
515− // Navigate to the server list as a new entry on top of Sessions so the
516− // user can back out to their conversations. Previously this popped back
517− // to the root SERVERS destination, which removed Sessions from the stack
518− // and left the user unable to return to their conversations without
519− // reconnecting. Pop only Settings, then push SERVERS; back from the
520− // server list lands on Sessions (the screen the user was on before
521− // Settings), and connecting pushes a fresh SESSIONS as usual.
522− onManageServers = {
523− navController.navigate(Routes.SERVERS) {
524− popUpTo(Routes.SETTINGS) { inclusive = true }
525− launchSingleTop = true
526− }
527− },
528− onOpenDiagnostics = { navController.navigate(Routes.DIAGNOSTICS) },
529− onOpenUsage = { navController.navigate(Routes.USAGE) },
530− onOpenMcp = { navController.navigate(Routes.MCP) },
531− onEditProfile = { id -> navController.navigate(Routes.serverEdit(id)) },
532− )
533− }
534−
535− composable(Routes.DIAGNOSTICS) {
536− DiagnosticsScreen(onBack = { navController.popBackStack() })
537− }
538−
539− composable(Routes.USAGE) {
540− UsageScreen(
541− container = container,
542− onBack = { navController.popBackStack() },
543− onOpenSession = { id -> navController.navigate(Routes.chat(id)) },
544− )
545− }
546−
547− composable(Routes.MCP) {
548− McpScreen(container = container, onBack = { navController.popBackStack() })
549− }
550−
551− composable(Routes.SEARCH) {
552− GlobalSearchScreen(
553− container = container,
554− onOpenSession = { id, focusMessageId -> navController.navigate(Routes.chat(id, focusMessageId)) },
555− onBack = { navController.popBackStack() },
556− )
557− }
558− }
559− }
560−
561− // Collect unread/run state for nav badges (rail on large screens, bottom bar on
562− // compact screens), so a user on Files/Settings sees pending activity at a glance.
563− val unread by container.unread.collectAsStateWithLifecycle()
564− val anyRunActive by container.anyRunActive.collectAsStateWithLifecycle()
565− val totalUnread = remember(unread) { unread.values.sum() }
566−
567− if (showNavRail) {
568− Row(modifier = Modifier.fillMaxSize()) {
569− LargeScreenNavRail(
570− currentRoute = currentRoute,
571− connected = connection != null,
572− unreadCount = totalUnread,
573− runActive = anyRunActive,
574− // Use the standard M3 nav-bar pattern: popUpTo the start destination
575− // saving state, and restoreState on re-entry, so switching between
576− // top-level tabs via the rail preserves each tab's scroll/selection
577− // state and back always exits cleanly instead of popping through
578− // every sibling tab the user visited.
579− onNavigate = { route ->
580− navController.navigate(route) {
581− popUpTo(navController.graph.findStartDestination().id) {
582− saveState = true
583− }
584− launchSingleTop = true
585− restoreState = true
586− }
587− },
588− )
589− Box(modifier = Modifier.weight(1f).fillMaxHeight()) { navHost() }
590− }
591− } else {
592− // Compact screens: a bottom NavigationBar surfaces the top-level destinations one
593− // tap away (Sessions/Search/Files/Settings/Servers) instead of buried in each
594− // screen's overflow menu. The navHost fills the space above the bar; the bar's
595− // own height is accounted for by the NavigationBar's intrinsic measurement.
596− androidx.compose.foundation.layout.Column(modifier = Modifier.fillMaxSize()) {
597− Box(modifier = Modifier.weight(1f).fillMaxHeight()) { navHost() }
598− CompactNavBar(
599− currentRoute = currentRoute,
600− connected = connection != null,
601− unreadCount = totalUnread,
602− runActive = anyRunActive,
603− onNavigate = { route ->
604− navController.navigate(route) {
605− popUpTo(navController.graph.findStartDestination().id) {
606− saveState = true
607− }
608− launchSingleTop = true
609− restoreState = true
610− }
611− },
612− )
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)
613121 }
614122 }
615123 }
616− }
617124}
app/src/main/java/soy/iko/opencode/ui/Routes.ktdeleted−39
@@ -1,39 +0,0 @@
1−package soy.iko.opencode.ui
2−
3−/** String routes for the app's NavHost. Kept simple and centralized. */
4−object Routes {
5− const val SERVERS = "servers"
6− const val SESSIONS = "sessions"
7− const val SETTINGS = "settings"
8− const val DIAGNOSTICS = "diagnostics"
9− const val USAGE = "usage"
10− const val MCP = "mcp"
11− const val FILES = "files"
12− const val SEARCH = "search"
13−
14− const val SERVER_EDIT = "server_edit"
15− fun serverEdit(id: String? = null) =
16− if (id.isNullOrEmpty()) SERVER_EDIT else "$SERVER_EDIT?id=${android.net.Uri.encode(id)}"
17−
18− /** Open the editor seeded with [sourceId]'s fields but creating a new profile. */
19− fun serverEditDuplicate(sourceId: String) = "$SERVER_EDIT?dup=${android.net.Uri.encode(sourceId)}"
20−
21− const val CHAT = "chat"
22− fun chat(sessionId: String, focusMessageId: String? = null): String {
23− val base = "$CHAT/${android.net.Uri.encode(sessionId)}"
24− // An optional focusMessageId scrolls the chat to (and briefly highlights) that message,
25− // used by global search to jump directly to the matched message instead of the tail.
26− return if (focusMessageId != null && focusMessageId.isNotBlank()) {
27− "$base?focus=${android.net.Uri.encode(focusMessageId)}"
28− } else {
29− base
30− }
31− }
32−
33− const val FILE_VIEW = "file_view"
34− fun fileView(path: String, line: Int? = null): String {
35− val base = "$FILE_VIEW?path=${android.net.Uri.encode(path)}"
36− // A positive [line] scrolls the viewer to that 1-based line (from a search hit).
37− return if (line != null && line > 0) "$base&line=$line" else base
38− }
39−}
app/src/main/java/soy/iko/opencode/ui/VmFactory.ktdeleted−16
@@ -1,16 +0,0 @@
1−package soy.iko.opencode.ui
2−
3−import androidx.lifecycle.ViewModel
4−import androidx.lifecycle.viewmodel.CreationExtras
5−import androidx.lifecycle.viewmodel.initializer
6−import androidx.lifecycle.viewmodel.viewModelFactory
7−
8−/**
9− * Tiny bridge between manual DI and Compose's `viewModel()`. Builds a
10− * [androidx.lifecycle.ViewModelProvider.Factory] from a plain constructor lambda.
11− */
12−inline fun <reified VM : ViewModel> vmFactory(
13− crossinline create: (CreationExtras) -> VM,
14−) = viewModelFactory {
15− initializer { create(this) }
16−}
app/src/main/java/soy/iko/opencode/ui/chat/AgentPickerSheet.ktdeleted−318
@@ -1,318 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import androidx.compose.foundation.clickable
4−import androidx.compose.foundation.layout.Column
5−import androidx.compose.foundation.layout.Row
6−import androidx.compose.foundation.layout.fillMaxWidth
7−import androidx.compose.foundation.layout.heightIn
8−import androidx.compose.foundation.layout.imePadding
9−import androidx.compose.foundation.layout.navigationBarsPadding
10−import androidx.compose.foundation.layout.padding
11−import androidx.compose.foundation.layout.size
12−import androidx.compose.foundation.lazy.LazyColumn
13−import androidx.compose.foundation.lazy.items
14−import androidx.compose.foundation.lazy.rememberLazyListState
15−import androidx.compose.foundation.text.KeyboardActions
16−import androidx.compose.foundation.text.KeyboardOptions
17−import androidx.compose.material.icons.Icons
18−import androidx.compose.material.icons.filled.Check
19−import androidx.compose.material.icons.filled.Close
20−import androidx.compose.material.icons.filled.Search
21−import androidx.compose.material3.CircularProgressIndicator
22−import androidx.compose.material3.ExperimentalMaterial3Api
23−import androidx.compose.material3.Icon
24−import androidx.compose.material3.IconButton
25−import androidx.compose.material3.MaterialTheme
26−import androidx.compose.material3.ModalBottomSheet
27−import androidx.compose.material3.OutlinedTextField
28−import androidx.compose.material3.Text
29−import androidx.compose.material3.TextButton
30−import androidx.compose.material3.rememberModalBottomSheetState
31−import androidx.compose.runtime.Composable
32−import androidx.compose.runtime.LaunchedEffect
33−import androidx.compose.runtime.getValue
34−import androidx.compose.runtime.mutableStateOf
35−import androidx.compose.runtime.remember
36−import androidx.compose.runtime.rememberCoroutineScope
37−import androidx.compose.runtime.saveable.rememberSaveable
38−import androidx.compose.runtime.setValue
39−import androidx.compose.ui.Alignment
40−import androidx.compose.ui.Modifier
41−import androidx.compose.ui.focus.FocusRequester
42−import androidx.compose.ui.focus.focusRequester
43−import androidx.compose.ui.hapticfeedback.HapticFeedbackType
44−import androidx.compose.ui.platform.LocalHapticFeedback
45−import androidx.compose.ui.platform.LocalSoftwareKeyboardController
46−import androidx.compose.ui.res.stringResource
47−import androidx.compose.ui.semantics.Role
48−import androidx.compose.ui.semantics.contentDescription
49−import androidx.compose.ui.semantics.role
50−import androidx.compose.ui.semantics.selectableGroup
51−import androidx.compose.ui.semantics.selected
52−import androidx.compose.ui.semantics.semantics
53−import androidx.compose.ui.text.input.ImeAction
54−import androidx.compose.ui.text.style.TextOverflow
55−import androidx.compose.ui.unit.dp
56−import androidx.compose.foundation.layout.Box
57−import kotlinx.coroutines.launch
58−import soy.iko.opencode.data.model.Agent
59−import soy.iko.opencode.data.network.NetworkConfig
60−import soy.iko.opencode.R
61−
62−/**
63− * Flat LazyColumn index of the selected agent, offset by the leading "Default" row when it's
64− * shown. A null selection targets that Default row (index 0). -1 when the selection isn't in
65− * the current list.
66− */
67−/** Whether the synthetic "Default" agent row matches the current search query. */
68−private fun defaultAgentMatches(query: String, label: String, desc: String): Boolean =
69− query.isEmpty() ||
70− label.contains(query, ignoreCase = true) ||
71− desc.contains(query, ignoreCase = true)
72−
73−private fun selectedAgentIndex(
74− distinctAgents: List<Agent>,
75− selected: String?,
76− defaultMatches: Boolean,
77−): Int {
78− if (selected == null) return if (defaultMatches) 0 else -1
79− val base = if (defaultMatches) 1 else 0
80− val pos = distinctAgents.indexOfFirst { it.name == selected }
81− return if (pos >= 0) base + pos else -1
82−}
83−
84−/** Bottom sheet that lists every agent and lets the user pick one. */
85−@OptIn(ExperimentalMaterial3Api::class)
86−@Composable
87−fun AgentPickerSheet(
88− agents: List<Agent>,
89− selected: String?,
90− loading: Boolean,
91− error: Boolean,
92− onSelect: (Agent?) -> Unit,
93− onRetry: () -> Unit,
94− onDismiss: () -> Unit,
95−) {
96− // Hoist the SheetState so selection can animate the sheet out (slide) instead of
97− // snap-dismissing by tearing down the composition. skipPartiallyExpanded = true so the
98− // sheet opens at full height and the list's heightIn cap resolves against a stable sheet,
99− // not the half-height partial state (which previously left the list at ~25% of the screen
100− // until the user dragged up).
101− val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
102− val scope = rememberCoroutineScope()
103− ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
104− Text(
105− stringResource(R.string.agent),
106− style = MaterialTheme.typography.titleMedium,
107− modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
108− )
109− if (loading) {
110− val loadingLabel = stringResource(R.string.loading_agents)
111− Column(
112− modifier = Modifier.fillMaxWidth().padding(vertical = 24.dp).imePadding(),
113− horizontalAlignment = Alignment.CenterHorizontally,
114− ) {
115− CircularProgressIndicator(Modifier.semantics { contentDescription = loadingLabel })
116− Text(
117− stringResource(R.string.loading_agents),
118− style = MaterialTheme.typography.bodyMedium,
119− color = MaterialTheme.colorScheme.onSurfaceVariant,
120− modifier = Modifier.padding(top = 8.dp),
121− )
122− }
123− } else if (error && agents.isEmpty()) {
124− Column(
125− modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 16.dp),
126− horizontalAlignment = Alignment.CenterHorizontally,
127− ) {
128− Text(
129− stringResource(R.string.load_failed),
130− style = MaterialTheme.typography.bodyMedium,
131− color = MaterialTheme.colorScheme.error,
132− )
133− TextButton(onClick = onRetry) { Text(stringResource(R.string.retry)) }
134− }
135− } else if (agents.isEmpty()) {
136− Text(
137− stringResource(R.string.no_agents),
138− style = MaterialTheme.typography.bodyMedium,
139− color = MaterialTheme.colorScheme.onSurfaceVariant,
140− modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp),
141− )
142− } else {
143− var query by rememberSaveable { mutableStateOf("") }
144− val keyboardController = LocalSoftwareKeyboardController.current
145− val haptics = LocalHapticFeedback.current
146− // Auto-focus the search field (and raise the keyboard) when the sheet opens, but skip
147− // it for a short catalog that's faster to scan by eye than to filter.
148− val searchFocus = remember { FocusRequester() }
149− LaunchedEffect(Unit) {
150− if (agents.size > NetworkConfig.pickerSearchAutofocusThreshold) {
151− runCatching { searchFocus.requestFocus() }
152− }
153− }
154− OutlinedTextField(
155− value = query,
156− onValueChange = { query = it },
157− modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp).focusRequester(searchFocus),
158− placeholder = { Text(stringResource(R.string.search_agents)) },
159− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
160− trailingIcon = if (query.isNotEmpty()) {
161− {
162− IconButton(onClick = { query = "" }) {
163− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
164− }
165− }
166− } else null,
167− singleLine = true,
168− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
169− keyboardActions = KeyboardActions(onSearch = { keyboardController?.hide() }),
170− )
171− // Dedupe the source list once (keyed on `agents`, not the per-keystroke `filtered`),
172− // so distinctBy doesn't re-walk the catalog on every character typed.
173− val distinctAgents = remember(agents) { agents.distinctBy { it.name } }
174− val filtered = remember(distinctAgents, query) {
175− val q = query.trim()
176− if (q.isEmpty()) distinctAgents
177− else distinctAgents.filter {
178− it.name.contains(q, ignoreCase = true) ||
179− it.displayDescription.contains(q, ignoreCase = true)
180− }
181− }
182− // The "Default" option participates in the search too: show it when the query is
183− // empty or matches its label/description. Without this it either always showed
184− // (ignoring the filter) or, when a query matched no named agent, disappeared with
185− // the whole list — leaving the default unselectable.
186− val defaultLabel = stringResource(R.string.default_agent)
187− val defaultDesc = stringResource(R.string.default_agent_desc)
188− val q = query.trim()
189− val defaultMatches = defaultAgentMatches(q, defaultLabel, defaultDesc)
190− if (filtered.isEmpty() && !defaultMatches) {
191− Text(
192− stringResource(R.string.no_agents_match, query.trim()),
193− style = MaterialTheme.typography.bodyMedium,
194− color = MaterialTheme.colorScheme.onSurfaceVariant,
195− modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp),
196− )
197− } else {
198− val listState = rememberLazyListState()
199− // Flat index of the selected agent, offset by the leading "Default" row when
200− // it's shown. selected == null targets that Default row (index 0). -1 when the
201− // selection isn't in the current list. Computed against `filtered` (not the
202− // unfiltered distinctAgents) so a query that hides agents before the selection
203− // still maps to the right visible row.
204− val selectedIndex = remember(filtered, selected, defaultMatches) {
205− selectedAgentIndex(filtered, selected, defaultMatches)
206− }
207− // Re-scroll to the selected item whenever the filter changes (not just once on
208− // open), so clearing a filter that had hidden the selection brings it back into
209− // view instead of leaving the list at the top.
210− LaunchedEffect(filtered, defaultMatches) {
211− if (selectedIndex >= 0) listState.scrollToItem(selectedIndex)
212− }
213− // Cap the list height against the screen, not the (partial) sheet, so the list
214− // is a predictable height regardless of drag position. weight(1f) would also
215− // work but heightIn keeps the sheet compact for short catalogs.
216− LazyColumn(
217− state = listState,
218− modifier = Modifier
219− .heightIn(max = NetworkConfig.pickerSheetMaxHeightDp.dp)
220− .imePadding()
221− .navigationBarsPadding()
222− .semantics { selectableGroup() },
223− ) {
224− if (defaultMatches) {
225− item(key = "__default") {
226− Column(
227− modifier = Modifier
228− .fillMaxWidth()
229− .semantics(mergeDescendants = true) {
230− this.selected = (selected == null)
231− }
232− .clickable(role = Role.RadioButton) {
233− haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)
234− // Animate the sheet out before tearing down, so the selection
235− // reads as a smooth transition instead of a snap disappearance.
236− scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() }
237− onSelect(null)
238− }
239− .padding(horizontal = 24.dp, vertical = 12.dp),
240− ) {
241− Row(verticalAlignment = Alignment.CenterVertically) {
242− Text(
243− stringResource(R.string.default_agent),
244− style = MaterialTheme.typography.bodyLarge,
245− color = if (selected == null) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
246− modifier = Modifier.weight(1f),
247− )
248− if (selected == null) {
249− Icon(
250− Icons.Filled.Check,
251− contentDescription = null,
252− tint = MaterialTheme.colorScheme.primary,
253− modifier = Modifier.size(20.dp),
254− )
255− }
256− }
257− Text(
258− stringResource(R.string.default_agent_desc),
259− style = MaterialTheme.typography.bodySmall,
260− color = MaterialTheme.colorScheme.onSurfaceVariant,
261− )
262− }
263− }
264− }
265− // distinctBy the name so a server that returns two agents with the same name
266− // (e.g. a built-in colliding with a project-level one) can't crash the list
267− // with LazyColumn's "Key was already used".
268− // Namespace the agent keys so an agent literally named "__default" can't
269− // collide with the sentinel key of the default item above (a duplicate key
270− // crashes LazyColumn).
271− items(filtered, key = { "agent_" + it.name }) { agent ->
272− val isSelected = agent.name == selected
273− Column(
274− modifier = Modifier
275− .fillMaxWidth()
276− .semantics(mergeDescendants = true) {
277− this.selected = isSelected
278− }
279− .clickable(role = Role.RadioButton) {
280− haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)
281− scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() }
282− onSelect(agent)
283− }
284− .padding(horizontal = 24.dp, vertical = 12.dp),
285− ) {
286− Row(verticalAlignment = Alignment.CenterVertically) {
287− Text(
288− agent.name,
289− style = MaterialTheme.typography.bodyLarge,
290− color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
291− modifier = Modifier.weight(1f),
292− )
293− if (isSelected) {
294− Icon(
295− Icons.Filled.Check,
296− contentDescription = null,
297− tint = MaterialTheme.colorScheme.primary,
298− modifier = Modifier.size(20.dp),
299− )
300− }
301− }
302− Text(
303− agent.displayDescription,
304− style = MaterialTheme.typography.bodySmall,
305− color = MaterialTheme.colorScheme.onSurfaceVariant,
306− // Cap at 2 lines (matching the command picker) so a verbose
307− // description doesn't make the row arbitrarily tall and push the
308− // radio affordance out of alignment across the list.
309− maxLines = 2,
310− overflow = TextOverflow.Ellipsis,
311− )
312− }
313− }
314− }
315− }
316− }
317− }
318−}
app/src/main/java/soy/iko/opencode/ui/chat/AttachmentResult.ktdeleted−12
@@ -1,12 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−/** Outcome of turning a picked Uri into a [PendingAttachment] (see `Uri.toAttachmentResult`). */
4−sealed interface AttachmentResult {
5− data class Ok(val attachment: PendingAttachment) : AttachmentResult
6−
7− /** The file exceeded the size cap ([soy.iko.opencode.data.network.NetworkConfig.maxAttachmentBytes]). */
8− data object TooLarge : AttachmentResult
9−
10− /** The file couldn't be read/resolved. */
11− data object Failed : AttachmentResult
12−}
app/src/main/java/soy/iko/opencode/ui/chat/Attachments.ktdeleted−115
@@ -1,115 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import android.content.Context
4−import android.net.Uri
5−import android.provider.OpenableColumns
6−import android.util.Base64
7−import androidx.core.content.FileProvider
8−import soy.iko.opencode.data.model.FilePromptPart
9−import soy.iko.opencode.data.network.NetworkConfig
10−import soy.iko.opencode.util.runCatchingCancellable
11−import kotlinx.coroutines.Dispatchers
12−import kotlinx.coroutines.withContext
13−import java.io.File
14−
15−/**
16− * Read [uri]'s bytes off the main thread, base64-encode them into a `data:` URL, and wrap
17− * the result as a [PendingAttachment] ready to send. Enforces the size cap. The original
18− * [uri] is kept as the thumbnail model for images (Coil loads content Uris directly).
19− */
20−suspend fun Uri.toAttachmentResult(context: Context): AttachmentResult = withContext(Dispatchers.IO) {
21− val resolver = context.contentResolver
22− val mime = resolver.getType(this@toAttachmentResult) ?: "application/octet-stream"
23− val name = displayName(context) ?: defaultName(mime)
24− val max = NetworkConfig.maxAttachmentBytes
25− // Cheap pre-check: if the provider reports a size, reject an oversize file before reading
26− // a single byte into memory. The picker can hand back arbitrarily large files (e.g. a
27− // multi-hundred-MB video), so reading first and checking after would OOM the app.
28− val declaredSize = fileSize(context)
29− if (declaredSize != null && declaredSize > max) return@withContext AttachmentResult.TooLarge
30− // Read with a hard cap so a provider that under-reports or omits its size still can't OOM
31− // us: stop as soon as we've read one byte past the cap, then reject.
32− val bytes = runCatchingCancellable {
33− resolver.openInputStream(this@toAttachmentResult)?.use { it.readAtMost(max + 1) }
34− }.getOrNull() ?: return@withContext AttachmentResult.Failed
35− if (bytes.size > max) return@withContext AttachmentResult.TooLarge
36− val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
37− val dataUrl = "data:$mime;base64,$b64"
38− AttachmentResult.Ok(
39− PendingAttachment(
40− id = java.util.UUID.randomUUID().toString(),
41− name = name,
42− mime = mime,
43− previewModel = if (mime.startsWith("image/")) this@toAttachmentResult.toString() else null,
44− part = FilePromptPart(mime = mime, url = dataUrl, filename = name),
45− ),
46− )
47−}
48−
49−/** The provider-reported byte size of the content [uri], or null if it isn't exposed. */
50−private fun Uri.fileSize(context: Context): Long? = runCatching {
51− context.contentResolver.query(this, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { cursor ->
52− val idx = cursor.getColumnIndex(OpenableColumns.SIZE)
53− if (idx >= 0 && cursor.moveToFirst() && !cursor.isNull(idx)) cursor.getLong(idx) else null
54− }
55−}.getOrNull()
56−
57−/** Read up to [limit] bytes from the stream without materializing the whole file, so an
58− * oversize source can be rejected on a bounded amount of memory. Reaching [limit] bytes is
59− * the caller's signal that the source exceeds the cap. */
60−private fun java.io.InputStream.readAtMost(limit: Long): ByteArray {
61− val out = java.io.ByteArrayOutputStream()
62− val chunk = ByteArray(8 * 1024)
63− var total = 0L
64− while (total < limit) {
65− val want = minOf(chunk.size.toLong(), limit - total).toInt()
66− val read = read(chunk, 0, want)
67− if (read < 0) break
68− out.write(chunk, 0, read)
69− total += read
70− }
71− return out.toByteArray()
72−}
73−
74−/** The raw (pre-base64) byte size encoded in a `data:<mime>;base64,<payload>` URL, derived from
75− * the payload length (len / 4 * 3, less any '=' padding) without allocating or decoding the
76− * payload — important since the payload can be many MB. Returns 0 when the URL has no base64
77− * payload. Lets the cumulative attachment-size cap use the same raw-byte measure as the per-file
78− * [NetworkConfig.maxAttachmentBytes] check above (which counts raw `bytes.size`). */
79−internal fun base64DataUrlByteSize(dataUrl: String): Long {
80− val marker = "base64,"
81− val start = dataUrl.indexOf(marker)
82− if (start < 0) return 0L
83− val payloadLen = dataUrl.length - (start + marker.length)
84− if (payloadLen <= 0) return 0L
85− val padding = when {
86− dataUrl.endsWith("==") -> 2
87− dataUrl.endsWith("=") -> 1
88− else -> 0
89− }
90− return payloadLen.toLong() / 4 * 3 - padding
91−}
92−
93−/** Resolve a human-readable display name for the content [uri], if the provider exposes one. */
94−private fun Uri.displayName(context: Context): String? = runCatching {
95− context.contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
96− val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
97− if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
98− }
99−}.getOrNull()?.takeIf { it.isNotBlank() }
100−
101−private fun defaultName(mime: String): String {
102− val ext = mime.substringAfterLast('/', "bin").takeIf { it.isNotBlank() } ?: "bin"
103− return "attachment.$ext"
104−}
105−
106−/**
107− * Create a temp file in the cache and a shareable content [Uri] for it (via the app's
108− * [FileProvider]) to hand to the camera as the capture target. Returns null if it can't be
109− * created. The file is overwritten on each capture; the OS cleans the cache dir.
110− */
111−fun newCameraCaptureUri(context: Context): Uri? = runCatching {
112− val dir = File(context.cacheDir, "captures").apply { mkdirs() }
113− val file = File(dir, "capture_${System.currentTimeMillis()}.jpg")
114− FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
115−}.getOrNull()
app/src/main/java/soy/iko/opencode/ui/chat/ChatAttachments.ktdeleted−258
@@ -1,258 +0,0 @@
1−package soy.iko.opencode.ui.chat
2−
3−import androidx.compose.foundation.layout.Arrangement
4−import androidx.compose.foundation.layout.Box
5−import androidx.compose.foundation.layout.Column
6−import androidx.compose.foundation.layout.Row
7−import androidx.compose.foundation.layout.fillMaxSize
8−import androidx.compose.foundation.layout.fillMaxWidth
9−import androidx.compose.foundation.layout.padding
10−import androidx.compose.foundation.layout.size
11−import androidx.compose.foundation.layout.widthIn
12−import androidx.compose.foundation.clickable
13−import androidx.compose.foundation.combinedClickable
14−import androidx.compose.foundation.horizontalScroll
15−import androidx.compose.foundation.rememberScrollState
16−import androidx.compose.material.icons.Icons
17−import androidx.compose.material.icons.filled.Close
18−import androidx.compose.material.icons.filled.Description
19−import androidx.compose.material3.AlertDialog
20−import androidx.compose.material3.CircularProgressIndicator
21−import androidx.compose.material3.Icon
22−import androidx.compose.material3.IconButton
23−import androidx.compose.material3.MaterialTheme
24−import androidx.compose.material3.Surface
25−import androidx.compose.material3.Text
26−import androidx.compose.runtime.Composable
27−import androidx.compose.runtime.getValue
28−import androidx.compose.runtime.mutableStateOf
29−import androidx.compose.runtime.remember
30−import androidx.compose.runtime.setValue
31−import androidx.compose.ui.Alignment
32−import androidx.compose.ui.Modifier
33−import androidx.compose.ui.draw.clip
34−import androidx.compose.ui.layout.ContentScale
35−import androidx.compose.ui.res.stringResource
36−import androidx.compose.ui.semantics.Role
37−import androidx.compose.ui.semantics.contentDescription
38−import androidx.compose.ui.semantics.semantics
39−import androidx.compose.ui.text.style.TextOverflow
40−import androidx.compose.ui.unit.dp
41−import androidx.compose.ui.window.Dialog
42−import androidx.compose.ui.window.DialogProperties
43−import coil3.compose.AsyncImage
44−import soy.iko.opencode.R
45−import soy.iko.opencode.data.network.NetworkConfig
46−import java.util.Locale
47−
48−/**
49− * The staged-attachment UI for the chat composer — extracted from ChatScreen so that (large)
50− * file stays focused on the conversation surface. `internal` so ChatScreen can call it.
51− *
52− * When at least one attachment is staged, a muted total-size label is rendered at the end of
53− * the strip so the user can see how close they are to the cumulative [NetworkConfig.maxTotalAttachmentBytes]
54− * cap — a bare per-file cap doesn't surface the combined total, and a failed send is the only
55− * other feedback.
56− */
57−@Composable
58−internal fun AttachmentStrip(
59− attachments: List<PendingAttachment>,
60− onRemove: (String) -> Unit,
61− staging: Boolean = false,
62− stagingFileCount: Int = 0,
63−) {
64− // Show the strip while an encode is in flight even before the first chip exists, so the
65− // user gets immediate feedback that their pick is being processed.
66− if (attachments.isEmpty() && !staging) return
67− // Horizontally-scrollable strip of staged attachment thumbnails/chips, each removable.
68− Row(
69− modifier = Modifier
70− .fillMaxWidth()
71− .horizontalScroll(rememberScrollState())
72− .padding(start = 8.dp, end = 8.dp, top = 8.dp),
73− horizontalArrangement = Arrangement.spacedBy(8.dp),
74− verticalAlignment = Alignment.CenterVertically,
75− ) {
76− attachments.forEach { att ->
77− AttachmentChip(att, onRemove = { onRemove(att.id) })
78− }
79− // A placeholder chip with an indeterminate spinner while any pick is still being
80− // read + base64-encoded off the main thread (chips only materialize once done).
81− if (staging) StagingChip(stagingFileCount)
82− // Total staged size label — surfaced so the user can see how close they are to the
83− // cumulative cap before a send fails. Hidden while staging (the total is in flux).
84− if (!staging && attachments.isNotEmpty()) {
85− val totalBytes = remember(attachments) {
86− attachments.sumOf { base64DataUrlByteSize(it.part.url) }
87− }
88− val maxBytes = NetworkConfig.maxTotalAttachmentBytes
89− val label = remember(totalBytes, maxBytes) { formatAttachmentTotal(totalBytes, maxBytes) }
90− val over = totalBytes > maxBytes
91− Text(
92− label,
93− style = MaterialTheme.typography.labelSmall,
94− color = if (over) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
95− modifier = Modifier.padding(start = 4.dp, end = 4.dp),
96− )
97− }
98− }
99−}
100−
101−/** Format the staged-attachment total as "N.N MB / max" (or KB when small), for the strip label. */
102−private fun formatAttachmentTotal(bytes: Long, max: Long): String {
103− val mb = 1024.0 * 1024.0
104− val kb = 1024.0
105− val used = when {
106− bytes >= mb -> String.format(Locale.US, "%.1f MB", bytes / mb)
107− bytes >= kb -> String.format(Locale.US, "%.0f KB", bytes / kb)
108− else -> "$bytes B"
109− }
110− val maxStr = when {
111− max >= mb -> String.format(Locale.US, "%.0f MB", max / mb)
112− max >= kb -> String.format(Locale.US, "%.0f KB", max / kb)
113− else -> "$max B"
114− }
115− return "$used / $maxStr"
116−}
117−
118−/** A placeholder chip shown while an attachment is being encoded. */
119−@Composable
120−private fun StagingChip(stagingFileCount: Int) {
121− // Show "Staging N files…" when a multi-file count is known; fall back to the generic
122− // "Attaching…" for the single/unknown case so the label never reads "Staging 1 files".
123− val label = if (stagingFileCount > 1) {
124− stringResource(R.string.staging_n_files, stagingFileCount)
125− } else {
126− stringResource(R.string.attachment_staging)
127− }
128− Surface(
129− shape = MaterialTheme.shapes.small,
130− color = MaterialTheme.colorScheme.surfaceVariant,
131− tonalElevation = 1.dp,
132− ) {
133− Row(
134− verticalAlignment = Alignment.CenterVertically,
135− modifier = Modifier.padding(horizontal = 10.dp),
136− ) {
137− CircularProgressIndicator(
138− Modifier.size(18.dp).semantics { contentDescription = label },
139− strokeWidth = 2.dp,
140− )
141− Text(
142− label,
143− style = MaterialTheme.typography.labelMedium,
144− maxLines = 1,
145− modifier = Modifier.padding(start = 8.dp, top = 10.dp, bottom = 10.dp),
146− )
147− }
148− }
149−}
150−
151−/** A single staged attachment: an image thumbnail (or a generic file icon) with its name
152− * and a remove button. Tapping the thumbnail/name of an image attachment opens a fullscreen
153− * preview so the user can verify it before sending (a sent image costs tokens and can't be
154− * unsent). */
155−@Composable
156−private fun AttachmentChip(attachment: PendingAttachment, onRemove: () -> Unit) {
157− var showPreview by remember { mutableStateOf(false) }
158− var showNameDialog by remember { mutableStateOf(false) }
159− val previewLabel = stringResource(R.string.preview_attachment)
160− val haptics = androidx.compose.ui.platform.LocalHapticFeedback.current
161− Surface(
162− shape = MaterialTheme.shapes.small,
163− color = MaterialTheme.colorScheme.surfaceVariant,
164− tonalElevation = 1.dp,
165− ) {
166− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 6.dp)) {
167− if (attachment.previewModel != null) {
168− AsyncImage(
169− model = attachment.previewModel,
170− contentDescription = attachment.name,
171− contentScale = ContentScale.Crop,
172− modifier = Modifier
173− .size(36.dp)
174− .clip(MaterialTheme.shapes.extraSmall)
175− .semantics { contentDescription = previewLabel }
176− .clickable(role = Role.Image) { showPreview = true },
177− )
178− } else {
179− // Long-press the file icon to see the full filename (it's truncated to 120dp
180− // in the chip, so a long name can't be read in full otherwise). Mirrors the
181− // image chip's tap-to-preview pattern for non-image files.
182− Icon(
183− Icons.Filled.Description,
184− contentDescription = null,
185− modifier = Modifier
186− .size(24.dp)
187− .combinedClickable(
188− role = Role.Image,
189− onLongClick = {
190− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
191− showNameDialog = true
192− },
193− onClick = {},
194− ),
195− tint = MaterialTheme.colorScheme.onSurfaceVariant,
196− )
197− }
198− Text(
199− attachment.name,
200− style = MaterialTheme.typography.labelMedium,
201− maxLines = 1,
202− overflow = TextOverflow.Ellipsis,
203− modifier = Modifier.widthIn(max = 120.dp).padding(horizontal = 6.dp),
204− )
205− // No .size() override so the IconButton keeps its default 48dp touch target
206− // (a11y minimum) while the visual X stays small (16dp).
207− IconButton(onClick = onRemove) {
208− Icon(
209− Icons.Filled.Close,
210− contentDescription = stringResource(R.string.remove),
211− modifier = Modifier.size(16.dp),
212− )
213− }
214− }
215− }
216− if (showPreview && attachment.previewModel != null) {
217− Dialog(
218− onDismissRequest = { showPreview = false },
219− properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
220− ) {
221− Box(
222− modifier = Modifier.fillMaxSize().padding(16.dp),
223− contentAlignment = Alignment.Center,
224− ) {
225− AsyncImage(
226− model = attachment.previewModel,
227− contentDescription = attachment.name,
228− contentScale = ContentScale.Fit,
229− modifier = Modifier.fillMaxWidth().clickable(role = Role.Image) { showPreview = false },
230− )
231− IconButton(
232− onClick = { showPreview = false },
233− modifier = Modifier.align(Alignment.TopEnd),
234− ) {
235− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close))
236− }
237− }
238− }
239− }
240− if (showNameDialog) {
241− AlertDialog(
242− onDismissRequest = { showNameDialog = false },
243− title = { Text(stringResource(R.string.attachment_name)) },
244− text = {
245− Text(
246− attachment.name,
247− style = MaterialTheme.typography.bodyMedium,
248− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
249− )
250− },
251− confirmButton = {
252− androidx.compose.material3.TextButton(onClick = { showNameDialog = false }) {
253− Text(stringResource(R.string.close))
254− }
255− },
256− )
257− }
258−}
app/src/main/java/soy/iko/opencode/ui/chat/ChatScreen.ktdeleted−3292
@@ -1,3292 +0,0 @@
1−@file:Suppress("TooManyFunctions")
2−
3−package soy.iko.opencode.ui.chat
4−
5−import android.app.Activity
6−import android.content.Intent
7−import android.net.Uri
8−import android.speech.RecognizerIntent
9−import androidx.activity.compose.BackHandler
10−import androidx.activity.compose.rememberLauncherForActivityResult
11−import androidx.activity.result.PickVisualMediaRequest
12−import androidx.activity.result.contract.ActivityResultContracts
13−import androidx.compose.animation.AnimatedVisibility
14−import androidx.compose.animation.core.RepeatMode
15−import androidx.compose.animation.core.animateFloat
16−import androidx.compose.animation.core.infiniteRepeatable
17−import androidx.compose.animation.core.rememberInfiniteTransition
18−import androidx.compose.animation.core.tween
19−import androidx.compose.foundation.background
20−import androidx.compose.foundation.clickable
21−import androidx.compose.foundation.content.contentReceiver
22−import androidx.compose.foundation.layout.Arrangement
23−import androidx.compose.foundation.layout.Box
24−import androidx.compose.foundation.layout.Column
25−import androidx.compose.foundation.layout.FlowRow
26−import androidx.compose.foundation.layout.PaddingValues
27−import androidx.compose.foundation.layout.Row
28−import androidx.compose.foundation.layout.Spacer
29−import androidx.compose.foundation.layout.WindowInsets
30−import androidx.compose.foundation.layout.fillMaxSize
31−import androidx.compose.foundation.layout.fillMaxWidth
32−import androidx.compose.foundation.layout.heightIn
33−import androidx.compose.foundation.layout.height
34−import androidx.compose.foundation.layout.imePadding
35−import androidx.compose.foundation.layout.ime
36−import androidx.compose.foundation.layout.navigationBars
37−import androidx.compose.foundation.layout.padding
38−import androidx.compose.foundation.layout.size
39−import androidx.compose.foundation.layout.union
40−import androidx.compose.foundation.layout.widthIn
41−import androidx.compose.foundation.layout.windowInsetsPadding
42−import androidx.compose.foundation.layout.wrapContentWidth
43−import androidx.compose.foundation.lazy.LazyColumn
44−import androidx.compose.foundation.lazy.items
45−import androidx.compose.foundation.lazy.rememberLazyListState
46−import androidx.compose.foundation.shape.RoundedCornerShape
47−import androidx.compose.material.icons.Icons
48−import androidx.compose.material.icons.automirrored.filled.ArrowBack
49−import androidx.compose.material.icons.automirrored.filled.Send
50−import androidx.compose.material.icons.filled.ErrorOutline
51−import androidx.compose.material.icons.filled.Add
52−import androidx.compose.material.icons.filled.AutoAwesome
53−import androidx.compose.material.icons.filled.Delete
54−import androidx.compose.material.icons.filled.Description
55−import androidx.compose.material.icons.filled.Close
56−import androidx.compose.material.icons.filled.Edit
57−import androidx.compose.material.icons.filled.Expand
58−import androidx.compose.material.icons.filled.FormatQuote
59−import androidx.compose.material.icons.filled.ExpandLess
60−import androidx.compose.material.icons.filled.ExpandMore
61−import androidx.compose.material.icons.filled.Search
62−import androidx.compose.material.icons.filled.KeyboardArrowDown
63−import androidx.compose.material.icons.filled.KeyboardArrowUp
64−import androidx.compose.material.icons.filled.Mic
65−import androidx.compose.material.icons.filled.MoreVert
66−import androidx.compose.material.icons.filled.PhotoCamera
67−import androidx.compose.material.icons.filled.PhotoLibrary
68−import androidx.compose.material.icons.filled.Refresh
69−import androidx.compose.material.icons.filled.Restore
70−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
71−import androidx.compose.material.icons.automirrored.filled.Reply
72−import androidx.compose.material.icons.filled.Schedule
73−import androidx.compose.material.icons.filled.Stop
74−import androidx.compose.material3.AlertDialog
75−import androidx.compose.material3.Badge
76−import androidx.compose.material3.BadgedBox
77−import androidx.compose.material3.Button
78−import androidx.compose.material3.CircularProgressIndicator
79−import androidx.compose.material3.SmallFloatingActionButton
80−import androidx.compose.material3.DropdownMenu
81−import androidx.compose.material3.DropdownMenuItem
82−import androidx.compose.material3.ExperimentalMaterial3Api
83−import androidx.compose.material3.ExtendedFloatingActionButton
84−import androidx.compose.material3.FloatingActionButton
85−import androidx.compose.material3.Icon
86−import androidx.compose.material3.IconButton
87−import androidx.compose.material3.MaterialTheme
88−import androidx.compose.material3.OutlinedTextField
89−import androidx.compose.material3.Scaffold
90−import androidx.compose.material3.SnackbarDuration
91−import androidx.compose.material3.SwipeToDismissBox
92−import androidx.compose.material3.SwipeToDismissBoxValue
93−import androidx.compose.material3.rememberSwipeToDismissBoxState
94−import androidx.compose.material3.SnackbarHost
95−import androidx.compose.material3.SnackbarHostState
96−import androidx.compose.material3.SnackbarResult
97−import androidx.compose.material3.Surface
98−import androidx.compose.material3.Text
99−import androidx.compose.material3.TextButton
100−import androidx.compose.material3.TopAppBar
101−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
102−import androidx.compose.runtime.Composable
103−import androidx.compose.runtime.CompositionLocalProvider
104−import androidx.compose.runtime.DisposableEffect
105−import androidx.compose.runtime.LaunchedEffect
106−import androidx.compose.runtime.derivedStateOf
107−import androidx.compose.runtime.getValue
108−import androidx.compose.runtime.mutableIntStateOf
109−import androidx.compose.runtime.mutableLongStateOf
110−import androidx.compose.runtime.mutableStateOf
111−import androidx.compose.runtime.produceState
112−import androidx.compose.runtime.remember
113−import androidx.compose.runtime.rememberCoroutineScope
114−import androidx.compose.runtime.rememberUpdatedState
115−import androidx.compose.runtime.saveable.rememberSaveable
116−import androidx.compose.runtime.setValue
117−import androidx.compose.runtime.snapshotFlow
118−import androidx.compose.foundation.text.KeyboardActions
119−import androidx.compose.foundation.text.KeyboardOptions
120−import androidx.compose.ui.text.input.KeyboardCapitalization
121−import androidx.compose.ui.Alignment
122−import androidx.compose.ui.Modifier
123−import androidx.compose.ui.draw.alpha
124−import androidx.compose.ui.draw.clip
125−import androidx.compose.ui.focus.focusRequester
126−import androidx.compose.ui.input.key.Key
127−import androidx.compose.ui.input.key.KeyEventType
128−import androidx.compose.ui.input.key.isCtrlPressed
129−import androidx.compose.ui.input.key.isShiftPressed
130−import androidx.compose.ui.input.key.key
131−import androidx.compose.ui.input.key.onPreviewKeyEvent
132−import androidx.compose.ui.input.key.type
133−import androidx.compose.ui.layout.onSizeChanged
134−import androidx.compose.ui.platform.LocalContext
135−import androidx.compose.ui.platform.LocalDensity
136−import androidx.compose.ui.platform.LocalHapticFeedback
137−import androidx.compose.ui.platform.LocalLayoutDirection
138−import androidx.compose.ui.platform.LocalView
139−import androidx.compose.ui.platform.testTag
140−import androidx.compose.ui.unit.LayoutDirection
141−import androidx.compose.ui.res.pluralStringResource
142−import androidx.compose.ui.res.stringResource
143−import androidx.compose.ui.semantics.Role
144−import androidx.compose.ui.semantics.contentDescription
145−import androidx.compose.ui.semantics.heading
146−import androidx.compose.ui.semantics.liveRegion
147−import androidx.compose.ui.semantics.LiveRegionMode
148−import androidx.compose.ui.semantics.invisibleToUser
149−import androidx.compose.ui.semantics.semantics
150−import androidx.compose.ui.text.input.ImeAction
151−import androidx.compose.ui.text.style.TextOverflow
152−import androidx.compose.ui.unit.dp
153−import androidx.lifecycle.compose.collectAsStateWithLifecycle
154−import androidx.lifecycle.viewmodel.compose.viewModel
155−import kotlinx.coroutines.Dispatchers
156−import kotlinx.coroutines.coroutineScope
157−import kotlinx.coroutines.delay
158−import kotlinx.coroutines.flow.distinctUntilChanged
159−import kotlinx.coroutines.launch
160−import kotlinx.coroutines.withContext
161−import soy.iko.opencode.data.model.Part
162−import soy.iko.opencode.data.model.MessageWithParts
163−import soy.iko.opencode.data.model.AssistantMessage
164−import soy.iko.opencode.data.model.Command
165−import soy.iko.opencode.data.model.ReasoningPart
166−import soy.iko.opencode.data.model.TextPart
167−import soy.iko.opencode.data.model.ToolCompleted
168−import soy.iko.opencode.data.model.ToolError
169−import soy.iko.opencode.data.model.ToolPart
170−import soy.iko.opencode.data.model.ToolRunning
171−import soy.iko.opencode.data.model.FilePart
172−import soy.iko.opencode.data.model.sourcePath
173−import soy.iko.opencode.data.model.inputElement
174−import soy.iko.opencode.data.network.EventStreamClient
175−import soy.iko.opencode.data.network.NetworkConfig
176−import soy.iko.opencode.di.AppContainer
177−import soy.iko.opencode.R
178−import soy.iko.opencode.ui.components.CommandPalette
179−import soy.iko.opencode.ui.components.ConnectionBanner
180−import soy.iko.opencode.ui.components.DiffView
181−import soy.iko.opencode.ui.components.PaletteAction
182−import soy.iko.opencode.ui.components.LocalReducedMotion
183−import soy.iko.opencode.ui.components.LocalSearchHighlight
184−import soy.iko.opencode.ui.components.reducedMotionAnimateItem
185−import soy.iko.opencode.ui.components.copyToClipboard
186−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
187−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
188−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
189−import soy.iko.opencode.ui.components.showToast
190−import soy.iko.opencode.ui.components.toImageContext
191−import soy.iko.opencode.ui.vmFactory
192−import soy.iko.opencode.util.runCatchingCancellable
193−
194−// Optional message id to scroll to and briefly highlight on first load (from global search).
195−// Consumed once: after the message is scrolled into view and highlighted, the focus is
196−// cleared so subsequent recompositions don't re-trigger the scroll.
197−@OptIn(ExperimentalMaterial3Api::class)
198−@Composable
199−fun ChatScreen(
200− container: AppContainer,
201− sessionId: String,
202− onBack: () -> Unit,
203− onOpenFile: ((String) -> Unit)? = null,
204− onOpenSession: ((String) -> Unit)? = null,
205− focusMessageId: String? = null,
206− onEditProfile: ((String) -> Unit)? = null,
207−) {
208− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
209− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
210− val running by vm.running.collectAsStateWithLifecycle()
211− val streamInterrupted by vm.streamInterrupted.collectAsStateWithLifecycle()
212− val aborting by vm.aborting.collectAsStateWithLifecycle()
213− val loading by vm.loading.collectAsStateWithLifecycle()
214− val loadError by vm.loadError.collectAsStateWithLifecycle()
215− val loadErrorInline by vm.loadErrorInline.collectAsStateWithLifecycle()
216− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
217− val models by vm.models.collectAsStateWithLifecycle()
218− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
219− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
220− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
221− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
222− val reconnectAttempts by vm.reconnectAttempts.collectAsStateWithLifecycle()
223− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
224− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
225− val agents by vm.agents.collectAsStateWithLifecycle()
226− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
227− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
228− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
229− val commands by vm.commands.collectAsStateWithLifecycle()
230− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
231− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
232− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
233− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
234− val draft by vm.draft.collectAsStateWithLifecycle()
235− val pendingQuote by vm.pendingQuote.collectAsStateWithLifecycle()
236− val attachments by vm.attachments.collectAsStateWithLifecycle()
237− val reverted by vm.reverted.collectAsStateWithLifecycle()
238− val editing by vm.editing.collectAsStateWithLifecycle()
239− val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
240− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
241− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
242− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
243− val preferredModelId by container.settingsStore.preferredModelId.collectAsStateWithLifecycle(initialValue = "")
244− val recentModelEntries by container.recentModelsStore.entries.collectAsStateWithLifecycle()
245− val compactSpacing by container.settingsStore.compactMessageSpacing.collectAsStateWithLifecycle(initialValue = false)
246− val notifPermission by container.settingsStore.notifPermission.collectAsStateWithLifecycle(initialValue = true)
247− val isOnline by container.isOnline.collectAsStateWithLifecycle()
248− val haptics = LocalHapticFeedback.current
249− val layoutDirection = LocalLayoutDirection.current
250− val scope = rememberCoroutineScope()
251− val shareContext = LocalContext.current
252− val defaultShareSubject = stringResource(R.string.share_subject)
253− val sessionLabel = stringResource(R.string.session)
254− val defaultModelLabel = stringResource(R.string.default_model)
255− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
256− buildString {
257− append(selectedModel?.modelLabel ?: defaultModelLabel)
258− selectedAgent?.let { append(" · $it") }
259− }
260− }
261−
262− // Connection profile (with auth) for rendering inline image attachments.
263− // Collect as state so a server switch recomposes the image context.
264− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
265− val imageContext = remember(activeConnection?.profile) {
266− activeConnection?.profile?.toImageContext()
267− }
268−
269− // Mark this session as read while the user is viewing it; clear on leave so new
270− // background activity can badge it again.
271− DisposableEffect(sessionId) {
272− container.setCurrentSession(sessionId)
273− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
274− }
275−
276− // Navigate away when the session is deleted via SSE so the user isn't left
277− // on a zombie screen showing a conversation that no longer exists. Surface a
278− // toast (not a snackbar) because the screen is about to be popped — a snackbar
279− // would be torn down before the user could read it, while a toast survives.
280− // Covers both SSE-driven deletion (deleted on another device) and a user-
281− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
282− // sets the same flag on success).
283− val deletedContext = LocalContext.current
284− LaunchedEffect(sessionDeleted) {
285− if (sessionDeleted) {
286− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
287− onBack()
288− }
289− }
290−
291− val snackbar = remember { SnackbarHostState() }
292− val retryLabel = stringResource(R.string.retry)
293− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
294− // Dedicated focus requester for the in-conversation search field. The overflow menu's
295− // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
296− // (the composer), so typing went to the composer instead of the search field.
297− val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
298− var showModelPicker by rememberSaveable { mutableStateOf(false) }
299− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
300− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
301− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
302− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
303− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
304− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
305− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
306− var showShellDialog by rememberSaveable { mutableStateOf(false) }
307− var showPalette by rememberSaveable { mutableStateOf(false) }
308− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
309− var searchActive by rememberSaveable { mutableStateOf(false) }
310− var chatSearch by rememberSaveable { mutableStateOf("") }
311− // Index of the currently-focused in-conversation search match (into the filtered list).
312− // Drives the up/down navigation: the search bar's arrows step through matches and scroll
313− // the list to each one, mirroring desktop chat apps (the bare filtered list previously
314− // required reading each message to find the term).
315− var searchPos by rememberSaveable { mutableIntStateOf(0) }
316− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
317− // a confirmation dialog (from both the overflow menu and the command palette).
318− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
319− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
320−
321− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
322− // action list doesn't need a Composable context. Actions map to the same handlers the
323− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
324− val paletteModelLabel = stringResource(R.string.palette_switch_model)
325− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
326− val paletteCommandLabel = stringResource(R.string.palette_run_command)
327− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
328− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
329− val paletteShellLabel = stringResource(R.string.run_shell_command)
330− val paletteActions = remember(
331− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
332− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
333− ) {
334− buildList {
335− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
336− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
337− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
338− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
339− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
340− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
341− }
342− }
343−
344− // Keep the screen awake while the agent is working in *this* session. The foreground
345− // service that holds process priority during a run is managed app-wide off
346− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
347− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
348− // SSE stream before the completion notification fires.
349− val currentView = LocalView.current
350− val appContext = LocalContext.current.applicationContext
351− DisposableEffect(running) {
352− currentView.keepScreenOn = running
353− onDispose { currentView.keepScreenOn = false }
354− }
355−
356− LaunchedEffect(Unit) {
357− vm.errorEvents.collect { event ->
358− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
359− // message-load failure) would silently re-submit the last prompt on tap.
360− val result = if (event.retryable) {
361− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
362− } else {
363− snackbar.showSnackbar(event.message)
364− }
365− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
366− }
367− }
368−
369− // Stop-undo: abort() emits the last-sent prompt here so this collector can show a
370− // "Stopped — Undo" snackbar. Tapping Undo re-sends the prompt, recovering an accidental
371− // Stop without a confirmation dialog (Stop now happens on first tap).
372− val undoStopLabel = stringResource(R.string.undo)
373− val stoppedLabel = stringResource(R.string.run_stopped_undo)
374− LaunchedEffect(Unit) {
375− vm.stopUndoEvents.collect { prompt ->
376− if (prompt != null) {
377− val result = snackbar.showSnackbar(message = stoppedLabel, actionLabel = undoStopLabel)
378− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.resendLastPrompt()
379− }
380− }
381− }
382−
383− // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
384− // window on the container; show the snackbar over the conversation the user is viewing so
385− // they can cancel without being navigated to the session list first. If the window expires
386− // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
387− val undoLabel = stringResource(R.string.undo)
388− val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
389− LaunchedEffect(Unit) {
390− vm.deleteUndoEvents.collect {
391− coroutineScope {
392− val dismisser = launch {
393− delay(NetworkConfig.undoDeleteDelayMs)
394− snackbar.currentSnackbarData?.dismiss()
395− }
396− val result = snackbar.showSnackbar(
397− message = sessionDeletedLabel,
398− actionLabel = undoLabel,
399− duration = SnackbarDuration.Indefinite,
400− )
401− dismisser.cancel()
402− if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
403− }
404− }
405− }
406−
407− // --- Attachments, voice, and share-link plumbing ---
408− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
409− val attachFailedMsg = stringResource(R.string.attachment_failed)
410− val attachLimitMsg = stringResource(R.string.attachment_limit)
411− val noCameraMsg = stringResource(R.string.no_camera_app)
412− val noVoiceMsg = stringResource(R.string.no_voice_app)
413− val voicePrompt = stringResource(R.string.voice_prompt)
414− val linkCopiedMsg = stringResource(R.string.link_copied)
415− val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
416−
417− // Count of picks currently being read + base64-encoded off the main thread, so the
418− // composer can show a staging placeholder immediately (chips only materialize once done).
419− var stagingCount by remember { mutableStateOf(0) }
420− // Total number of files still being staged across all in-flight batches, so the
421− // staging chip can show "Staging N files…" rather than a bare indeterminate spinner.
422− // A separate counter from [stagingCount] (which tracks batches, not files) so a
423− // multi-file pick reads as more work than a single-file pick.
424− var stagingFileTotal by remember { mutableStateOf(0) }
425−
426− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
427− // per-prompt count cap and surfacing per-file errors without aborting the batch.
428− fun stageUris(uris: List<Uri>) {
429− if (uris.isEmpty()) return
430− scope.launch {
431− stagingCount++
432− stagingFileTotal += uris.size
433− try {
434− uris.forEachIndexed { index, uri ->
435− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
436− snackbar.showSnackbar(attachLimitMsg)
437− // The cap dropped the rest of this batch; account for the files we
438− // won't process so stagingFileTotal doesn't linger over-counted,
439− // then abandon the batch. return@launch (not return@forEachIndexed)
440− // so the remaining uris aren't re-checked against a never-relieved
441− // cap (which would over-decrement the counter and re-fire the snackbar
442− // once per leftover uri). The `finally` below still decrements
443− // stagingCount.
444− stagingFileTotal -= uris.size - index
445− return@launch
446− }
447− when (val result = uri.toAttachmentResult(appContext)) {
448− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
449− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
450− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
451− }
452− stagingFileTotal--
453− }
454− } finally {
455− stagingCount--
456− }
457− }
458− }
459−
460− val photoPicker = rememberLauncherForActivityResult(
461− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
462− ) { uris -> stageUris(uris) }
463−
464− val filePicker = rememberLauncherForActivityResult(
465− ActivityResultContracts.GetMultipleContents(),
466− ) { uris -> stageUris(uris) }
467−
468− // Uri survives a config change mid-capture so the TakePicture result still resolves.
469− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
470− val cameraLauncher = rememberLauncherForActivityResult(
471− ActivityResultContracts.TakePicture(),
472− ) { success ->
473− val uri = pendingCaptureUri
474− pendingCaptureUri = null
475− if (success && uri != null) stageUris(listOf(uri))
476− }
477−
478− val voiceLauncher = rememberLauncherForActivityResult(
479− ActivityResultContracts.StartActivityForResult(),
480− ) { result ->
481− if (result.resultCode == Activity.RESULT_OK) {
482− val spoken = result.data
483− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
484− ?.firstOrNull()
485− ?.takeIf { it.isNotBlank() }
486− if (spoken != null) {
487− // Append to the existing draft rather than replacing, so dictation adds to
488− // whatever the user already typed.
489− val current = vm.draft.value
490− val combined = if (current.isBlank()) spoken else "$current $spoken"
491− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
492− }
493− }
494− }
495−
496− fun launchCamera() {
497− val uri = newCameraCaptureUri(appContext)
498− if (uri == null) {
499− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
500− return
501− }
502− pendingCaptureUri = uri
503− runCatching { cameraLauncher.launch(uri) }
504− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
505− }
506−
507− fun launchVoice() {
508− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
509− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
510− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
511− }
512− runCatching { voiceLauncher.launch(intent) }
513− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
514− }
515−
516− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
517− LaunchedEffect(Unit) {
518− vm.shareLinkEvents.collect { url ->
519− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
520− snackbar.showSnackbar(linkCopiedMsg)
521− }
522− }
523−
524− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
525− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
526− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
527− // a dropped branch-navigation event in the gap.
528− val branchedMsg = stringResource(R.string.branch_created)
529− LaunchedEffect(Unit) {
530− vm.branchEvents.collect { newId ->
531− showToast(shareContext, branchedMsg)
532− onOpenSession?.invoke(newId)
533− }
534− }
535−
536− // Stage images shared into the app (via the system share sheet) as attachments.
537− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
538− // while this ChatScreen is already composed — which happens in two-pane mode, where the
539− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
540− // only fire on first composition. consumePendingSharedMedia() atomically drains the
541− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
542− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
543− LaunchedEffect(pendingSharedMedia) {
544− val shared = container.consumePendingSharedMedia()
545− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
546− }
547−
548− fun doSend() {
549− if (vm.send(draft)) {
550− // TextHandleMove (a light tick) is semantically right for a send commit;
551− // LongPress is reserved for long-press/swipe gestures.
552− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
553− }
554− }
555−
556− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
557−
558− Scaffold(
559− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
560− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
561− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
562− // typing (and the composer's own Enter-to-send handling) is untouched.
563− modifier = Modifier.onPreviewKeyEvent { ev ->
564− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
565− when {
566− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
567− // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
568− // the field so the user can type immediately.
569− ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
570− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
571− ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
572− ev.key == Key.Escape && running && !showExitConfirm -> {
573− vm.abort(); true
574− }
575− else -> false
576− }
577− },
578− topBar = {
579− TopAppBar(
580− title = {
581− val changeLabel = stringResource(R.string.change_model_agent)
582− // The subtitle reads "model · agent", so tapping the title offers *both*
583− // — a small menu picks which picker to open. Previously the tap went
584− // straight to the model picker, leaving the agent changeable only via
585− // the overflow menu despite the title implying otherwise.
586− Box {
587− Row(
588− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
589− // node; the click label rides on `clickable` (onClickLabel) instead of
590− // an explicit contentDescription, which would have SUPPRESSED the child
591− // Texts and announced only "Change model and agent".
592− modifier = Modifier
593− .clickable(
594− role = Role.Button,
595− onClickLabel = changeLabel,
596− ) { showTitleMenu = true }
597− .semantics(mergeDescendants = true) {},
598− verticalAlignment = Alignment.CenterVertically,
599− ) {
600− Column(modifier = Modifier.weight(1f, fill = false)) {
601− // maxLines=1 + Ellipsis so a long session title can't wrap and
602− // push the top bar to multiple lines, shifting the whole layout.
603− Text(
604− sessionTitle ?: sessionLabel,
605− maxLines = 1,
606− overflow = TextOverflow.Ellipsis,
607− )
608− Text(
609− subtitle,
610− style = MaterialTheme.typography.labelSmall,
611− color = MaterialTheme.colorScheme.onSurfaceVariant,
612− maxLines = 1,
613− overflow = TextOverflow.Ellipsis,
614− )
615− }
616− // Always show the affordance so the title reads as tappable even when
617− // the model catalog failed to load (models empty). Without it the title
618− // is indistinguishable from plain text and the pickers are effectively
619− // undiscoverable — and the dropdown items already disable themselves
620− // while a catalog is loading or unavailable.
621− Icon(
622− Icons.Filled.KeyboardArrowDown,
623− contentDescription = null,
624− tint = MaterialTheme.colorScheme.onSurfaceVariant,
625− modifier = Modifier.size(20.dp),
626− )
627− }
628− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
629− DropdownMenuItem(
630− text = { Text(stringResource(R.string.palette_switch_model)) },
631− enabled = !modelsLoading || models.isNotEmpty(),
632− onClick = { showTitleMenu = false; showModelPicker = true },
633− )
634− DropdownMenuItem(
635− text = { Text(stringResource(R.string.palette_choose_agent)) },
636− enabled = !agentsLoading || agents.isNotEmpty(),
637− onClick = { showTitleMenu = false; showAgentPicker = true },
638− )
639− }
640− }
641− },
642− navigationIcon = {
643− IconButton(onClick = {
644− if (running) showExitConfirm = true else onBack()
645− }) {
646− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
647− }
648− },
649− actions = {
650− // At-a-glance run status in the top bar. When the user is scrolled
651− // up (jump-to-latest FAB visible), the input-bar Stop button and the
652− // trailing "working…" row are off-screen, so a top-bar spinner is the
653− // only signal the agent is still working.
654− if (running) {
655− val workingLabel = stringResource(R.string.working)
656− CircularProgressIndicator(
657− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
658− strokeWidth = 2.dp,
659− )
660− }
661− // Manual refresh: forces an SSE reconnect, which re-seeds messages
662− // from REST. A recovery path when the stream silently drops and the
663− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
664− // immediate tap feedback — the SSE reconnect may not visibly change
665− // the connection state when already Connected, so without it the tap
666− // appears to do nothing. Disabled while a run is active: a mid-run
667− // refresh forces a reconnect that can interrupt the streaming reply,
668− // and the working spinner already signals "wait" — the recovery path
669− // is only needed when nothing is actively streaming.
670− val refreshLabel = stringResource(R.string.refresh)
671− IconButton(
672− onClick = { vm.refreshMessages() },
673− enabled = activeConnection != null && !refreshing && !running,
674− ) {
675− if (refreshing) {
676− CircularProgressIndicator(
677− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
678− strokeWidth = 2.dp,
679− )
680− } else {
681− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
682− }
683− }
684− // Overflow menu consolidates the less-frequent actions (share,
685− // commands, agent, model, rename, delete) so the top bar stays
686− // scannable on narrow phones — previously 5 icons crowded the bar
687− // alongside the back button and tappable title. Catalog-loading
688− // spinners stay inline (next to the overflow) so a load state is
689− // visible without opening the menu.
690− val moreLabel = stringResource(R.string.more)
691− val loadingLabel = stringResource(R.string.loading)
692− val shareLabel = stringResource(R.string.share_conversation)
693− val copyAsMarkdownLabel = stringResource(R.string.copy_as_markdown)
694− val shareAsJsonLabel = stringResource(R.string.share_as_json)
695− val copyAsJsonLabel = stringResource(R.string.copy_as_json)
696− val commandsLabel = stringResource(R.string.commands)
697− val renameLabel = stringResource(R.string.rename_session_chat)
698− val deleteLabel = stringResource(R.string.delete_session_chat)
699− val createShareLabel = stringResource(R.string.create_share_link)
700− val copyShareLabel = stringResource(R.string.copy_share_link)
701− val stopShareLabel = stringResource(R.string.stop_sharing)
702− val summarizeLabel = stringResource(R.string.summarize_conversation)
703− val initLabel = stringResource(R.string.generate_agents_md)
704− val shellLabel = stringResource(R.string.run_shell_command)
705− Box {
706− IconButton(onClick = { showOverflowMenu = true }) {
707− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
708− }
709− DropdownMenu(
710− expanded = showOverflowMenu,
711− onDismissRequest = { showOverflowMenu = false },
712− ) {
713− DropdownMenuItem(
714− text = { Text(shareLabel) },
715− enabled = hasMessages,
716− onClick = {
717− showOverflowMenu = false
718− scope.launch {
719− val md = withContext(Dispatchers.Default) {
720− buildConversationMarkdown(vm.messages.value, sessionTitle)
721− }
722− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
723− type = "text/markdown"
724− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
725− putExtra(android.content.Intent.EXTRA_TEXT, md)
726− }
727− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
728− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
729− }
730− },
731− )
732− // Copy the whole conversation as Markdown to the clipboard, so a
733− // user can paste into another app without the share-sheet round-trip.
734− DropdownMenuItem(
735− text = { Text(copyAsMarkdownLabel) },
736− enabled = hasMessages,
737− onClick = {
738− showOverflowMenu = false
739− scope.launch {
740− val md = withContext(Dispatchers.Default) {
741− buildConversationMarkdown(vm.messages.value, sessionTitle)
742− }
743− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), md)
744− }
745− },
746− )
747− // Lossless JSON share: the full List<MessageWithParts> serialized with
748− // the shared OpencodeJson, so tool outputs, file sources, and reasoning
749− // survive verbatim (the Markdown export truncates/summarizes them).
750− DropdownMenuItem(
751− text = { Text(shareAsJsonLabel) },
752− enabled = hasMessages,
753− onClick = {
754− showOverflowMenu = false
755− scope.launch {
756− val json = withContext(Dispatchers.Default) {
757− buildConversationJson(vm.messages.value)
758− }
759− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
760− type = "application/json"
761− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
762− putExtra(android.content.Intent.EXTRA_TEXT, json)
763− }
764− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareAsJsonLabel)) }
765− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
766− }
767− },
768− )
769− DropdownMenuItem(
770− text = { Text(copyAsJsonLabel) },
771− enabled = hasMessages,
772− onClick = {
773− showOverflowMenu = false
774− scope.launch {
775− val json = withContext(Dispatchers.Default) {
776− buildConversationJson(vm.messages.value)
777− }
778− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), json)
779− }
780− },
781− )
782− DropdownMenuItem(
783− text = { Text(commandsLabel) },
784− enabled = !commandsLoading || commands.isNotEmpty(),
785− onClick = { showOverflowMenu = false; showCommandPicker = true },
786− )
787− DropdownMenuItem(
788− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
789− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
790− )
791− DropdownMenuItem(
792− text = { Text(stringResource(R.string.find_in_conversation)) },
793− onClick = {
794− showOverflowMenu = false
795− searchActive = true
796− // Focus is requested by the LaunchedEffect(searchActive)
797− // below, which waits for the search field to be composed
798− // before requesting focus (calling requestFocus here would
799− // target a field that isn't in the composition yet).
800− },
801− )
802− androidx.compose.material3.HorizontalDivider()
803− // Session sharing: create a public link, copy an existing one, or revoke it.
804− if (shareUrl == null) {
805− DropdownMenuItem(
806− text = { Text(createShareLabel) },
807− enabled = hasMessages,
808− onClick = { showOverflowMenu = false; vm.shareSession() },
809− )
810− } else {
811− DropdownMenuItem(
812− text = { Text(copyShareLabel) },
813− onClick = {
814− showOverflowMenu = false
815− shareUrl?.let {
816− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
817− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
818− }
819− },
820− )
821− DropdownMenuItem(
822− text = { Text(stopShareLabel) },
823− onClick = { showOverflowMenu = false; vm.unshareSession() },
824− )
825− }
826− DropdownMenuItem(
827− text = { Text(summarizeLabel) },
828− enabled = hasMessages && !running,
829− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
830− )
831− DropdownMenuItem(
832− text = { Text(initLabel) },
833− enabled = !running,
834− onClick = { showOverflowMenu = false; showInitConfirm = true },
835− )
836− DropdownMenuItem(
837− text = { Text(shellLabel) },
838− enabled = !running,
839− onClick = { showOverflowMenu = false; showShellDialog = true },
840− )
841− androidx.compose.material3.HorizontalDivider()
842− DropdownMenuItem(
843− text = { Text(renameLabel) },
844− onClick = { showOverflowMenu = false; showRenameDialog = true },
845− )
846− DropdownMenuItem(
847− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
848− onClick = { showOverflowMenu = false; showDeleteDialog = true },
849− )
850− }
851− // While a catalog is initially loading (empty list + loading flag),
852− // show a tiny inline spinner beside the overflow so the user can see
853− // a load is in progress without opening the menu. Once loaded the
854− // spinner disappears; the menu items are always enabled (tapping a
855− // picker with no items shows the "no models/agents/commands" state).
856− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
857− (agentsLoading && agents.isEmpty()) ||
858− (modelsLoading && models.isEmpty())
859− if (catalogLoading) {
860− CircularProgressIndicator(
861− Modifier
862− .align(Alignment.TopEnd)
863− .size(10.dp)
864− .semantics { contentDescription = loadingLabel },
865− strokeWidth = 1.dp,
866− )
867− }
868− }
869− },
870− )
871− },
872− snackbarHost = { SnackbarHost(snackbar) },
873− bottomBar = {
874− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
875− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
876− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
877− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
878− Column {
879− // Pinned above the composer so the agent's plan and progress stay visible
880− // while scrolled up mid-run; renders nothing when there's no plan.
881− TodoPlanBar(todoPlan)
882− val bannerMotion = rememberVisibilityTransitions()
883− AnimatedVisibility(
884− visible = reverted,
885− enter = bannerMotion.enter,
886− exit = bannerMotion.exit,
887− ) {
888− RevertBanner(
889− diff = revertDiff,
890− isEditing = editing,
891− onUndo = { vm.unrevert() },
892− )
893− }
894− AnimatedVisibility(
895− visible = queuedOffline.isNotEmpty(),
896− enter = bannerMotion.enter,
897− exit = bannerMotion.exit,
898− ) {
899− OutboxBanner(
900− count = queuedOffline.size,
901− sending = outboxSending,
902− onFlush = { vm.flushQueued() },
903− onDiscard = { vm.discardAllQueued() },
904− )
905− }
906− AnimatedVisibility(
907− visible = pendingQuote != null,
908− enter = bannerMotion.enter,
909− exit = bannerMotion.exit,
910− ) {
911− pendingQuote?.let { QuoteReplyBanner(it, onCancel = { vm.cancelQuoteReply() }) }
912− }
913− ChatInputBar(
914− value = draft,
915− onValueChange = vm::updateDraft,
916− running = running,
917− aborting = aborting,
918− enabled = activeConnection != null,
919− sendOnEnter = sendOnEnter,
920− onSend = ::doSend,
921− onAbort = { vm.abort() },
922− queuedFollowUp = queuedFollowUp,
923− onQueueFollowUp = vm::queueFollowUp,
924− onCancelQueue = { vm.queueFollowUp("") },
925− focusRequester = inputFocusRequester,
926− attachments = attachments,
927− staging = stagingCount > 0,
928− stagingFileCount = stagingFileTotal,
929− onRemoveAttachment = vm::removeAttachment,
930− onPickPhoto = {
931− photoPicker.launch(
932− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
933− )
934− },
935− onPickFile = { filePicker.launch("*/*") },
936− onCamera = { launchCamera() },
937− onVoice = { launchVoice() },
938− onPasteImage = { stageUris(it) },
939− commands = commands,
940− onRunCommand = { cmd ->
941− vm.runCommand(cmd)
942− // Clear the draft so the typed /prefix doesn't linger after the
943− // command fires (the command picker confirmation, if any, is
944− // handled inside runCommand).
945− vm.updateDraft("")
946− },
947− )
948− }
949− },
950− ) { padding ->
951− // Collect messages inside the content lambda so streaming token updates
952− // recompose only this subtree, not the top bar / input bar / 20+ other
953− // state reads in the ChatScreen body.
954− val messages by vm.messages.collectAsStateWithLifecycle()
955− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
956− val listState = rememberLazyListState()
957− val contentScope = rememberCoroutineScope()
958− val timeTick = rememberRelativeTimeTick()
959− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
960− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
961− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
962− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
963− androidx.compose.runtime.LaunchedEffect(listState) {
964− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
965− .distinctUntilChanged()
966− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
967− } // Group messages by day and interleave date separators so a long conversation
968− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
969− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
970− // outside the PullToRefreshBox so the auto-scroll effects below can reference
971− // the same list the LazyColumn renders (separators shift the indices vs. the
972− // raw messages list, so scroll targets must be in listItems space).
973− val todayLabel = stringResource(R.string.today)
974− val yesterdayLabel = stringResource(R.string.yesterday)
975− // In-conversation search: when active, narrow to messages whose text contains the query.
976− // Computed on the filtered set so day separators still align with the visible messages.
977− // Debounced + off-main-thread so a keystroke-by-keystroke filter walk over a long
978− // conversation (with many tool parts whose state stringification is non-trivial)
979− // doesn't jank the UI. produceState yields the empty list immediately and publishes
980− // the filtered result once the debounce settles.
981− val searchQuery = chatSearch.trim()
982− val searchMessages by produceState(
983− initialValue = if (searchQuery.isEmpty()) messages else emptyList(),
984− messages,
985− searchQuery,
986− ) {
987− if (searchQuery.isEmpty()) {
988− value = messages
989− } else {
990− // Debounce: wait for the user to stop typing before running the filter,
991− // so each keystroke doesn't kick off a fresh scan.
992− kotlinx.coroutines.delay(NetworkConfig.chatSearchDebounceMs)
993− // Run the filter off the main thread — the walk stringifies tool state
994− // and scans every part of every message, which is non-trivial work for a
995− // long conversation.
996− value = withContext(Dispatchers.Default) {
997− messages.filter { m ->
998− m.parts.any { p ->
999− when (p) {
1000− is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
1001− is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
1002− is ToolPart -> {
1003− // Match the tool name plus its running/completed/error text and the
1004− // stringified input, so searching for an error string or a file the
1005− // tool touched actually finds the message it appeared in.
1006− p.tool.contains(searchQuery, ignoreCase = true) ||
1007− (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
1008− (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
1009− p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
1010− (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
1011− p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
1012− }
1013− is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
1014− p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
1015− else -> false
1016− }
1017− }
1018− }
1019− }
1020− }
1021− }
1022− // Keep the focused-match index in range as the query (and thus the match set) changes.
1023− // A new query resets to the first match; a shrunk set clamps to the last valid index.
1024− LaunchedEffect(searchQuery, searchMessages.size) {
1025− if (searchPos >= searchMessages.size) searchPos = 0
1026− }
1027− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
1028− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
1029− }
1030− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
1031− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
1032− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
1033− // would capture the first composition's list — which is empty, since `messages`
1034− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
1035− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
1036− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
1037− // whose value tracks the latest list.
1038− val currentListItems by rememberUpdatedState(listItems)
1039−
1040− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
1041− // while the user was scrolled away from the bottom, cleared once they return. A count
1042− // (vs. a bare dot) tells the user how much they missed at a glance.
1043− var newContentCount by remember { mutableIntStateOf(0) }
1044−
1045− val isPinnedToBottom by remember {
1046− derivedStateOf {
1047− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1048− // When a run is active, the LazyColumn has one trailing "__typing"
1049− // item after the last list item. Account for it so "pinned to bottom"
1050− // includes the working indicator — otherwise the pin check targets
1051− // listItems.lastIndex, the typing row sits just below the viewport,
1052− // and the user never sees the progress indicator even when pinned.
1053− val items = currentListItems
1054− val effectiveLast = if (running) items.size else items.lastIndex
1055− lastVisible >= effectiveLast || items.isEmpty()
1056− }
1057− }
1058−
1059− // Jump to the newest message once, when the conversation first loads. Guarded by a
1060− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1061− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1062− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1063− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1064− LaunchedEffect(listItems.isNotEmpty()) {
1065− if (listItems.isNotEmpty() && !didInitialScroll) {
1066− // When a run is active the LazyColumn has a trailing "__typing" row at
1067− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1068− // running session lands truly pinned to bottom and streaming auto-scroll engages.
1069− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1070− didInitialScroll = true
1071− }
1072− }
1073−
1074− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1075− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1076− // isPinnedToBottom check flips to false the instant you send — freezing
1077− // auto-scroll. If the user was pinned to the last item just before the run
1078− // began, bring the typing row into view so the pin (and streaming follow) is
1079− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1080− // recomputed to false by now) so we don't scroll when the user had scrolled up.
1081− LaunchedEffect(running) {
1082− if (running && listItems.isNotEmpty()) {
1083− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1084− if (lastVisible >= listItems.lastIndex) {
1085− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1086− }
1087− }
1088− }
1089−
1090− // Scroll the focused search match into view whenever the user steps through results with
1091− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1092− // includes date separators) and animates there.
1093− LaunchedEffect(searchPos, searchQuery, listItems) {
1094− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1095− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1096− val index = listItems.indexOfFirst {
1097− it is MessageListItem.Message && it.message.info.id == target.info.id
1098− }
1099− if (index >= 0) runCatchingCancellable { listState.animateScrollToItem(index) }
1100− }
1101−
1102− // Global-search deep link: scroll to and briefly highlight the matched message. The
1103− // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1104− // clears itself after a short delay so the user can re-read the surrounding context
1105− // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1106− var focusedMessageId by remember(focusMessageId) { mutableStateOf(focusMessageId) }
1107− LaunchedEffect(focusedMessageId, listItems) {
1108− val focus = focusedMessageId ?: return@LaunchedEffect
1109− if (listItems.isEmpty()) return@LaunchedEffect
1110− val index = listItems.indexOfFirst {
1111− it is MessageListItem.Message && it.message.info.id == focus
1112− }
1113− if (index < 0) return@LaunchedEffect
1114− runCatchingCancellable { listState.animateScrollToItem(index) }
1115− kotlinx.coroutines.delay(2500)
1116− focusedMessageId = null
1117− }
1118−
1119− // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1120− // latest reply stays visible as the composer rises. Without this the IME can obscure the
1121− // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1122− // @Composable property, so we read it inside a snapshotFlow registered in the composable
1123− // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1124− val density = androidx.compose.ui.platform.LocalDensity.current
1125− var wasImeOpen by remember { mutableStateOf(false) }
1126− val imeBottomPx = WindowInsets.ime.getBottom(density)
1127− androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1128− if (listItems.isEmpty()) return@LaunchedEffect
1129− val imeOpen = imeBottomPx > 0
1130− // Scroll to bottom only on the open transition (not close) and only when the user
1131− // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1132− val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1133− if (shouldScroll) {
1134− runCatchingCancellable {
1135− listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1136− }
1137− }
1138− wasImeOpen = imeOpen
1139− }
1140−
1141− LaunchedEffect(Unit) {
1142− var prevSize = 0
1143− var prevLen = 0
1144− snapshotFlow {
1145− // Track list size + the streaming length of the last part so we auto-scroll
1146− // as content arrives, plus the pinned flag. A small data class with primitive
1147− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1148− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1149− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1150− // and tool output — not just TextPart — keeps a pinned view following a long
1151− // reasoning/tool block while it streams (previously it stalled at 0).
1152− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1153− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1154− }.collect { signal ->
1155− if (signal.pinned) {
1156− // Back at the bottom: clear the new-content badge.
1157− newContentCount = 0
1158− if (signal.size > 0) {
1159− // Scroll to the effective last index, including the trailing
1160− // "__typing" row when a run is active so the working indicator
1161− // is brought into view (not just the last message).
1162− val items = currentListItems
1163− val target = if (running) items.size else items.lastIndex
1164− listState.scrollToItem(target)
1165− }
1166− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1167− // Content arrived while scrolled up — increment the jump-to-latest badge.
1168− // Only count whole new items (not per-token growth) so the number reflects
1169− // new messages, not a token count.
1170− if (signal.size > prevSize) newContentCount += signal.size - prevSize
1171− else if (newContentCount == 0) newContentCount = 1
1172− }
1173− prevSize = signal.size
1174− prevLen = signal.lastTextLength
1175− }
1176− }
1177−
1178− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1179− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1180− // content padding accounts for the bottomBar's raised height, so the message
1181− // list is already above the keyboard. Adding imePadding here would double-apply
1182− // the IME inset and push messages too far up.
1183− //
1184− // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1185− // message list on wide screens instead of floating at the screen edges — on a
1186− // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1187− // The horizontal margin below is applied to the FAB/search containers so they
1188− // track the list's left/right edges.
1189− androidx.compose.foundation.layout.BoxWithConstraints(
1190− modifier = Modifier.fillMaxSize().padding(padding),
1191− ) {
1192− val screenMaxWidth = maxWidth
1193− val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1194− // Horizontal margin between the capped list's edge and the screen edge (0 on
1195− // screens narrower than the cap). Applied as start/end padding so the FABs and
1196− // search bar sit at the list's edges, not the screen's.
1197− val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1198− if (activeConnection == null) {
1199− Column(
1200− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1201− horizontalAlignment = Alignment.CenterHorizontally,
1202− ) {
1203− Text(
1204− stringResource(R.string.not_connected),
1205− color = MaterialTheme.colorScheme.error,
1206− )
1207− Spacer(Modifier.size(12.dp))
1208− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1209− if (reconnecting) {
1210− CircularProgressIndicator(
1211− Modifier.size(20.dp),
1212− color = MaterialTheme.colorScheme.onPrimary,
1213− strokeWidth = 2.dp,
1214− )
1215− } else {
1216− Text(stringResource(R.string.reconnect))
1217− }
1218− }
1219− }
1220− } else {
1221− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1222− // Measure the banner's actual height instead of hardcoding 44dp. At large
1223− // accessibility font scales the banner's labelMedium text + spinner + Retry
1224− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1225− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1226− // fires while the banner is composed (visible), so gate the inset on
1227− // bannerVisible and fall back to 44dp until the first measurement arrives.
1228− var bannerHeightPx by remember { mutableIntStateOf(0) }
1229− // Track the search bar height so the list's top padding can grow when search
1230− // is active — otherwise a scrolled-to match lands at index 0, hidden behind
1231− // the floating search bar (the "scroll-under-the-search-bar" bug).
1232− var searchbarHeightPx by remember { mutableIntStateOf(0) }
1233− val density = LocalDensity.current
1234− val topPad = if (bannerVisible) {
1235− if (bannerHeightPx > 0) {
1236− with(density) { bannerHeightPx.toDp() } + 4.dp
1237− } else {
1238− 44.dp
1239− }
1240− } else {
1241− 16.dp
1242− } + if (searchActive && searchbarHeightPx > 0) {
1243− with(density) { searchbarHeightPx.toDp() } + 4.dp
1244− } else {
1245− 0.dp
1246− }
1247− ConnectionBanner(
1248− state = connectionState,
1249− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1250− isOnline = isOnline,
1251− // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1252− // re-seeds from REST). refreshMessages is the right recovery path
1253− // when the connection is present but the stream died; reconnect()
1254− // is the path when the whole connection is gone (handled by the
1255− // separate "Not connected" state below).
1256− onRetry = { vm.refreshMessages() },
1257− // On an auth failure (401/403), retrying with the same bad credentials
1258− // is futile — offer a one-tap path to edit the active profile's
1259− // credentials instead of making the user hunt for the server list.
1260− onEditCredentials = {
1261− val profileId = activeConnection?.profile?.id
1262− if (profileId != null) onEditProfile?.invoke(profileId)
1263− },
1264− reconnectAttempts = reconnectAttempts,
1265− )
1266− // Persistent inline error banner for a mid-conversation load failure.
1267− // Unlike the one-shot snackbar (which fires once per streak then goes
1268− // silent), this stays visible until the stream recovers, so a persistent
1269− // outage doesn't read as "everything is fine" after the snackbar dismisses.
1270− // Anchored at the top, below the connection banner, so it doesn't overlap
1271− // the message list.
1272− if (loadErrorInline && hasMessages) {
1273− Surface(
1274− color = MaterialTheme.colorScheme.errorContainer,
1275− shape = MaterialTheme.shapes.small,
1276− modifier = Modifier
1277− .align(Alignment.TopCenter)
1278− .padding(top = if (bannerVisible) topPad else 8.dp)
1279− .padding(horizontal = 16.dp)
1280− .semantics { liveRegion = LiveRegionMode.Polite },
1281− ) {
1282− Row(
1283− modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1284− verticalAlignment = Alignment.CenterVertically,
1285− horizontalArrangement = Arrangement.spacedBy(8.dp),
1286− ) {
1287− Icon(
1288− Icons.Filled.ErrorOutline,
1289− contentDescription = null,
1290− modifier = Modifier.size(16.dp),
1291− tint = MaterialTheme.colorScheme.onErrorContainer,
1292− )
1293− Text(
1294− stringResource(R.string.load_error_persistent),
1295− style = MaterialTheme.typography.labelMedium,
1296− color = MaterialTheme.colorScheme.onErrorContainer,
1297− modifier = Modifier.weight(1f),
1298− )
1299− TextButton(
1300− onClick = { vm.refreshMessages() },
1301− contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1302− ) {
1303− Text(stringResource(R.string.retry))
1304− }
1305− }
1306− }
1307− }
1308− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1309− // recovery is a swipe away everywhere — not just when the message list is
1310− // populated. Previously PTR was only around the populated list, leaving the
1311− // error/loading states reachable only via a button tap.
1312− PullToRefreshBox(
1313− isRefreshing = refreshing,
1314− // Suppress the refresh action while a run is active: a mid-stream
1315− // refresh forces an SSE reconnect that can interrupt the actively
1316− // streaming reply (matching the top-bar refresh button, which is
1317− // also disabled while running). The pull gesture still responds, but
1318− // the release no-ops instead of triggering a disruptive re-seed.
1319− onRefresh = { if (!running) vm.refreshMessages() },
1320− // Cap width and center on large screens for readability — full-width
1321− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1322− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1323− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1324− ) {
1325− // Reserve top space when the banner is visible so it doesn't overlap the
1326− // first message / state content. (topPad computed above.)
1327− if (loading && messages.isEmpty()) {
1328− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1329− // than a bare centered spinner and the first real messages pop into an
1330− // already-shaped list instead of a blank-then-pop.
1331− ChatSkeleton(topPad = topPad)
1332− } else if (loadError && messages.isEmpty()) {
1333− // A failed load with nothing to show. Distinct from the empty
1334− // conversation state below — the conversation isn't empty, it
1335− // failed to load, and offering "Start a conversation" here is
1336− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1337− Column(
1338− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1339− horizontalAlignment = Alignment.CenterHorizontally,
1340− ) {
1341− Text(
1342− stringResource(R.string.load_messages_failed),
1343− color = MaterialTheme.colorScheme.error,
1344− )
1345− Spacer(Modifier.size(12.dp))
1346− Button(onClick = { vm.refreshMessages() }) {
1347− Text(stringResource(R.string.retry))
1348− }
1349− // When the VM's retryWhen loop is actively retrying (loading is true
1350− // on top of the error state), surface a small "retrying…" indicator so
1351− // the user knows the system is working — without it, the static error
1352− // + Retry button reads as "broken, tap to fix", and the user may not
1353− // realize an automatic retry is already in progress.
1354− if (loading) {
1355− Spacer(Modifier.size(12.dp))
1356− val retryingLabel = stringResource(R.string.retrying_ellipsis)
1357− Row(verticalAlignment = Alignment.CenterVertically) {
1358− CircularProgressIndicator(
1359− Modifier.size(14.dp),
1360− strokeWidth = 2.dp,
1361− )
1362− Text(
1363− retryingLabel,
1364− style = MaterialTheme.typography.labelSmall,
1365− color = MaterialTheme.colorScheme.onSurfaceVariant,
1366− modifier = Modifier.padding(start = 6.dp),
1367− )
1368− }
1369− }
1370− }
1371− } else if (messages.isEmpty() && running) {
1372− // A run just started but no parts have arrived yet — the empty list with
1373− // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1374− // from the initial-load branch so the perceived start latency is lower and
1375− // the first real assistant part pops into an already-shaped list.
1376− ChatSkeleton(topPad = topPad)
1377− } else if (messages.isEmpty()) {
1378− EmptyConversation(
1379− onSuggestion = {
1380− vm.updateDraft(it)
1381− // Focus the input so the user can edit the suggestion before
1382− // sending, instead of having to manually tap the field.
1383− runCatching { inputFocusRequester.requestFocus() }
1384− },
1385− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1386− )
1387− } else {
1388− val lastMessageId = messages.lastOrNull()?.info?.id
1389− // Text-to-speech for reading assistant replies aloud; shuts down when the
1390− // message list leaves composition.
1391− val tts = rememberTtsController()
1392− val speakingMessageId by tts.speakingId
1393− val ttsState by tts.state
1394− // Provide the in-conversation search query to the markdown renderer so matching
1395− // text spans are highlighted in-place (in addition to the focused-row highlight
1396− // above). Scoped to the list so cleared search stops highlighting immediately.
1397− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1398− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1399− LazyColumn(
1400− state = listState,
1401− modifier = Modifier.fillMaxSize(),
1402− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1403− // never floats over the last message. Top padding grows when the
1404− // connection banner is visible so it doesn't overlap the first message.
1405− contentPadding = PaddingValues(
1406− start = 16.dp,
1407− top = topPad,
1408− end = 16.dp,
1409− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1410− ),
1411− // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1412− // more conversation on screen without scrolling as much.
1413− verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1414− ) {
1415− items(
1416− items = listItems,
1417− key = { it.key },
1418− contentType = { it.contentType },
1419− ) { item ->
1420− // When in-conversation search is stepping through matches, highlight the
1421− // focused one's row so the user can spot it at a glance among the filtered
1422− // results (full in-text term highlighting would require threading the query
1423− // through the markdown renderer; the row highlight + scroll-to-match covers
1424− // the navigation use case desktop chat apps solve with next/prev).
1425− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1426− searchMessages.getOrNull(searchPos)?.info?.id
1427− } else null
1428− val isFocusedMatch = focusedMatchId != null &&
1429− item is MessageListItem.Message &&
1430− item.message.info.id == focusedMatchId
1431− // Default placement animation so inserted/moved rows glide in. Skipped
1432− // entirely under reduced motion so a streaming message growing in place
1433− // doesn't animate on every token (and respects the a11y preference).
1434− Box(
1435− Modifier
1436− .then(reducedMotionAnimateItem())
1437− .then(
1438− if (isFocusedMatch) {
1439− Modifier.background(
1440− MaterialTheme.colorScheme.secondaryContainer,
1441− MaterialTheme.shapes.medium,
1442− )
1443− } else {
1444− Modifier
1445− },
1446− ),
1447− ) {
1448− when (item) {
1449− is MessageListItem.Separator -> DateSeparator(item.label)
1450− is MessageListItem.Message -> {
1451− val message = item.message
1452− // Only the last (streaming) message needs isRunning — it drives the
1453− // reasoning-block spinner. Passing the live flag to every bubble
1454− // makes all visible messages recompose whenever a run starts or stops.
1455− val modelLabel = remember(message.info, models) {
1456− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1457− ?.let { resolveModelLabel(it, models) }
1458− }
1459− val agentLabel = remember(message.parts) {
1460− message.parts
1461− .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1462− .firstOrNull { it.name.isNotBlank() }?.name
1463− }
1464− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1465− // image/code-only messages, which then opt out of the swipe gesture.
1466− val quoteText = remember(message.parts) {
1467− message.parts
1468− .filterIsInstance<TextPart>()
1469− .joinToString("\n\n") { it.text }
1470− .trim()
1471− .takeIf { it.isNotEmpty() }
1472− }
1473− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1474− // snapping back (the message isn't dismissed — the quote fills the composer).
1475− // Enabled for non-text messages too (image/tool-only), but the confirm
1476− // callback gives a haptic without triggering reply — so the user gets a
1477− // perceptible "can't quote this" signal instead of a silently dead gesture.
1478− val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1479− val undoLabel = stringResource(R.string.undo)
1480− val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1481− val swipeState = rememberSwipeToDismissBoxState(
1482− confirmValueChange = { value ->
1483− val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1484− SwipeToDismissBoxValue.EndToStart
1485− } else {
1486− SwipeToDismissBoxValue.StartToEnd
1487− }
1488− if (value == replyValue) {
1489− if (quoteText != null) {
1490− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1491− vm.quoteReply(quoteText)
1492− runCatching { inputFocusRequester.requestFocus() }
1493− // Offer a quick Undo for an accidental swipe,
1494− // mirroring the app's undo-everywhere ethos so
1495− // the user needn't reach for the banner's X.
1496− scope.launch {
1497− val res = snackbar.showSnackbar(
1498− message = quoteReplyLabel,
1499− actionLabel = undoLabel,
1500− )
1501− if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1502− vm.cancelQuoteReply()
1503− }
1504− }
1505− } else {
1506− // Non-text message: give a longer haptic so the user
1507− // feels the gesture was received but can't quote it,
1508− // and surface a brief toast so the reason is clear.
1509− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1510− scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1511− }
1512− }
1513− false
1514− },
1515− )
1516− // In RTL locales, mirror the swipe direction so the reply
1517− // gesture reads naturally (swipe from the trailing edge
1518− // toward the leading edge), matching how LTR users swipe
1519− // left-to-right. Without this, RTL users had no reply swipe.
1520− val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1521− SwipeToDismissBox(
1522− state = swipeState,
1523− enableDismissFromEndToStart = !replyFromStartToEnd,
1524− enableDismissFromStartToEnd = replyFromStartToEnd,
1525− backgroundContent = {
1526− Box(
1527− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1528− contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1529− ) {
1530− Icon(
1531− Icons.AutoMirrored.Filled.Reply,
1532− contentDescription = null,
1533− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1534− )
1535− }
1536− },
1537− ) {
1538− MessageBubble(
1539− message,
1540− isRunning = running && message.info.id == lastMessageId,
1541− imageContext = imageContext,
1542− modelLabel = modelLabel,
1543− agentLabel = agentLabel,
1544− onOpenFile = onOpenFile,
1545− onRevert = { vm.revertTo(message.info.id) },
1546− onEdit = { text -> // editMessage reverts to before this message (hiding it and
1547− // everything after); the revert banner surfaces the rewind
1548− // with an Undo. Focus + scroll the composer into view like the
1549− // Quote action so the prefilled draft isn't off-screen.
1550− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1551− vm.editMessage(message.info.id, text)
1552− runCatching { inputFocusRequester.requestFocus() }
1553− contentScope.launch {
1554− runCatchingCancellable {
1555− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1556− }
1557− }
1558− },
1559− onSpeak = { text ->
1560− if (!tts.toggle(message.info.id, text)) {
1561− // TTS engine unavailable (init failed / not yet ready
1562− // / blank text): surface feedback so the button doesn't
1563− // appear dead. Throttled so a rapid double-tap (stop
1564− // then immediate re-tap before ready) doesn't spam.
1565− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1566− }
1567− },
1568− isSpeaking = message.info.id == speakingMessageId,
1569− ttsState = if (message.info.id == speakingMessageId) ttsState else TtsState.IDLE,
1570− onPause = { tts.pause() },
1571− onResume = { tts.resume() },
1572− onStop = { tts.stop() },
1573− onQuote = { text ->
1574− vm.quoteReply(text)
1575− runCatching { inputFocusRequester.requestFocus() }
1576− },
1577− onBranch = { text -> vm.branchFrom(text) },
1578− // Regenerate is only meaningful for a finished assistant reply
1579− // (not the actively-streaming one), so gate it on !running.
1580− onRegenerate = if (!running) {
1581− { vm.regenerate(message.info.id) }
1582− } else null,
1583− // Continue: resume a partial reply. Shown only for
1584− // incomplete assistant messages (a partial reply that
1585− // was aborted) and not while a run is active.
1586− onContinue = if (!running && message.info is AssistantMessage && !message.info.isComplete) {
1587− { vm.continueRun(message.info.id) }
1588− } else null,
1589− sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1590− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1591− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1592− },
1593− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1594− onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1595− if (failed) {
1596− { vm.retryOptimisticMessage(message.info.id) }
1597− } else {
1598− null
1599− }
1600− },
1601− onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1602− if (failed) {
1603− { vm.dismissOptimistic(message.info.id) }
1604− } else {
1605− null
1606− }
1607− },
1608− onShare = {
1609− // Per-message share: build a single-message Markdown
1610− // transcript off-thread and fire ACTION_SEND, mirroring the
1611− // whole-conversation share but scoped to just this message.
1612− scope.launch {
1613− val md = withContext(Dispatchers.Default) {
1614− buildMessageMarkdown(message)
1615− } ?: return@launch
1616− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1617− type = "text/markdown"
1618− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1619− putExtra(android.content.Intent.EXTRA_TEXT, md)
1620− }
1621− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1622− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1623− }
1624− },
1625− isFirstOfSpeaker = item.isFirstOfSpeaker,
1626− highlighted = focusedMessageId != null && message.info.id == focusedMessageId,
1627− )
1628− }
1629− }
1630− }
1631− }
1632− }
1633− if (running) {
1634− item(key = "__typing") {
1635− val workingText = stringResource(R.string.working)
1636− // When the SSE stream dropped mid-run, show a "reconnecting" label
1637− // instead of the plain "working" text so the user understands the
1638− // run is still active but the stream is reconnecting (not finished).
1639− val reconnectingText = stringResource(R.string.reconnecting)
1640− val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1641− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1642− // survives LazyColumn recycling — a local remember reset to 0:00 when
1643− // the row was disposed and scrolled back into view. The VM stamps the
1644− // start on the real false→true transition (send/run/init), not on
1645− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1646− // once per second; the value is decorative (the a11y label is the row's).
1647− // The clock freezes when an abort is confirmed (aborting = true) so the
1648− // user can see how long the run lasted before they stopped it, rather
1649− // than the clock continuing to tick until SessionIdle clears _running.
1650− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1651− val elapsedMs by produceState(0L, startMs, aborting) {
1652− if (startMs == 0L) return@produceState
1653− if (aborting) {
1654− // Freeze at the last-computed value: one final snapshot then stop.
1655− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1656− return@produceState
1657− }
1658− while (true) {
1659− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1660− delay(1000)
1661− }
1662− }
1663− val elapsedText = remember(elapsedMs) {
1664− val total = elapsedMs / 1000
1665− // Locale.US for stable digit formatting: on locales with
1666− // non-ASCII digits (ar-/fa-) the default locale would render
1667− // localized digits inside the Monospace block, breaking the
1668− // fixed-width alignment the monospace family was chosen for.
1669− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1670− }
1671− Row(
1672− verticalAlignment = Alignment.CenterVertically,
1673− // Animate this slot in/out so the working row doesn't pop in and
1674− // jolt the message list when a run starts/stops — matching the
1675− // AnimatedVisibility used by every other transient banner/FAB here.
1676− modifier = Modifier
1677− .then(reducedMotionAnimateItem())
1678− .padding(vertical = 4.dp),
1679− ) {
1680− // Merge the indicator + label + clock into one TalkBack node so
1681− // it's announced once (the working label, then the elapsed time)
1682− // instead of "working… / working… / 0:14" with the label read
1683− // twice. The Stop IconButton below stays separately focusable.
1684− Row(
1685− verticalAlignment = Alignment.CenterVertically,
1686− modifier = Modifier.semantics(mergeDescendants = true) {
1687− contentDescription = "$interruptedLabel $elapsedText"
1688− },
1689− ) {
1690− // Dim the spinner when interrupted so the row reads as
1691− // "paused/reconnecting" rather than actively progressing.
1692− CircularProgressIndicator(
1693− Modifier.size(16.dp),
1694− strokeWidth = 2.dp,
1695− color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1696− else MaterialTheme.colorScheme.primary,
1697− )
1698− Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1699− Spacer(Modifier.size(8.dp))
1700− Icon(
1701− Icons.Filled.Schedule,
1702− contentDescription = null,
1703− modifier = Modifier.size(14.dp),
1704− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1705− )
1706− Text(
1707− elapsedText,
1708− style = MaterialTheme.typography.labelMedium,
1709− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1710− color = MaterialTheme.colorScheme.onSurfaceVariant,
1711− modifier = Modifier.padding(start = 4.dp),
1712− )
1713− }
1714− // A trailing Stop on the working row so the run can be aborted
1715− // without scrolling back to the composer (which may be off-screen
1716− // while the user reads the streaming output up-thread).
1717− Spacer(Modifier.weight(1f))
1718− val stopLabel = stringResource(R.string.stop)
1719− IconButton(
1720− onClick = { vm.abort() },
1721− modifier = Modifier.semantics { contentDescription = stopLabel },
1722− ) {
1723− Icon(Icons.Filled.Stop, contentDescription = null)
1724− }
1725− }
1726− }
1727− }
1728− }
1729− }
1730− }
1731− }
1732− // Jump-to-latest affordance when the user has scrolled away during a stream.
1733− val fabMotion = rememberVisibilityTransitions()
1734− AnimatedVisibility(
1735− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1736− enter = fabMotion.enter,
1737− exit = fabMotion.exit,
1738− // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1739− // edge instead of floating at the screen edge (visually detached on tablets).
1740− modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1741− ) {
1742− // Badge the FAB when new content arrived while the user was scrolled up, so
1743− // they know there's something new to jump to (cleared once back at bottom).
1744− BadgedBox(
1745− badge = {
1746− if (newContentCount > 0) {
1747− // Merge the count into the badge announcement so TalkBack reads
1748− // "5 new messages" instead of the bare label and a separate number.
1749− val newContentLabel = pluralStringResource(
1750− R.plurals.plurals_new_messages,
1751− newContentCount,
1752− newContentCount,
1753− )
1754− Badge(
1755− modifier = Modifier.semantics {
1756− contentDescription = newContentLabel
1757− // Announce new-content counts as they change so a
1758− // TalkBack user hears "5 new messages" without having
1759− // to focus the FAB. Polite so it doesn't interrupt an
1760− // in-progress utterance (e.g. streaming token reads).
1761− liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1762− },
1763− ) {
1764− Text(
1765− if (newContentCount > 99) "99+" else newContentCount.toString(),
1766− modifier = Modifier.semantics { invisibleToUser() },
1767− )
1768− }
1769− }
1770− },
1771− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1772− ) {
1773− ExtendedFloatingActionButton(
1774− onClick = {
1775− newContentCount = 0
1776− if (listItems.isNotEmpty()) {
1777− // Scroll to the effective last index, including the
1778− // trailing "__typing" row when a run is active.
1779− val target = if (running) listItems.size else listItems.lastIndex
1780− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1781− }
1782− },
1783− // contentDescription null: the visible "Latest" text already labels
1784− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1785− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1786− text = { Text(stringResource(R.string.latest)) },
1787− )
1788− }
1789− }
1790− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1791− // user has scrolled down past the first few messages. Symmetric to the
1792− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1793− val scrolledDown by remember {
1794− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1795− }
1796− AnimatedVisibility(
1797− visible = scrolledDown && listItems.size > 4,
1798− enter = fabMotion.enter,
1799− exit = fabMotion.exit,
1800− modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1801− ) {
1802− SmallFloatingActionButton(
1803− onClick = {
1804− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1805− },
1806− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1807− ) {
1808− Icon(
1809− Icons.Filled.KeyboardArrowUp,
1810− contentDescription = stringResource(R.string.scroll_to_top),
1811− )
1812− }
1813− }
1814− // In-conversation search bar. Overlays the list so typing filters messages in
1815− // place; the match count + a no-matches note give immediate feedback.
1816− val searchMotion = rememberVisibilityTransitions()
1817− AnimatedVisibility(
1818− visible = searchActive,
1819− enter = searchMotion.enter,
1820− exit = searchMotion.exit,
1821− // Inset by sideMargin on wide screens so the search bar spans the capped
1822− // list's width, not the full screen width.
1823− modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1824− ) {
1825− Surface(
1826− tonalElevation = 3.dp,
1827− modifier = Modifier
1828− .padding(horizontal = 12.dp, vertical = 4.dp)
1829− .fillMaxWidth()
1830− .onSizeChanged { searchbarHeightPx = it.height },
1831− ) {
1832− // Focus the search field when the bar appears (from the overflow menu's
1833− // "Find in conversation" or Ctrl+F), so the user can start typing
1834− // immediately. Runs after the search field enters the composition.
1835− LaunchedEffect(searchActive) {
1836− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1837− }
1838− Row(
1839− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1840− verticalAlignment = Alignment.CenterVertically,
1841− ) {
1842− OutlinedTextField(
1843− value = chatSearch,
1844− onValueChange = { chatSearch = it },
1845− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1846− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1847− singleLine = true,
1848− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1849− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1850− )
1851− // Match counter: "N of M" where N is the focused match (1-based) and
1852− // M is the total matching messages. Only shown when there's a query.
1853− val matchCount = searchMessages.size
1854− Text(
1855− if (searchQuery.isNotEmpty() && matchCount > 0) {
1856− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1857− } else if (searchQuery.isNotEmpty()) {
1858− stringResource(R.string.search_no_matches)
1859− } else "",
1860− style = MaterialTheme.typography.labelSmall,
1861− color = MaterialTheme.colorScheme.onSurfaceVariant,
1862− modifier = Modifier
1863− .padding(horizontal = 4.dp)
1864− // Live region so a TalkBack user hears "3 of 12" / "No
1865− // matches" announce as they step through results, not just
1866− // the sighted user seeing the counter update.
1867− .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
1868− )
1869− // Step through matches (Previous / Next), disabled when there are
1870− // fewer than two to navigate. Wrap around at the ends so repeated
1871− // taps cycle through every hit.
1872− val prevLabel = stringResource(R.string.find_previous)
1873− val nextLabel = stringResource(R.string.find_next)
1874− IconButton(
1875− onClick = {
1876− if (matchCount > 0) {
1877− searchPos = (searchPos - 1 + matchCount) % matchCount
1878− }
1879− },
1880− enabled = matchCount > 1,
1881− ) {
1882− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1883− }
1884− IconButton(
1885− onClick = {
1886− if (matchCount > 0) {
1887− searchPos = (searchPos + 1) % matchCount
1888− }
1889− },
1890− enabled = matchCount > 1,
1891− ) {
1892− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
1893− }
1894− IconButton(onClick = {
1895− searchActive = false
1896− chatSearch = ""
1897− }) {
1898− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1899− }
1900− }
1901− }
1902− }
1903− // When a search yields no matches (but the conversation isn't empty), say so
1904− // instead of showing a blank list.
1905− if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1906− Text(
1907− stringResource(R.string.search_no_matches),
1908− style = MaterialTheme.typography.bodyMedium,
1909− color = MaterialTheme.colorScheme.onSurfaceVariant,
1910− modifier = Modifier.align(Alignment.Center),
1911− )
1912− }
1913− }
1914− }
1915− }
1916− }
1917−
1918− if (showExitConfirm) {
1919− AlertDialog(
1920− onDismissRequest = { showExitConfirm = false },
1921− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1922− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1923− confirmButton = {
1924− TextButton(onClick = {
1925− showExitConfirm = false
1926− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1927− vm.abort()
1928− onBack()
1929− }) { Text(stringResource(R.string.stop_and_exit)) }
1930− },
1931− dismissButton = {
1932− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1933− },
1934− )
1935− }
1936−
1937− if (showSummarizeConfirm) {
1938− AlertDialog(
1939− onDismissRequest = { showSummarizeConfirm = false },
1940− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1941− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1942− confirmButton = {
1943− TextButton(onClick = {
1944− showSummarizeConfirm = false
1945− vm.summarize()
1946− }) { Text(stringResource(R.string.action_continue)) }
1947− },
1948− dismissButton = {
1949− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1950− },
1951− )
1952− }
1953−
1954− if (showInitConfirm) {
1955− AlertDialog(
1956− onDismissRequest = { showInitConfirm = false },
1957− title = { Text(stringResource(R.string.init_confirm_title)) },
1958− text = { Text(stringResource(R.string.init_confirm_text)) },
1959− confirmButton = {
1960− TextButton(onClick = {
1961− showInitConfirm = false
1962− vm.initProject()
1963− }) { Text(stringResource(R.string.action_continue)) }
1964− },
1965− dismissButton = {
1966− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1967− },
1968− )
1969− }
1970−
1971− if (showRenameDialog) {
1972− RenameSessionChatDialog(
1973− initialTitle = sessionTitle ?: "",
1974− onDismiss = { showRenameDialog = false },
1975− onConfirm = { newName ->
1976− showRenameDialog = false
1977− vm.renameSession(newName)
1978− },
1979− )
1980− }
1981−
1982− if (showDeleteDialog) {
1983− AlertDialog(
1984− onDismissRequest = { showDeleteDialog = false },
1985− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1986− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1987− confirmButton = {
1988− TextButton(onClick = {
1989− showDeleteDialog = false
1990− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1991− vm.deleteSession()
1992− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1993− },
1994− dismissButton = {
1995− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1996− },
1997− )
1998− }
1999−
2000− if (showShellDialog) {
2001− ShellCommandDialog(
2002− onDismiss = { showShellDialog = false },
2003− onRun = { cmd ->
2004− showShellDialog = false
2005− vm.runShell(cmd)
2006− },
2007− )
2008− }
2009−
2010− if (showModelPicker) {
2011− // Resolve persisted recent composite keys to the live ModelOption entries they refer
2012− // to, dropping any whose model is no longer offered by the server. Ordered by
2013− // recency (head of the store first).
2014− val recentOptions = remember(models, recentModelEntries) {
2015− val byKey = models.associateBy { it.providerID to it.modelID }
2016− recentModelEntries.mapNotNull { entry ->
2017− container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2018− }
2019− }
2020− // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2021− // below isn't @Composable, so stringResource can't be called inside it.
2022− val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2023− val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2024− ModelPickerSheet(
2025− options = models,
2026− selected = selectedModel,
2027− loading = modelsLoading,
2028− error = modelsError,
2029− onSelect = {
2030− vm.selectModel(it)
2031− container.recentModelsStore.add(it.providerID, it.modelID)
2032− },
2033− onRetry = { vm.reloadModels() },
2034− onDismiss = { showModelPicker = false },
2035− preferredModelId = preferredModelId,
2036− onSetPreferredModel = { id ->
2037− scope.launch {
2038− runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2039− // Confirm the change with a snackbar so the user sees it took effect —
2040− // the toggle's label flip can be missed, especially when clearing.
2041− val msg = if (id.isEmpty()) {
2042− defaultModelClearedMsg
2043− } else {
2044− val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2045− defaultModelSetFmt.format(label)
2046− }
2047− snackbar.showSnackbar(msg)
2048− }
2049− },
2050− recent = recentOptions,
2051− )
2052− }
2053−
2054− if (showAgentPicker) {
2055− AgentPickerSheet(
2056− agents = agents,
2057− selected = selectedAgent,
2058− loading = agentsLoading,
2059− error = agentsError,
2060− onSelect = { vm.selectAgent(it?.name) },
2061− onRetry = { vm.reloadAgents() },
2062− onDismiss = { showAgentPicker = false },
2063− )
2064− }
2065−
2066− if (showCommandPicker) {
2067− CommandPickerSheet(
2068− commands = commands,
2069− loading = commandsLoading,
2070− error = commandsError,
2071− onSelect = { vm.runCommand(it) },
2072− onRetry = { vm.reloadCommands() },
2073− onDismiss = { showCommandPicker = false },
2074− )
2075− }
2076−
2077− pendingPermission?.let { permission ->
2078− PermissionDialog(
2079− permission = permission,
2080− position = permissionProgress.position,
2081− total = permissionProgress.total,
2082− onRespond = { response -> vm.respondPermission(permission, response) },
2083− // On auto-reject timeout, post a notification so a returning user finds a
2084− // persistent record of why the run stopped (the dialog itself is gone).
2085− // Gated by the user's notification setting (notifPermission).
2086− onAutoReject = {
2087− val conn = activeConnection
2088− val ctx = appContext
2089− val title = sessionTitle ?: sessionId
2090− if (notifPermission) {
2091− soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2092− ctx, sessionId, title, conn?.profile?.id,
2093− )
2094− }
2095− },
2096− )
2097− }
2098−
2099− if (showPalette) {
2100− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2101− }
2102−
2103− if (showShortcutsDialog) {
2104− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2105− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2106− // depends on the "Send on Enter" setting, noted inline.
2107− AlertDialog(
2108− onDismissRequest = { showShortcutsDialog = false },
2109− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2110− text = {
2111− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2112− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2113− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2114− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2115− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2116− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2117− }
2118− },
2119− confirmButton = {
2120− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2121− },
2122− )
2123− }
2124−}
2125−
2126−@Composable
2127−private fun ShortcutRow(keys: String, desc: String) {
2128− Row(verticalAlignment = Alignment.CenterVertically) {
2129− Text(
2130− keys,
2131− style = MaterialTheme.typography.labelLarge,
2132− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2133− modifier = Modifier.widthIn(min = 160.dp),
2134− )
2135− Text(
2136− desc,
2137− style = MaterialTheme.typography.bodyMedium,
2138− color = MaterialTheme.colorScheme.onSurfaceVariant,
2139− )
2140− }
2141−}
2142−
2143−/**
2144− * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2145− * of matching commands above the composer. Tapping a command fires it immediately.
2146− * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2147− * the detekt threshold. Suppressed while running or when the command catalog is empty.
2148− */
2149−@Composable
2150−private fun SlashCommandAutocomplete(
2151− value: String,
2152− commands: List<Command>,
2153− running: Boolean,
2154− onRunCommand: (Command) -> Unit,
2155−) {
2156− if (running || commands.isEmpty()) return
2157− val slashQuery = remember(value) {
2158− if (value.startsWith("/")) value.removePrefix("/") else null
2159− } ?: return
2160− val matchingCommands = remember(slashQuery, commands) {
2161− commands.filter { cmd ->
2162− slashQuery.isEmpty() ||
2163− cmd.name.contains(slashQuery, ignoreCase = true) ||
2164− (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2165− }.take(8)
2166− }
2167− if (matchingCommands.isNotEmpty()) {
2168− CommandAutocompleteDropdown(
2169− commands = matchingCommands,
2170− onPick = onRunCommand,
2171− )
2172− }
2173−}
2174−
2175−/**
2176− * Slash-command autocomplete dropdown shown above the composer when the draft starts
2177− * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2178− * user can discover and invoke commands by typing the conventional "/" prefix instead
2179− * of opening the overflow menu / command palette. Tapping a row fires the command.
2180− */
2181−@Composable
2182−private fun CommandAutocompleteDropdown(
2183− commands: List<Command>,
2184− onPick: (Command) -> Unit,
2185−) {
2186− val haptics = LocalHapticFeedback.current
2187− Surface(
2188− color = MaterialTheme.colorScheme.surface,
2189− tonalElevation = 3.dp,
2190− shape = MaterialTheme.shapes.medium,
2191− modifier = Modifier
2192− .fillMaxWidth()
2193− .padding(horizontal = 8.dp, vertical = 4.dp)
2194− .heightIn(max = 240.dp),
2195− ) {
2196− LazyColumn {
2197− items(
2198− count = commands.size,
2199− key = { commands[it].name },
2200− ) { i ->
2201− val cmd = commands[i]
2202− Row(
2203− modifier = Modifier
2204− .fillMaxWidth()
2205− .clickable(role = Role.Button) {
2206− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2207− onPick(cmd)
2208− }
2209− .padding(horizontal = 16.dp, vertical = 10.dp),
2210− verticalAlignment = Alignment.CenterVertically,
2211− horizontalArrangement = Arrangement.spacedBy(12.dp),
2212− ) {
2213− Text(
2214− "/${cmd.name}",
2215− style = MaterialTheme.typography.labelLarge,
2216− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2217− color = MaterialTheme.colorScheme.primary,
2218− )
2219− cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2220− Text(
2221− desc,
2222− style = MaterialTheme.typography.bodySmall,
2223− color = MaterialTheme.colorScheme.onSurfaceVariant,
2224− maxLines = 1,
2225− overflow = TextOverflow.Ellipsis,
2226− )
2227− }
2228− }
2229− }
2230− }
2231− }
2232−}
2233−
2234−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2235−@Suppress("CyclomaticComplexMethod")
2236−@Composable
2237−private fun ChatInputBar(
2238− value: String,
2239− onValueChange: (String) -> Unit,
2240− running: Boolean,
2241− aborting: Boolean,
2242− enabled: Boolean,
2243− sendOnEnter: Boolean,
2244− onSend: () -> Unit,
2245− onAbort: () -> Unit,
2246− queuedFollowUp: String?,
2247− onQueueFollowUp: (String) -> Unit,
2248− onCancelQueue: () -> Unit,
2249− focusRequester: androidx.compose.ui.focus.FocusRequester,
2250− attachments: List<PendingAttachment>,
2251− staging: Boolean,
2252− stagingFileCount: Int,
2253− onRemoveAttachment: (String) -> Unit,
2254− onPickPhoto: () -> Unit,
2255− onPickFile: () -> Unit,
2256− onCamera: () -> Unit,
2257− onVoice: () -> Unit,
2258− onPasteImage: (List<Uri>) -> Unit,
2259− commands: List<Command> = emptyList(),
2260− onRunCommand: (Command) -> Unit = {},
2261−) {
2262− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2263− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2264− val context = LocalContext.current
2265− // Full-screen editor state: opened when the user wants more space for a long prompt.
2266− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2267− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2268− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2269− // A queued follow-up replaces the Stop button with a "queued" chip so the
2270− // user sees their message will be sent when the run finishes, and can cancel.
2271− if (queuedFollowUp != null) {
2272− val editLabel = stringResource(R.string.edit)
2273− Row(
2274− modifier = Modifier
2275− .fillMaxWidth()
2276− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2277− verticalAlignment = Alignment.CenterVertically,
2278− ) {
2279− // Tapping the chip reloads the queued text into the draft (and clears the
2280− // queue) so a typo spotted while queuing can be fixed without retyping.
2281− Column(
2282− modifier = Modifier
2283− .weight(1f)
2284− .clip(MaterialTheme.shapes.small)
2285− .clickable(role = Role.Button, onClickLabel = editLabel) {
2286− onValueChange(queuedFollowUp)
2287− onCancelQueue()
2288− }
2289− .padding(vertical = 4.dp),
2290− ) {
2291− Text(
2292− stringResource(R.string.queued),
2293− style = MaterialTheme.typography.labelSmall,
2294− color = MaterialTheme.colorScheme.onSurfaceVariant,
2295− )
2296− Text(
2297− queuedFollowUp,
2298− style = MaterialTheme.typography.bodySmall,
2299− color = MaterialTheme.colorScheme.onSurfaceVariant,
2300− maxLines = 1,
2301− overflow = TextOverflow.Ellipsis,
2302− )
2303− }
2304− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2305− Text(stringResource(R.string.cancel))
2306− }
2307− }
2308− }
2309− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2310− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2311− // Slash-command autocomplete: extracted to a helper to keep this function's
2312− // complexity under the detekt threshold. Returns no-op when the draft doesn't
2313− // start with "/" or the command catalog is empty.
2314− SlashCommandAutocomplete(
2315− value = value,
2316− commands = commands,
2317− running = running,
2318− onRunCommand = onRunCommand,
2319− )
2320− Row(
2321− modifier = Modifier.fillMaxWidth().padding(8.dp),
2322− verticalAlignment = Alignment.Bottom,
2323− ) {
2324− // Attach menu: photo picker, camera, or any file.
2325− var showAttachMenu by remember { mutableStateOf(false) }
2326− Box {
2327− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2328− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2329− }
2330− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2331− DropdownMenuItem(
2332− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2333− text = { Text(stringResource(R.string.attach_photo)) },
2334− onClick = { showAttachMenu = false; onPickPhoto() },
2335− )
2336− DropdownMenuItem(
2337− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2338− text = { Text(stringResource(R.string.attach_camera)) },
2339− onClick = { showAttachMenu = false; onCamera() },
2340− )
2341− DropdownMenuItem(
2342− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2343− text = { Text(stringResource(R.string.attach_file)) },
2344− onClick = { showAttachMenu = false; onPickFile() },
2345− )
2346− }
2347− }
2348− // Voice dictation: appends recognized speech to the draft. Hidden (not just
2349− // disabled) when the device has no speech-recognition activity, so a user
2350− // without a voice app doesn't get a button that only fails noisily on tap.
2351− val voiceAvailable = remember {
2352− val pm = context.packageManager
2353− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2354− pm.queryIntentActivities(intent, 0).isNotEmpty()
2355− }
2356− if (voiceAvailable) {
2357− IconButton(onClick = onVoice, enabled = enabled) {
2358− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2359− }
2360− }
2361− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2362− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2363− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2364− }
2365− OutlinedTextField(
2366− value = value,
2367− onValueChange = { v ->
2368− // Cap input length so a huge paste can't stall the UI. Shares are
2369− // capped separately in MainActivity; this guards typed/pasted drafts.
2370− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2371− },
2372− modifier = Modifier
2373− .weight(1f)
2374− .focusRequester(focusRequester)
2375− .testTag("chat_input")
2376− // Intercept image content pasted/dropped into the field (keyboard paste
2377− // of a copied screenshot, drag from Files, etc.) and route it through the
2378− // same staging path as the attach menu. Non-image content (text) falls
2379− // through unchanged so normal typing/paste works.
2380− .contentReceiver(
2381− remember {
2382− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2383− val clipData = transferable.clipEntry?.clipData
2384− if (clipData != null) {
2385− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2386− val item = clipData.getItemAt(i)
2387− item.uri?.takeIf { uri ->
2388− item.text == null && uri.toString().let { s ->
2389− s.startsWith("content:") || s.startsWith("file:")
2390− }
2391− }
2392− }
2393− if (imageUris.isNotEmpty()) {
2394− onPasteImage(imageUris)
2395− }
2396− }
2397− transferable
2398− }
2399− },
2400− )
2401− .onPreviewKeyEvent { event ->
2402− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2403− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2404− // With it off, Enter inserts a newline and Ctrl+Enter sends.
2405− val send = enterShouldSend(
2406− enabled = enabled,
2407− hasContent = hasContent,
2408− sendOnEnter = sendOnEnter,
2409− shift = event.isShiftPressed,
2410− ctrl = event.isCtrlPressed,
2411− )
2412− if (send) {
2413− if (running) onQueueFollowUp(value) else onSend()
2414− true
2415− } else {
2416− false
2417− }
2418− },
2419− // While a run is active a typed message only queues (sends after the run), so
2420− // the placeholder says so instead of the plain "Message…".
2421− placeholder = {
2422− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2423− },
2424− enabled = enabled,
2425− maxLines = 6,
2426− // Show a "N / max" countdown once the draft crosses a high fraction of
2427− // the cap, so the user knows a paste is about to be truncated instead
2428− // of being silently cut off. Hidden for normal short prompts to avoid
2429− // clutter under a typical one-line message.
2430− supportingText = {
2431− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2432− if (value.length >= threshold) {
2433− Text(
2434− stringResource(
2435− R.string.draft_chars_remaining,
2436− NetworkConfig.maxDraftLengthChars - value.length,
2437− NetworkConfig.maxDraftLengthChars,
2438− ),
2439− style = MaterialTheme.typography.labelSmall,
2440− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2441− else MaterialTheme.colorScheme.onSurfaceVariant,
2442− )
2443− } else if (value.lines().size > 6) {
2444− // The inline field caps at 6 lines; once the draft crosses that,
2445− // hint that a bigger full-screen editor exists (the Expand icon
2446− // above is easy to miss among the icon row). A tappable label
2447− // would be ideal, but a plain hint is enough to draw attention.
2448− Text(
2449− stringResource(R.string.open_full_editor_hint),
2450− style = MaterialTheme.typography.labelSmall,
2451− color = MaterialTheme.colorScheme.onSurfaceVariant,
2452− )
2453− }
2454− },
2455− keyboardOptions = KeyboardOptions(
2456− // When "Send on Enter" is on, expose ImeAction.Send so the soft
2457− // keyboard shows a send key — matching the setting's intent and
2458− // giving touch-only users a keyboard send affordance. When off,
2459− // ImeAction.Default keeps the enter/newline key for multi-line input.
2460− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2461− capitalization = KeyboardCapitalization.Sentences,
2462− ),
2463− keyboardActions = KeyboardActions(
2464− onSend = {
2465− if (enabled && hasContent) onSend()
2466− },
2467− ),
2468− )
2469− ComposerTrailingButton(
2470− running = running,
2471− aborting = aborting,
2472− canSend = enabled && hasContent,
2473− canQueue = enabled && value.isNotBlank(),
2474− onSend = onSend,
2475− onAbort = onAbort,
2476− onQueue = { onQueueFollowUp(value) },
2477− )
2478− }
2479− }
2480− if (showFullScreenEditor) {
2481− FullScreenEditor(
2482− value = value,
2483− onValueChange = onValueChange,
2484− onDismiss = { showFullScreenEditor = false },
2485− onSend = {
2486− showFullScreenEditor = false
2487− // Mirror the inline composer's behavior: while a run is active a send
2488− // can't go immediately, so queue the follow-up instead of silently
2489− // dropping it (vm.send() returns false during a run, which previously
2490− // lost the typed message with no feedback).
2491− if (running) onQueueFollowUp(value) else onSend()
2492− },
2493− canSend = enabled && hasContent,
2494− running = running,
2495− sendOnEnter = sendOnEnter,
2496− attachments = attachments,
2497− onRemoveAttachment = onRemoveAttachment,
2498− staging = staging,
2499− stagingFileCount = stagingFileCount,
2500− )
2501− }
2502− }
2503−}
2504−
2505−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2506− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2507−@OptIn(ExperimentalMaterial3Api::class)
2508−@Composable
2509−private fun FullScreenEditor(
2510− value: String,
2511− onValueChange: (String) -> Unit,
2512− onDismiss: () -> Unit,
2513− onSend: () -> Unit,
2514− canSend: Boolean,
2515− running: Boolean = false,
2516− sendOnEnter: Boolean = false,
2517− attachments: List<PendingAttachment> = emptyList(),
2518− onRemoveAttachment: (String) -> Unit = {},
2519− staging: Boolean = false,
2520− stagingFileCount: Int = 0,
2521−) {
2522− androidx.compose.ui.window.Dialog(
2523− onDismissRequest = onDismiss,
2524− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2525− ) {
2526− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2527− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2528− // gives the available width so we can center a capped-width column.
2529− androidx.compose.foundation.layout.BoxWithConstraints(
2530− modifier = Modifier.fillMaxSize(),
2531− contentAlignment = Alignment.Center,
2532− ) {
2533− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2534− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2535− else 0.dp
2536− Scaffold(
2537− modifier = Modifier.padding(horizontal = hPad),
2538− topBar = {
2539− androidx.compose.material3.TopAppBar(
2540− title = { Text(stringResource(R.string.compose_editor_title)) },
2541− navigationIcon = {
2542− androidx.compose.material3.TextButton(onClick = onDismiss) {
2543− Text(stringResource(R.string.collapse_editor))
2544− }
2545− },
2546− )
2547− },
2548− bottomBar = {
2549− Surface(tonalElevation = 3.dp) {
2550− Row(
2551− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2552− horizontalArrangement = Arrangement.End,
2553− ) {
2554− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2555− Text(stringResource(if (running) R.string.queue else R.string.send))
2556− }
2557− }
2558− }
2559− },
2560− ) { padding ->
2561− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2562− // Show staged attachments in the full-screen editor too, so a user who staged
2563− // images then expanded for a long prompt can still see and remove them without
2564− // collapsing first (mirrors the inline composer's AttachmentStrip).
2565− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2566− OutlinedTextField(
2567− value = value,
2568− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2569− modifier = Modifier
2570− .fillMaxSize()
2571− .weight(1f)
2572− // Honor the "Send on Enter" setting here too, so the full-screen
2573− // editor matches the inline composer: Enter sends (Shift+Enter
2574− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2575− // when off. Previously this hard-coded ImeAction.Default and had no
2576− // key handler, so a hardware-keyboard user got a different behaviour
2577− // from the inline composer depending on which they happened to open.
2578− .onPreviewKeyEvent { event ->
2579− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2580− val send = enterShouldSend(
2581− enabled = canSend,
2582− hasContent = canSend,
2583− sendOnEnter = sendOnEnter,
2584− shift = event.isShiftPressed,
2585− ctrl = event.isCtrlPressed,
2586− )
2587− if (send) { onSend(); true } else false
2588− },
2589− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2590− maxLines = Int.MAX_VALUE,
2591− keyboardOptions = KeyboardOptions(
2592− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2593− capitalization = KeyboardCapitalization.Sentences,
2594− ),
2595− keyboardActions = KeyboardActions(
2596− onSend = { if (canSend) onSend() },
2597− ),
2598− )
2599− }
2600− }
2601− }
2602− }
2603−}
2604−
2605−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2606− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2607−private fun enterShouldSend(
2608− enabled: Boolean,
2609− hasContent: Boolean,
2610− sendOnEnter: Boolean,
2611− shift: Boolean,
2612− ctrl: Boolean,
2613−): Boolean = when {
2614− !enabled || !hasContent -> false
2615− sendOnEnter -> !shift
2616− else -> ctrl
2617−}
2618−
2619−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2620− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2621− * [ChatInputBar] stays under the complexity threshold. */
2622−@Composable
2623−private fun ComposerTrailingButton(
2624− running: Boolean,
2625− aborting: Boolean,
2626− canSend: Boolean,
2627− canQueue: Boolean,
2628− onSend: () -> Unit,
2629− onAbort: () -> Unit,
2630− onQueue: () -> Unit,
2631−) {
2632− if (running) {
2633− Row(verticalAlignment = Alignment.CenterVertically) {
2634− // While a run is active the trailing action is Stop, so the only send affordance is
2635− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2636− // That leaves a touch-only user with the setting off no way to queue a follow-up
2637− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2638− // there's typed TEXT so queuing is always reachable, without changing the user's
2639− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2640− // canSend, which is also true for an attachment-only composer — because queuing "" just
2641− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2642− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2643− if (canQueue) {
2644− IconButton(
2645− onClick = onQueue,
2646− modifier = Modifier.testTag("queue_button"),
2647− ) {
2648− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2649− // icon (which can be read as "snooze" or "later"), and isn't confused with
2650− // the Send action sitting right beside the Stop button.
2651− Icon(
2652− Icons.AutoMirrored.Filled.PlaylistAdd,
2653− contentDescription = stringResource(R.string.queue_followup),
2654− )
2655− }
2656− }
2657− // Show a spinner while the abort REST call is in flight so the user sees the stop
2658− // was sent, and disable to prevent a double-tap.
2659− IconButton(
2660− onClick = onAbort,
2661− enabled = !aborting,
2662− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2663− ) {
2664− if (aborting) {
2665− val stopLabel = stringResource(R.string.stop)
2666− CircularProgressIndicator(
2667− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2668− strokeWidth = 2.dp,
2669− )
2670− } else {
2671− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2672− }
2673− }
2674− }
2675− } else {
2676− IconButton(
2677− onClick = onSend,
2678− enabled = canSend,
2679− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2680− ) {
2681− // Tint the send icon with primary when there's content to send so the commit action
2682− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2683− Icon(
2684− Icons.AutoMirrored.Filled.Send,
2685− contentDescription = stringResource(R.string.send),
2686− tint = if (canSend) MaterialTheme.colorScheme.primary
2687− else MaterialTheme.colorScheme.onSurfaceVariant,
2688− )
2689− }
2690− }
2691−}
2692−
2693−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2694−@Composable
2695−private fun EmptyConversation(
2696− onSuggestion: (String) -> Unit,
2697− modifier: Modifier = Modifier,
2698−) {
2699− // A few example prompts so a first-time user has a one-tap path to their first
2700− // message instead of staring at a blank input. Tapping a chip fills the draft
2701− // (without sending) so the user can edit it before sending.
2702− val suggestions = remember {
2703− listOf(
2704− R.string.empty_chat_suggest_1,
2705− R.string.empty_chat_suggest_2,
2706− R.string.empty_chat_suggest_3,
2707− )
2708− }
2709− Column(
2710− modifier = modifier.padding(32.dp),
2711− horizontalAlignment = Alignment.CenterHorizontally,
2712− ) {
2713− Icon(
2714− Icons.Filled.AutoAwesome,
2715− contentDescription = null,
2716− modifier = Modifier.size(48.dp),
2717− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2718− )
2719− Spacer(Modifier.size(16.dp))
2720− Text(
2721− stringResource(R.string.empty_chat_title),
2722− style = MaterialTheme.typography.titleMedium,
2723− )
2724− Spacer(Modifier.size(8.dp))
2725− Text(
2726− stringResource(R.string.empty_chat_hint),
2727− style = MaterialTheme.typography.bodyMedium,
2728− color = MaterialTheme.colorScheme.onSurfaceVariant,
2729− )
2730− Spacer(Modifier.size(20.dp))
2731− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2732− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2733− FlowRow(
2734− modifier = Modifier.fillMaxWidth(),
2735− horizontalArrangement = Arrangement.spacedBy(8.dp),
2736− verticalArrangement = Arrangement.spacedBy(8.dp),
2737− ) {
2738− suggestions.forEach { resId ->
2739− val text = stringResource(resId)
2740− androidx.compose.material3.AssistChip(
2741− onClick = { onSuggestion(text) },
2742− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2743− )
2744− }
2745− }
2746− }
2747−}
2748−
2749−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2750− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2751− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2752−@Composable
2753−private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2754− val haptics = LocalHapticFeedback.current
2755− var showDiff by rememberSaveable { mutableStateOf(false) }
2756− val expandMotion = rememberVisibilityTransitions()
2757− Surface(
2758− color = MaterialTheme.colorScheme.tertiaryContainer,
2759− tonalElevation = 2.dp,
2760− modifier = Modifier.fillMaxWidth(),
2761− ) {
2762− Column {
2763− Row(
2764− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2765− verticalAlignment = Alignment.CenterVertically,
2766− horizontalArrangement = Arrangement.SpaceBetween,
2767− ) {
2768− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2769− Icon(
2770− if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2771− contentDescription = null,
2772− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2773− modifier = Modifier.size(18.dp),
2774− )
2775− Text(
2776− stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2777− style = MaterialTheme.typography.bodySmall,
2778− color = MaterialTheme.colorScheme.onTertiaryContainer,
2779− modifier = Modifier.padding(start = 8.dp),
2780− )
2781− // "Show what changed" toggle, shown only when the server provided a diff.
2782− // Collapsible so the banner stays compact by default; a user curious about
2783− // what the revert rolled back can expand it inline without leaving the chat.
2784− if (!diff.isNullOrBlank()) {
2785− TextButton(
2786− onClick = {
2787− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2788− showDiff = !showDiff
2789− },
2790− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2791− ) {
2792− Icon(
2793− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2794− contentDescription = null,
2795− modifier = Modifier.size(16.dp),
2796− )
2797− Text(
2798− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2799− style = MaterialTheme.typography.labelSmall,
2800− modifier = Modifier.padding(start = 4.dp),
2801− )
2802− }
2803− }
2804− }
2805− TextButton(onClick = {
2806− // Haptic on undo to match the other destructive/important confirmations: a
2807− // revert restores potentially hundreds of hidden messages.
2808− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2809− onUndo()
2810− }) { Text(stringResource(R.string.undo)) }
2811− }
2812− // The diff render lives inside the banner's Surface so it inherits the tertiary
2813− // tonal container and reads as part of the banner, not a floating panel.
2814− if (!diff.isNullOrBlank()) {
2815− AnimatedVisibility(
2816− visible = showDiff,
2817− enter = expandMotion.enter,
2818− exit = expandMotion.exit,
2819− ) {
2820− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2821− Text(
2822− stringResource(R.string.revert_diff_header),
2823− style = MaterialTheme.typography.labelSmall,
2824− color = MaterialTheme.colorScheme.onTertiaryContainer,
2825− modifier = Modifier.padding(bottom = 4.dp),
2826− )
2827− DiffView(diff, saveKey = "revertDiff")
2828− }
2829− }
2830− }
2831− }
2832− }
2833−}
2834−
2835−/** A dismissible preview card shown above the composer when the user quote-replied to a
2836− * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2837− * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2838− * the Discord/Slack quote-preview pattern. */
2839−@Composable
2840−private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2841− val haptics = LocalHapticFeedback.current
2842− Surface(
2843− color = MaterialTheme.colorScheme.secondaryContainer,
2844− tonalElevation = 2.dp,
2845− modifier = Modifier.fillMaxWidth(),
2846− ) {
2847− Row(
2848− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2849− verticalAlignment = Alignment.Top,
2850− ) {
2851− Icon(
2852− Icons.Filled.FormatQuote,
2853− contentDescription = null,
2854− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2855− modifier = Modifier.size(18.dp).padding(top = 2.dp),
2856− )
2857− Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
2858− Text(
2859− stringResource(R.string.quote_reply_banner),
2860− style = MaterialTheme.typography.labelSmall,
2861− color = MaterialTheme.colorScheme.onSecondaryContainer,
2862− )
2863− Text(
2864− quotedText,
2865− style = MaterialTheme.typography.bodySmall,
2866− color = MaterialTheme.colorScheme.onSecondaryContainer,
2867− maxLines = 2,
2868− overflow = TextOverflow.Ellipsis,
2869− )
2870− }
2871− IconButton(onClick = {
2872− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2873− onCancel()
2874− }) {
2875− Icon(
2876− Icons.Filled.Close,
2877− contentDescription = stringResource(R.string.cancel_quote_reply),
2878− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2879− modifier = Modifier.size(18.dp),
2880− )
2881− }
2882− }
2883− }
2884−}
2885−
2886−/** A banner shown while messages composed offline are queued in the outbox, with a
2887− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2888−@Composable
2889−private fun OutboxBanner(
2890− count: Int,
2891− sending: Boolean,
2892− onFlush: () -> Unit,
2893− onDiscard: () -> Unit,
2894−) {
2895− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
2896− Surface(
2897− color = MaterialTheme.colorScheme.secondaryContainer,
2898− tonalElevation = 2.dp,
2899− modifier = Modifier.fillMaxWidth(),
2900− ) {
2901− Row(
2902− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2903− verticalAlignment = Alignment.CenterVertically,
2904− horizontalArrangement = Arrangement.SpaceBetween,
2905− ) {
2906− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2907− if (sending) {
2908− CircularProgressIndicator(
2909− Modifier.size(16.dp),
2910− strokeWidth = 2.dp,
2911− color = MaterialTheme.colorScheme.onSecondaryContainer,
2912− )
2913− Spacer(Modifier.size(8.dp))
2914− }
2915− Text(
2916− if (sending) {
2917− stringResource(R.string.outbox_sending)
2918− } else {
2919− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2920− stringResource(res, count)
2921− },
2922− style = MaterialTheme.typography.bodySmall,
2923− color = MaterialTheme.colorScheme.onSecondaryContainer,
2924− )
2925− }
2926− if (!sending) {
2927− val haptics = LocalHapticFeedback.current
2928− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2929− TextButton(onClick = {
2930− // Confirm before discarding all queued messages (irreversible), matching
2931− // the confirmation pattern used by deleteSession and other destructive
2932− // actions. Previously a single tap dropped every queued message.
2933− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2934− showDiscardConfirm = true
2935− }) {
2936− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2937− }
2938− }
2939− }
2940− }
2941− if (showDiscardConfirm) {
2942− androidx.compose.material3.AlertDialog(
2943− onDismissRequest = { showDiscardConfirm = false },
2944− title = { Text(stringResource(R.string.discard_queued_title)) },
2945− text = { Text(stringResource(R.string.discard_queued_text, count)) },
2946− confirmButton = {
2947− androidx.compose.material3.TextButton(onClick = {
2948− showDiscardConfirm = false
2949− onDiscard()
2950− }) { Text(stringResource(R.string.discard)) }
2951− },
2952− dismissButton = {
2953− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
2954− Text(stringResource(R.string.cancel))
2955− }
2956− },
2957− )
2958− }
2959−}
2960−
2961−/** Prompt for a one-off shell command to run in the session's worktree. */
2962−@Composable
2963−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
2964− var command by rememberSaveable { mutableStateOf("") }
2965− AlertDialog(
2966− onDismissRequest = onDismiss,
2967− title = { Text(stringResource(R.string.run_shell_command)) },
2968− text = {
2969− OutlinedTextField(
2970− value = command,
2971− onValueChange = { command = it },
2972− modifier = Modifier.fillMaxWidth(),
2973− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
2974− label = { Text(stringResource(R.string.shell_command_label)) },
2975− singleLine = true,
2976− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2977− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
2978− )
2979− },
2980− confirmButton = {
2981− TextButton(
2982− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
2983− enabled = command.isNotBlank(),
2984− ) { Text(stringResource(R.string.run)) }
2985− },
2986− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
2987− )
2988−}
2989−
2990−/**
2991− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
2992− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
2993− * equality is structural so `snapshotFlow` emits only when something relevant changes.
2994− */
2995−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
2996−
2997−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
2998− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
2999− * streaming, not just plain assistant text. O(1). */
3000−private fun streamingContentLength(part: Part?): Int = when (part) {
3001− is TextPart -> part.text.length
3002− is ReasoningPart -> part.text.length
3003− is ToolPart -> when (val st = part.state) {
3004− is ToolCompleted -> st.output?.length ?: 0
3005− is ToolError -> st.error?.length ?: 0
3006− is ToolRunning -> st.title?.length ?: 0
3007− else -> 0
3008− }
3009− else -> 0
3010−}
3011−
3012−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3013− * dialog but lives in the chat screen so the user can rename without backing out to
3014− * the list. Pre-filled with the current title; the cap matches the list dialog. */
3015−@Composable
3016−private fun RenameSessionChatDialog(
3017− initialTitle: String,
3018− onDismiss: () -> Unit,
3019− onConfirm: (String) -> Unit,
3020−) {
3021− // Seed the field once (no key input) so a later external title change — e.g. opencode
3022− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3023− // doesn't re-initialize the box and discard the user's in-progress edit.
3024− var title by rememberSaveable { mutableStateOf(initialTitle) }
3025− AlertDialog(
3026− onDismissRequest = onDismiss,
3027− title = { Text(stringResource(R.string.rename_session_chat)) },
3028− text = {
3029− OutlinedTextField(
3030− value = title,
3031− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3032− modifier = Modifier.fillMaxWidth(),
3033− placeholder = { Text(stringResource(R.string.session_title_hint)) },
3034− label = { Text(stringResource(R.string.rename_session_chat)) },
3035− singleLine = true,
3036− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3037− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3038− )
3039− },
3040− confirmButton = {
3041− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3042− Text(stringResource(R.string.save))
3043− }
3044− },
3045− dismissButton = {
3046− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3047− },
3048− )
3049−}
3050−
3051−/**
3052− * A single item in the chat message list — either a [Message] bubble or a day
3053− * [Separator] inserted before the first message of a new day. The separator shifts
3054− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3055− * the [List] of these items (not `messages.size`/`lastIndex`).
3056− */
3057−private sealed interface MessageListItem {
3058− val key: Any
3059− val contentType: Any
3060−
3061− data class Message(
3062− val message: MessageWithParts,
3063− override val key: Any,
3064− // Whether this is the first message in a consecutive run of the same speaker (role).
3065− // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3066− // reducing visual noise in tool-heavy conversations where many assistant messages
3067− // appear back-to-back. A separator or a role change resets the flag.
3068− val isFirstOfSpeaker: Boolean,
3069− ) : MessageListItem {
3070− override val contentType: Any get() = message.info::class
3071− }
3072−
3073− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3074− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3075− // can share a label (e.g. an untimestamped message — empty label — between two
3076− // same-day messages, or two untimestamped groups), and a label-only key would
3077− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3078− // stable for a given message ordering so slots aren't needlessly recreated.
3079− override val key: Any get() = "sep_${ordinal}_$label"
3080− // Separators share a contentType so the LazyColumn can recycle their slots.
3081− override val contentType: Any get() = "separator"
3082− }
3083−}
3084−
3085−/**
3086− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3087− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3088− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3089− * Messages with no timestamp are grouped under an empty-label separator only if they
3090− * start the list, so a server that omits timestamps doesn't suppress the first divider.
3091− *
3092− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3093− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3094− * labels; older days fall back to a locale-stable medium-date format.
3095− */
3096−private fun buildMessageListItems(
3097− messages: List<MessageWithParts>,
3098− todayLabel: String,
3099− yesterdayLabel: String,
3100−): List<MessageListItem> {
3101− if (messages.isEmpty()) return emptyList()
3102− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3103− val dateFmt = mediumDateFormat()
3104− val result = ArrayList<MessageListItem>(messages.size + 4)
3105− val seenKeys = HashSet<String>(messages.size * 2)
3106− var lastDayKey: String? = null
3107− var sepOrdinal = 0
3108− var emptyIdOrdinal = 0
3109− var first = true
3110− // Track the previous message's role to detect consecutive same-speaker runs, so the
3111− // avatar/header can be suppressed on follow-up messages in the same run. A null means
3112− // "no previous message or a separator just interrupted the run", both of which make the
3113− // next message the first of its group.
3114− var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3115− for (message in messages) {
3116− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3117− val dayKey = ts?.let { dayKey(it) } ?: ""
3118− // Emit a separator before the very first message (so a leading un-timestamped message
3119− // still gets the first divider, empty label and all), and thereafter only when crossing
3120− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3121− // neither emits its own separator nor resets the day — otherwise a following same-day
3122− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3123− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3124− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3125− // A date separator visually breaks a speaker run, so the next message is treated
3126− // as the first of its group (even if the same role continues across the day break).
3127− prevRoleClass = null
3128− }
3129− if (dayKey.isNotEmpty()) lastDayKey = dayKey
3130− first = false
3131− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3132− // empty id — and the reducer intentionally keeps several such messages as distinct
3133− // holders — so give each a stable synthetic key and defensively de-collide any remaining
3134− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3135− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3136− if (!seenKeys.add(key)) {
3137− var suffix = 1
3138− while (!seenKeys.add("$key#$suffix")) suffix++
3139− key = "$key#$suffix"
3140− }
3141− val roleClass = message.info::class
3142− val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3143− result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3144− prevRoleClass = roleClass
3145− }
3146− return result
3147−}
3148−
3149−/**
3150− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3151− *
3152− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3153− * whole `messages` list, which must stay so the live message's fresh parts render), so a
3154− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3155− * every message on every token. Message timestamps are immutable once assigned, so we
3156− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3157− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
3158− * thread during composition, so the coarse lock is uncontended.
3159− */
3160−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
3161− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
3162−}
3163−
3164−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
3165− dayKeyCache.getOrPut(epochMillis) {
3166− java.time.Instant.ofEpochMilli(epochMillis)
3167− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3168− }
3169−}
3170−
3171−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3172−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3173−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3174−private var cachedDateFmt: java.text.DateFormat? = null
3175−private var cachedDateFmtLocale: java.util.Locale? = null
3176−
3177−private fun mediumDateFormat(): java.text.DateFormat {
3178− val locale = java.util.Locale.getDefault()
3179− val existing = cachedDateFmt
3180− if (existing != null && cachedDateFmtLocale == locale) return existing
3181− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3182− cachedDateFmt = it
3183− cachedDateFmtLocale = locale
3184− }
3185−}
3186−
3187−/**
3188− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3189− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3190− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3191− * messages.
3192− */
3193−private fun dayLabel(
3194− dayKey: String,
3195− ts: Long,
3196− today: java.time.LocalDate,
3197− todayLabel: String,
3198− yesterdayLabel: String,
3199− dateFmt: java.text.DateFormat,
3200−): String {
3201− if (dayKey.isEmpty()) return ""
3202− val epochDay = dayKey.toLongOrNull() ?: return ""
3203− val date = java.time.LocalDate.ofEpochDay(epochDay)
3204− return when {
3205− date == today -> todayLabel
3206− date == today.minusDays(1) -> yesterdayLabel
3207− else -> dateFmt.format(java.util.Date(ts))
3208− }
3209−}
3210−
3211−/**
3212− * A centered day divider in the message list. Renders nothing for an empty label
3213− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3214− */
3215−@Composable
3216−private fun DateSeparator(label: String) {
3217− if (label.isBlank()) return
3218− Row(
3219− modifier = Modifier.fillMaxWidth(),
3220− horizontalArrangement = Arrangement.Center,
3221− ) {
3222− Surface(
3223− color = MaterialTheme.colorScheme.surfaceVariant,
3224− shape = MaterialTheme.shapes.small,
3225− // Marked as a heading so TalkBack users can navigate day-by-day with the
3226− // heading-skip gesture — the canonical affordance for date dividers in a list.
3227− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3228− ) {
3229− Text(
3230− label,
3231− style = MaterialTheme.typography.labelSmall,
3232− color = MaterialTheme.colorScheme.onSurfaceVariant,
3233− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3234− )
3235− }
3236− }
3237−}
3238−
3239−/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3240− * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3241− * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3242− * [BoxScope] extension so it can align itself to the top center of its host box. */
3243−@Composable
3244−private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3245− val loadingLabel = stringResource(R.string.loading)
3246− val reducedMotion = LocalReducedMotion.current
3247− val transition = rememberInfiniteTransition(label = "skeleton")
3248− val pulse by transition.animateFloat(
3249− initialValue = 0.35f,
3250− targetValue = 0.7f,
3251− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3252− label = "skeletonAlpha",
3253− )
3254− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3255− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3256− @Composable
3257− fun bar(widthFraction: Float) {
3258− Box(
3259− Modifier
3260− .fillMaxWidth(widthFraction)
3261− .height(14.dp)
3262− .clip(RoundedCornerShape(4.dp))
3263− .background(skeletonColor)
3264− .alpha(skeletonAlpha),
3265− )
3266− }
3267− Column(
3268− modifier = Modifier
3269− .align(Alignment.TopCenter)
3270− .padding(top = topPad)
3271− .padding(16.dp)
3272− .fillMaxWidth()
3273− .semantics { contentDescription = loadingLabel },
3274− verticalArrangement = Arrangement.spacedBy(14.dp),
3275− ) {
3276− repeat(4) { i ->
3277− val left = i % 2 == 0
3278− Row(
3279− modifier = Modifier.fillMaxWidth(),
3280− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3281− ) {
3282− Column(
3283− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3284− verticalArrangement = Arrangement.spacedBy(6.dp),
3285− ) {
3286− bar(1f)
3287− bar(0.8f)
3288− }
3289− }
3290− }
3291− }
3292−}
app/src/main/java/soy/iko/opencode/ui/chat/ChatViewModel.ktdeleted−1812

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/CommandPickerSheet.ktdeleted−248

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/ConversationExport.ktdeleted−236

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/CostFormat.ktdeleted−60

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/chat/MessageBubble.ktdeleted−1418

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

app/src/main/java/soy/iko/opencode/ui/components/QrCode.ktdeleted−175

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

build.gradle.kts+2−1

This diff is too big to show here.

config/detekt/detekt.ymldeleted−68

This diff is too big to show here.

flake.lock+3−3

This diff is too big to show here.

flake.nix+29−19

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

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

This diff is too big to show here.

gradle.properties+5−2

This diff is too big to show here.

gradle/libs.versions.toml+29−60

This diff is too big to show here.

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

This diff is too big to show here.

renovate.jsondeleted−32

This diff is too big to show here.

scripts/run-device.shdeleted−106

This diff is too big to show here.

scripts/run.shdeleted−95

This diff is too big to show here.

settings.gradle.kts+3

This diff is too big to show here.

shared/Cargo.locknew file+1358

This diff is too big to show here.

shared/Cargo.tomlnew file+31

This diff is too big to show here.

shared/src/app.rsnew file+1051

This diff is too big to show here.

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

This diff is too big to show here.

shared/src/lib.rsnew file+17

This diff is too big to show here.

shared/src/protocol.rsnew file+248

This diff is too big to show here.