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
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package dev.opencode.mobile.data.remote

import dev.opencode.mobile.network.OpencodeHttpClient
import dev.opencode.mobile.network.applyDirectory
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.http.isSuccess
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

@Serializable
internal data class WorktreeDirectoryDto(
val directory: String,
val strategy: String? = null,
)

sealed class V1WorkspaceHttp {
data class Ok(
val body: String,
) : V1WorkspaceHttp()

data object NotFound : V1WorkspaceHttp()

data class Failed(
val statusCode: Int,
) : V1WorkspaceHttp()
}

interface WorktreeRemote {
suspend fun listV2(projectId: String): List<String>

suspend fun refreshV2(projectId: String)

suspend fun probeV1(directory: String): V1WorkspaceHttp
}

class WorktreesApi private constructor(
private val httpClient: ClientProvider,
) : WorktreeRemote {
constructor(httpClient: OpencodeHttpClient) : this(ClientProvider(httpClient::get))

internal constructor(httpClient: HttpClient) : this(ClientProvider { httpClient })

override suspend fun listV2(projectId: String): List<String> =
httpClient
.get()
.get("api/worktree") {
parameter("projectID", projectId)
}.body<List<WorktreeDirectoryDto>>()
.map { it.directory }

override suspend fun refreshV2(projectId: String) {
val response =
httpClient.get().post("api/worktree/refresh") {
contentType(ContentType.Application.Json)
setBody(buildJsonObject { put("projectID", projectId) }.toString())
}
if (!response.status.isSuccess()) {
error("worktree refresh failed with status ${response.status.value}")
}
}

override suspend fun probeV1(directory: String): V1WorkspaceHttp {
val response =
httpClient.get().get("experimental/workspace") {
applyDirectory(directory)
}
return when (val status = response.status.value) {
404 -> V1WorkspaceHttp.NotFound
in 200..299 -> V1WorkspaceHttp.Ok(response.bodyAsText())
else -> V1WorkspaceHttp.Failed(status)
}
}

private fun interface ClientProvider {
fun get(): HttpClient
}
}
16 changes: 16 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 @@ -9,6 +9,8 @@ import dev.opencode.mobile.data.remote.EventsApi
import dev.opencode.mobile.data.remote.FilesystemApi
import dev.opencode.mobile.data.remote.HealthApi
import dev.opencode.mobile.data.remote.ProjectsApi
import dev.opencode.mobile.data.remote.WorktreeRemote
import dev.opencode.mobile.data.remote.WorktreesApi
import dev.opencode.mobile.data.remote.sessionEventsApi
import dev.opencode.mobile.domain.connection.ConnectivityDeviceNetworkPath
import dev.opencode.mobile.domain.connection.DeviceNetworkPath
Expand All @@ -31,6 +33,8 @@ import dev.opencode.mobile.domain.filesystem.TextMateProjectFileHighlighter
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.domain.worktree.DefaultWorktreeRepository
import dev.opencode.mobile.domain.worktree.WorktreeRepository
import dev.opencode.mobile.network.ActiveConnectionManager
import dev.opencode.mobile.network.OpencodeHttpClient
import dev.opencode.mobile.network.OpencodeSseHttpClient
Expand All @@ -47,6 +51,14 @@ abstract class ProjectModule {
@Singleton
abstract fun bindProjectRepository(impl: DefaultProjectRepository): ProjectRepository

@Binds
@Singleton
abstract fun bindWorktreeRepository(impl: DefaultWorktreeRepository): WorktreeRepository

@Binds
@Singleton
abstract fun bindWorktreeRemote(impl: WorktreesApi): WorktreeRemote

@Binds
@Singleton
abstract fun bindFilesystemRepository(impl: DefaultFilesystemRepository): FilesystemRepository
Expand All @@ -68,6 +80,10 @@ abstract class ProjectModule {
@Singleton
fun provideProjectsApi(httpClient: OpencodeHttpClient): ProjectsApi = ProjectsApi(httpClient)

@Provides
@Singleton
fun provideWorktreesApi(httpClient: OpencodeHttpClient): WorktreesApi = WorktreesApi(httpClient)

@Provides
@Singleton
fun provideFilesystemApi(httpClient: OpencodeHttpClient): FilesystemApi = FilesystemApi(httpClient)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package dev.opencode.mobile.domain.event

import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow

Expand All @@ -13,3 +15,13 @@ interface ForegroundEventStream {

fun onReconnectWake() {}
}

/** No events. View-model tests use this when they do not pass a stream. */
object IdleForegroundEventStream : ForegroundEventStream {
override val connectionState = MutableStateFlow(EventStreamConnectionState.Idle)
override val events = MutableSharedFlow<OpencodeEvent>()

override fun start() = Unit

override suspend fun stop() = Unit
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package dev.opencode.mobile.domain.event

import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

data class OpencodeEvent(
val type: String,
Expand Down Expand Up @@ -47,3 +49,9 @@ data class OpencodeEvent(
)
}
}

fun OpencodeEvent.namedProjectId(): String? {
val properties = rawProperties ?: return null
fun string(key: String) = (properties[key] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }
return string("projectID") ?: string("projectId")
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,13 @@ interface ProjectRepository {

suspend fun getCurrentProject(directory: String? = null): Project
}

/** Session Chat tests that do not load a worktree inventory. */
object UnavailableProjectRepository : ProjectRepository {
override suspend fun probeServer() = Unit

override suspend fun listProjects(): List<Project> = emptyList()

override suspend fun getCurrentProject(directory: String?): Project =
Project(id = "", worktree = directory.orEmpty(), displayName = "")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package dev.opencode.mobile.domain.worktree

import dev.opencode.mobile.data.remote.V1WorkspaceHttp
import dev.opencode.mobile.data.remote.WorktreeRemote
import dev.opencode.mobile.domain.connection.ServerProtocol
import dev.opencode.mobile.network.ActiveConnectionManager
import kotlinx.coroutines.CancellationException
import javax.inject.Inject

class DefaultWorktreeRepository(
private val remote: WorktreeRemote,
private val protocol: suspend () -> ServerProtocol,
) : WorktreeRepository {
@Inject
constructor(
remote: WorktreeRemote,
activeConnectionManager: ActiveConnectionManager,
) : this(
remote = remote,
protocol = { activeConnectionManager.currentProtocolOrProbe() },
)

private var connectionKey: String? = null
private var v1StoppedKey: String? = null

override suspend fun load(
addedPath: String,
projectId: String?,
): WorktreeLoad =
when (protocol()) {
ServerProtocol.V2 -> loadV2(projectId)
ServerProtocol.V1 -> loadV1(addedPath)
}

override suspend fun loadRefreshed(
addedPath: String,
projectId: String?,
): WorktreeLoad {
val listed = load(addedPath, projectId)
if (listed !is WorktreeLoad.Loaded || listed.listsSessions || projectId.isNullOrBlank()) return listed
if (!refresh(projectId)) return listed
return when (val refreshed = refetch(projectId)) {
is WorktreeLoad.Loaded, is WorktreeLoad.Failed -> refreshed
WorktreeLoad.Unloaded, WorktreeLoad.Stopped -> listed
}
}

override suspend fun refresh(projectId: String): Boolean {
if (protocol() != ServerProtocol.V2 || projectId.isBlank()) return false
return try {
remote.refreshV2(projectId)
true
} catch (cancellation: CancellationException) {
throw cancellation
} catch (_: Exception) {
false
}
}

override suspend fun refetch(projectId: String): WorktreeLoad {
if (protocol() != ServerProtocol.V2) return WorktreeLoad.Unloaded
return loadV2(projectId)
}

override fun onDisconnected() {
connectionKey = null
v1StoppedKey = null
}

override fun onConnection(key: String) {
if (connectionKey != key) {
v1StoppedKey = null
connectionKey = key
}
}

private suspend fun loadV2(projectId: String?): WorktreeLoad {
if (projectId.isNullOrBlank()) return WorktreeLoad.Unloaded
return try {
WorktreeLoad.Loaded(remote.listV2(projectId), listsSessions = false)
} catch (cancellation: CancellationException) {
throw cancellation
} catch (error: Exception) {
WorktreeLoad.Failed(error)
}
}

private suspend fun loadV1(addedPath: String): WorktreeLoad {
if (v1StoppedKey != null && v1StoppedKey == connectionKey) return WorktreeLoad.Stopped
return when (val probe = runV1(addedPath)) {
is V1WorkspaceHttp.NotFound -> {
v1StoppedKey = connectionKey
WorktreeLoad.Stopped
}
is V1WorkspaceHttp.Failed ->
WorktreeLoad.Failed(IllegalStateException("workspace probe failed with status ${probe.statusCode}"))
is V1WorkspaceHttp.Ok -> {
val directories = WorkspaceDirectoryParser.parse(probe.body)
?: return WorktreeLoad.Failed(IllegalStateException("unrecognized workspace body"))
WorktreeLoad.Loaded(directories, listsSessions = true)
}
}
}

private suspend fun runV1(addedPath: String): V1WorkspaceHttp =
try {
remote.probeV1(addedPath)
} catch (cancellation: CancellationException) {
throw cancellation
} catch (_: Exception) {
V1WorkspaceHttp.Failed(-1)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package dev.opencode.mobile.domain.worktree

import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

/**
* V1 `GET /experimental/workspace` bodies. A recognized shape is an array, or an
* object whose `data` is an array, of strings or `{ "directory": "..." }`.
* Null means the body is not that shape.
*/
object WorkspaceDirectoryParser {
private val json = Json { ignoreUnknownKeys = true }

fun parse(body: String): List<String>? {
val element = runCatching { json.parseToJsonElement(body) }.getOrNull() ?: return null
val array =
when (element) {
is JsonArray -> element
is JsonObject -> element["data"] as? JsonArray ?: return null
else -> return null
}
val directories = mutableListOf<String>()
for (item in array) {
when (item) {
is JsonPrimitive -> {
if (!item.isString) return null
val value = item.content.trim()
if (value.isNotEmpty()) directories += value
}
is JsonObject -> {
when (val directory = item["directory"]) {
null, is JsonNull -> Unit
is JsonPrimitive -> {
if (!directory.isString) return null
val value = directory.contentOrNull?.trim().orEmpty()
if (value.isNotEmpty()) directories += value
}
else -> return null
}
}
else -> return null
}
}
return directories
}
}
Loading