Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ is the server-managed conversation for the current project.
### Message Repository

The mobile integration layer that reads and sends **messages** for a session
(list, get one, sync send, and asynchronous prompt send).
(list, get one, sync send, and asynchronous prompt send). Its read boundary also
exposes the observed raw and display-message timelines backed by
`MessageSync`, `InMemoryMessageStore`, and `DisplayMessagePipeline`.

Distinct from a **message**: the repository is app infrastructure; a message is
a single item in a session timeline.
Expand Down Expand Up @@ -189,12 +191,14 @@ Attachment.
A reactive observation layer above CRUD repositories that keeps screen data fresh
while the **foreground event stream** is active.

A Live Store listens for relevant server-sent events, applies debounced REST
refresh policy, and exposes ongoing updates through platform streams (for
example Kotlin `Flow` or Swift `AsyncStream`). Screen Models collect Live Store
streams for timelines, session lists, and status labels. Mutations such as
send, create, and delete still go through repositories directly. Optimistic send
and quiet refresh merge stay in the Screen Model.
A Live Store listens for relevant server-sent events, applies refresh policy,
and exposes ongoing updates through platform streams (for example Kotlin `Flow`
or Swift `AsyncStream`). Screen Models collect Live Store streams for session
lists, status labels, permissions, and questions. The message timeline uses the
equivalent synchronization boundary behind **Message Repository** rather than a
type named `MessageLiveStore`. Mutations such as send, create, and delete still
go through repositories directly. Optimistic send and quiet refresh merge stay
in the Screen Model.

### message

Expand Down
3 changes: 3 additions & 0 deletions android/app/src/main/java/dev/opencode/mobile/Navigation.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import dev.opencode.mobile.ui.componentgallery.components.MessageListGalleryDeta
import dev.opencode.mobile.ui.componentgallery.components.OutgoingMessageGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.OverflowMenuGalleryScreen
import dev.opencode.mobile.domain.preferences.HomeDisplayPreferences
import dev.opencode.mobile.domain.preferences.MarkdownHighlightPreferences
import dev.opencode.mobile.ui.componentgallery.components.ProjectSessionSelectorGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.SessionListDockGalleryScreen
import dev.opencode.mobile.ui.componentgallery.components.SessionListGalleryScreen
Expand Down Expand Up @@ -149,6 +150,8 @@ fun MainNavigation() {
showSessionListOnHome = HomeDisplayPreferences.showSessionListOnHome,
onShowSessionListOnHomeChange =
settingsViewModel::setShowSessionListOnHome,
textMateEnabled = MarkdownHighlightPreferences.textMateEnabled,
onTextMateEnabledChange = settingsViewModel::setTextMateEnabled,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package dev.opencode.mobile
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import dev.opencode.mobile.domain.preferences.HomeDisplayPreferences
import dev.opencode.mobile.domain.preferences.MarkdownHighlightPreferences
import dev.opencode.mobile.markdown.OpenCodeAndroidMarkdownAssets
import dev.opencode.mobile.theme.ThemeManager

Expand All @@ -12,6 +13,7 @@ class OpenCodeMobileApplication : Application() {
super.onCreate()
ThemeManager.initialize(this)
HomeDisplayPreferences.initialize(this)
MarkdownHighlightPreferences.initialize(this)
OpenCodeAndroidMarkdownAssets.init(this)
OpenCodeReleaseObservability.initialize(this)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,34 +22,22 @@ class EventsApi(
.prepareGet("global/event") {
accept(ContentType.Text.EventStream)
header(HttpHeaders.CacheControl, "no-cache")
// Match iOS: keep SSE uncompressed so framing stays line-oriented under burst.
header(HttpHeaders.AcceptEncoding, "identity")
}.execute { response ->
onHTTPResponse(response.status.value)
val channel = response.bodyAsChannel()
val dataBuffer = StringBuilder()
val parser = SseDataLineParser()
try {
while (!channel.isClosedForRead) {
val line = channel.readUTF8Line() ?: break
when {
line.isEmpty() -> {
if (dataBuffer.isNotEmpty()) {
onDataLine(dataBuffer.toString())
dataBuffer.clear()
}
}
line.startsWith("data:") -> {
val payload = line.removePrefix("data:").trimStart()
if (dataBuffer.isNotEmpty()) dataBuffer.append('\n')
dataBuffer.append(payload)
}
line.startsWith("{") -> {
if (dataBuffer.isNotEmpty()) {
onDataLine(dataBuffer.toString())
dataBuffer.clear()
}
onDataLine(line)
}
for (payload in parser.ingest(line)) {
onDataLine(payload)
}
}
for (payload in parser.finish()) {
onDataLine(payload)
}
} catch (error: CancellationException) {
throw error
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package dev.opencode.mobile.data.remote

import kotlinx.serialization.json.Json

/**
* SSE `data:` line parser matching iOS [SSEDataLineParser]: flush each complete JSON
* payload without waiting for a blank event separator.
*/
internal class SseDataLineParser {
private val dataBuffer = StringBuilder()

fun ingest(line: String): List<String> {
val trimmed = line.trim()
if (trimmed.isEmpty()) {
return finish()
}
if (trimmed.startsWith(":")) {
return emptyList()
}
if (trimmed.startsWith("data:")) {
val payload = trimmed.removePrefix("data:").trimStart()
if (dataBuffer.isNotEmpty()) {
dataBuffer.append('\n')
}
dataBuffer.append(payload)
return if (isCompleteJsonPayload(dataBuffer.toString())) finish() else emptyList()
}
if (trimmed.startsWith("{")) {
val payloads = finish().toMutableList()
payloads.add(trimmed)
return payloads
}
return emptyList()
}

fun finish(): List<String> {
if (dataBuffer.isEmpty()) return emptyList()
val payload = dataBuffer.toString()
dataBuffer.clear()
return listOf(payload)
}

private fun isCompleteJsonPayload(payload: String): Boolean =
runCatching { Json.parseToJsonElement(payload) }.isSuccess
}
14 changes: 12 additions & 2 deletions android/app/src/main/java/dev/opencode/mobile/di/MessageModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import dev.opencode.mobile.domain.message.MessageContentPreparer
import dev.opencode.mobile.domain.message.MessageDomainAdapter
import dev.opencode.mobile.domain.message.MessageRepository
import dev.opencode.mobile.domain.message.MessageSync
import dev.opencode.mobile.domain.message.SessionMessageEngine
import javax.inject.Singleton

@Module
Expand Down Expand Up @@ -45,18 +46,27 @@ abstract class MessageModule {
fun provideMessageSync(
api: MessagesApi,
adapter: MessageDomainAdapter,
store: InMemoryMessageStore,
engine: SessionMessageEngine,
eventStream: ForegroundEventStream,
liveStoreScope: LiveStoreScope,
activeConnectionManager: dev.opencode.mobile.network.ActiveConnectionManager,
): MessageSync =
MessageSync(
listMessages = { sessionId, directory ->
runCatching { api.listMessages(sessionId, directory).map(adapter::toMessage) }
.getOrElse { throw adapter.mapError(it) }
},
store = store,
engine = engine,
eventStream = eventStream,
liveStoreScope = liveStoreScope,
connectionProfileIdProvider = {
val connection = activeConnectionManager.current()
if (connection == null) {
"local"
} else {
"${connection.baseUrl.lowercase()}|${connection.username.lowercase()}"
}
},
)
}
}
17 changes: 17 additions & 0 deletions android/app/src/main/java/dev/opencode/mobile/di/ProjectModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ import dev.opencode.mobile.domain.filesystem.FilesystemRepository
import dev.opencode.mobile.domain.project.DefaultProjectRepository
import dev.opencode.mobile.domain.project.ProjectDomainAdapter
import dev.opencode.mobile.domain.project.ProjectRepository
import dev.opencode.mobile.lifecycle.ForegroundEventLifecycleCoordinator
import dev.opencode.mobile.network.ActiveConnectionManager
import dev.opencode.mobile.network.OpencodeHttpClient
import dev.opencode.mobile.network.OpencodeSseHttpClient
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.serialization.json.Json
import javax.inject.Singleton

Expand Down Expand Up @@ -72,5 +77,17 @@ abstract class EventStreamModule {
@Provides
@Singleton
fun provideEventDomainAdapter(json: Json): EventDomainAdapter = EventDomainAdapter(json)

@Provides
@Singleton
fun provideForegroundEventLifecycleCoordinator(
foregroundEventStream: ForegroundEventStream,
activeConnectionManager: ActiveConnectionManager,
): ForegroundEventLifecycleCoordinator =
ForegroundEventLifecycleCoordinator(
foregroundEventStream = foregroundEventStream,
hasActiveConnection = { activeConnectionManager.current() != null },
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate),
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dev.opencode.mobile.domain.event

import android.util.Log
import dev.opencode.mobile.data.remote.EventsApi
import dev.opencode.mobile.domain.message.ConnectionEpoch
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
Expand Down Expand Up @@ -33,12 +34,13 @@ class DefaultForegroundEventStream
private val _connectionState = MutableStateFlow(EventStreamConnectionState.Idle)
override val connectionState: StateFlow<EventStreamConnectionState> = _connectionState.asStateFlow()

private val _events = MutableSharedFlow<OpencodeEvent>(extraBufferCapacity = 64)
private val _events = MutableSharedFlow<OpencodeEvent>(extraBufferCapacity = 4_096)
override val events: SharedFlow<OpencodeEvent> = _events.asSharedFlow()

override fun start() {
if (streamJob?.isActive == true) return
logI("foreground SSE stream starting")
ConnectionEpoch.shared.bump()
streamJob =
scope.launch {
var retryAttempt = 0
Expand Down Expand Up @@ -67,11 +69,14 @@ class DefaultForegroundEventStream
"server.connected" -> {
markStreamConnected()
retryAttempt = 0
_events.emit(event)
}
"server.heartbeat" -> Unit
else -> {
markStreamConnected()
scope.launch { _events.emit(event) }
// Emit on the read coroutine so order is preserved and
// we do not spawn one job per delta under burst.
_events.emit(event)
}
}
}
Expand Down Expand Up @@ -104,14 +109,15 @@ class DefaultForegroundEventStream
setConnectionState(EventStreamConnectionState.Idle)
}

private fun markStreamConnected() {
private suspend fun markStreamConnected() {
val shouldPublishReconnect = wasConnected && !currentStreamWasConnected && !emittedReconnectForCurrentStream
if (_connectionState.value != EventStreamConnectionState.Connected) {
setConnectionState(EventStreamConnectionState.Connected)
}
if (shouldPublishReconnect) {
logI("foreground SSE stream reconnected")
_events.tryEmit(OpencodeEvent(type = "stream.reconnected"))
ConnectionEpoch.shared.bump()
_events.emit(OpencodeEvent(type = "stream.reconnected"))
emittedReconnectForCurrentStream = true
}
currentStreamWasConnected = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ data class OpencodeEvent(
setOf(
"message.updated",
"message.part.updated",
"message.part.delta",
"message.part.removed",
"message.removed",
"session.status",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package dev.opencode.mobile.domain.message

import dev.opencode.mobile.markdown.MarkdownDocument

/**
* Phase 5 per-text-block decoration lookup.
* Keyed by session + block + content revision + streaming flag (no generation).
* Generation rejects happen in the pipeline before [put].
*/
object BlockDecorationCache {
private const val MAX_ENTRIES = 32

data class Key(
val sessionKey: String,
val blockID: String,
val textHash: Int,
val textLength: Int,
val isStreaming: Boolean,
)

private val lock = Any()
private val entries =
object : LinkedHashMap<Key, MarkdownDocument>(MAX_ENTRIES + 1, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Key, MarkdownDocument>?): Boolean =
size > MAX_ENTRIES
}

fun get(
sessionKey: String,
blockID: String,
textHash: Int,
textLength: Int,
isStreaming: Boolean,
): MarkdownDocument? =
synchronized(lock) {
entries[
Key(
sessionKey = sessionKey,
blockID = blockID,
textHash = textHash,
textLength = textLength,
isStreaming = isStreaming,
),
]
}

fun put(
sessionKey: String,
blockID: String,
textHash: Int,
textLength: Int,
isStreaming: Boolean,
document: MarkdownDocument,
) {
synchronized(lock) {
entries[
Key(
sessionKey = sessionKey,
blockID = blockID,
textHash = textHash,
textLength = textLength,
isStreaming = isStreaming,
),
] = document
}
}

fun clear() {
synchronized(lock) {
entries.clear()
}
}

/** Test / diagnostics only. */
internal fun size(): Int = synchronized(lock) { entries.size }
}
Loading