Skip to content
Merged
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
23 changes: 20 additions & 3 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,27 @@ and quiet refresh merge stay in the Screen Model.

### message

A user, assistant, command, or tool-related item inside a session.
A user, assistant, or tool-related item inside a session.

The mobile client treats messages as the main way to understand what happened in
a session and as the vehicle for sending new prompts.
Each message has a `role` (user/assistant), a pre-computed `text` for display,
and an ordered array of `parts` that represent the content structure. A message
with no meaningful parts (empty prompt, system-only) still has a `text` fallback.

### message part

A typed content unit within a message. Parts are ordered and rendered
sequentially. For v1 the domain model defines two variants:

- **TextPart**: user prompt text or assistant response text. May carry
`isStreaming: true` while delta chunks are still arriving. Model reasoning
traces are hidden from normal chat text in v1.
- **ToolPart**: a tool call with a friendly status label such as
`"⌛ webfetch"` (pending), `"⏳ webfetch: Searching"` (running),
`"✓ webfetch"` (completed), or `"✕ weftch: error"` (error).

Server-only part types (`step-start`, `step-finish`, `agent`, `subtask`,
`snapshot`, `patch`, `compaction`, `retry`) are consumed by the adapter but do
not produce a visible domain part in v1.

### Model Selection

Expand Down
1 change: 1 addition & 0 deletions android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ dependencies {
implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.serialization.kotlinx.json)
implementation(libs.ktor.client.auth)
implementation(libs.ktor.client.logging)
implementation(libs.kotlinx.serialization.json)
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.security.crypto)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ import kotlinx.coroutines.CancellationException
class EventsApi(
private val httpClient: OpencodeSseHttpClient,
) {
suspend fun streamGlobalEvents(onDataLine: suspend (String) -> Unit) {
suspend fun streamGlobalEvents(
onHTTPResponse: suspend (Int) -> Unit = {},
onDataLine: suspend (String) -> Unit,
) {
httpClient
.get()
.prepareGet("global/event") {
accept(ContentType.Text.EventStream)
header(HttpHeaders.CacheControl, "no-cache")
}.execute { response ->
onHTTPResponse(response.status.value)
val channel = response.bodyAsChannel()
val dataBuffer = StringBuilder()
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,53 @@ data class MessageTimeDto(

@Serializable
data class MessagePartDto(
val id: String? = null,
@SerialName("sessionID") val sessionId: String? = null,
@SerialName("messageID") val messageId: String? = null,
val type: String,
val text: String? = null,
val tool: String? = null,
@SerialName("callID") val callId: String? = null,
val state: JsonObject? = null,
val snapshot: String? = null,
val reason: String? = null,
val name: String? = null,
val prompt: String? = null,
val description: String? = null,
val agent: String? = null,
val attempt: Int? = null,
val error: MessageErrorInfoDto? = null,
val time: MessagePartTimeDto? = null,
val synthetic: Boolean? = null,
val ignored: Boolean? = null,
val hash: String? = null,
val files: List<String>? = null,
val auto: Boolean? = null,
)

@Serializable
data class MessagePartTimeDto(
val start: Long? = null,
val end: Long? = null,
)

@Serializable
data class MessageToolStateDto(
val status: String,
val input: JsonObject? = null,
val raw: String? = null,
val title: String? = null,
val output: String? = null,
val error: String? = null,
val time: MessageToolTimeDto? = null,
)

@Serializable
data class MessageToolTimeDto(
val start: Long? = null,
val end: Long? = null,
val compacted: Long? = null,
val created: Long? = null,
)

@Serializable
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.opencode.mobile.domain.event

import android.util.Log
import dev.opencode.mobile.data.remote.EventsApi
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
Expand All @@ -26,6 +27,8 @@ class DefaultForegroundEventStream
private val scope = CoroutineScope(SupervisorJob())
private var streamJob: Job? = null
private var wasConnected = false
private var currentStreamWasConnected = false
private var emittedReconnectForCurrentStream = false

private val _connectionState = MutableStateFlow(EventStreamConnectionState.Idle)
override val connectionState: StateFlow<EventStreamConnectionState> = _connectionState.asStateFlow()
Expand All @@ -35,48 +38,115 @@ class DefaultForegroundEventStream

override fun start() {
if (streamJob?.isActive == true) return
logI("foreground SSE stream starting")
streamJob =
scope.launch {
var retryAttempt = 0
while (true) {
_connectionState.value =
if (wasConnected) EventStreamConnectionState.Reconnecting else EventStreamConnectionState.Connecting
currentStreamWasConnected = false
emittedReconnectForCurrentStream = false
setConnectionState(
if (wasConnected) EventStreamConnectionState.Reconnecting else EventStreamConnectionState.Connecting,
)
try {
eventsApi.streamGlobalEvents { dataLine ->
val event = eventDomainAdapter.parseEvent(dataLine) ?: return@streamGlobalEvents
eventsApi.streamGlobalEvents(
onHTTPResponse = { statusCode ->
logI("GET /global/event opened status=$statusCode")
markStreamConnected()
retryAttempt = 0
},
) { dataLine ->
val event =
eventDomainAdapter.parseEvent(dataLine)
?: run {
logW("SSE event parse failed")
return@streamGlobalEvents
}
logD("SSE event type=${event.type} session=${event.sessionId ?: "-"}")
when (event.type) {
"server.connected" -> {
_connectionState.value = EventStreamConnectionState.Connected
if (wasConnected) {
_events.tryEmit(OpencodeEvent(type = "stream.reconnected"))
}
wasConnected = true
markStreamConnected()
retryAttempt = 0
}
"server.heartbeat" -> Unit
else -> scope.launch { _events.emit(event) }
else -> {
markStreamConnected()
scope.launch { _events.emit(event) }
}
}
}
_connectionState.value = EventStreamConnectionState.Disconnected
setConnectionState(EventStreamConnectionState.Disconnected)
} catch (_: CancellationException) {
_connectionState.value = EventStreamConnectionState.Idle
setConnectionState(EventStreamConnectionState.Idle)
return@launch
} catch (_: Throwable) {
_connectionState.value =
if (wasConnected) EventStreamConnectionState.Reconnecting else EventStreamConnectionState.Disconnected
} catch (throwable: Throwable) {
logW("foreground SSE stream failed", throwable)
setConnectionState(
if (wasConnected) EventStreamConnectionState.Reconnecting else EventStreamConnectionState.Disconnected,
)
}

retryAttempt += 1
val backoffMs = (1_000L * retryAttempt).coerceAtMost(10_000L)
logD("foreground SSE retry in ${backoffMs}ms")
delay(backoffMs)
}
}
}

override fun stop() {
logI("foreground SSE stream stopping")
streamJob?.cancel()
streamJob = null
wasConnected = false
_connectionState.value = EventStreamConnectionState.Idle
currentStreamWasConnected = false
emittedReconnectForCurrentStream = false
setConnectionState(EventStreamConnectionState.Idle)
}

private 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"))
emittedReconnectForCurrentStream = true
}
currentStreamWasConnected = true
wasConnected = true
}

private fun setConnectionState(state: EventStreamConnectionState) {
if (_connectionState.value != state) {
logD("foreground SSE state ${_connectionState.value} -> $state")
}
_connectionState.value = state
}

private fun logI(message: String) {
runCatching { Log.i(TAG, message) }
}

private fun logD(message: String) {
runCatching { Log.d(TAG, message) }
}

private fun logW(
message: String,
throwable: Throwable? = null,
) {
runCatching {
if (throwable == null) {
Log.w(TAG, message)
} else {
Log.w(TAG, message, throwable)
}
}
}

private companion object {
private const val TAG = "OpencodeSse"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ class EventDomainAdapter(
val payload = envelope.payload
val type = payload?.type ?: envelope.type ?: return null
val properties = payload?.properties ?: envelope.properties ?: JsonObject(emptyMap())
return OpencodeEvent(type = type, sessionId = sessionIdFromProperties(properties))
return OpencodeEvent(
type = type,
sessionId = sessionIdFromProperties(properties),
rawProperties = properties,
)
}

private fun sessionIdFromProperties(properties: JsonObject): String? {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package dev.opencode.mobile.domain.event

import kotlinx.serialization.json.JsonObject

data class OpencodeEvent(
val type: String,
val sessionId: String? = null,
val rawProperties: JsonObject? = null,
) {
val triggersMessageRefresh: Boolean
get() =
Expand All @@ -16,7 +19,7 @@ data class OpencodeEvent(
get() =
type in STATUS_REFRESH_TYPES

private companion object {
companion object {
val MESSAGE_REFRESH_TYPES =
setOf(
"message.updated",
Expand Down
Loading