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,103 @@
package dev.opencode.mobile.data.remote

import dev.opencode.mobile.network.OpencodeHttpClient
import dev.opencode.mobile.network.applyLocationDirectory
import io.ktor.client.HttpClient
import io.ktor.client.plugins.onUpload
import io.ktor.client.plugins.timeout
import io.ktor.client.request.parameter
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.content.OutgoingContent
import io.ktor.http.contentType
import io.ktor.http.isSuccess
import io.ktor.utils.io.ByteWriteChannel
import io.ktor.utils.io.writeFully
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import java.io.File

/** `POST /api/experimental/fs/write`: raw bytes to an absolute server path (v2, experimental). */
class AttachmentUploadApi private constructor(
private val httpClient: ClientProvider,
) {
constructor(httpClient: OpencodeHttpClient) : this(ClientProvider(httpClient::get))

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

/** The raw outcome; [path] is the answer's `data.path` when the 200 body carried one. */
class Response(
val status: Int,
val path: String?,
) {
val isSuccess: Boolean get() = status in 200..299
}

suspend fun write(
serverPath: String,
file: File,
directory: String,
onProgress: (sent: Long, total: Long) -> Unit,
): Response {
val response: HttpResponse =
httpClient.get().post("api/experimental/fs/write") {
parameter("path", serverPath)
applyLocationDirectory(directory)
// Large files outlast the default REST ceiling; a stalled socket still fails.
timeout {
requestTimeoutMillis = UPLOAD_TIMEOUT_MS
socketTimeoutMillis = SOCKET_TIMEOUT_MS
}
onUpload { sent, total ->
val expected = total ?: file.length()
if (expected > 0) onProgress(sent, expected)
}
contentType(ContentType.Application.OctetStream)
setBody(FileContent(file))
}
val text = runCatching { response.bodyAsText() }.getOrDefault("")
return Response(
status = response.status.value,
path = if (response.status.isSuccess()) resolvedPath(text) else null,
)
}

private fun resolvedPath(body: String): String? =
runCatching {
val data = (json.parseToJsonElement(body) as? JsonObject)?.get("data") as? JsonObject
(data?.get("path") as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }
}.getOrNull()

private class FileContent(
private val file: File,
) : OutgoingContent.WriteChannelContent() {
override val contentType: ContentType = ContentType.Application.OctetStream
override val contentLength: Long = file.length()

override suspend fun writeTo(channel: ByteWriteChannel) {
file.inputStream().use { input ->
val buffer = ByteArray(16 * 1024)
while (true) {
val read = input.read(buffer)
if (read <= 0) break
channel.writeFully(buffer, 0, read)
}
}
}
}

private fun interface ClientProvider {
fun get(): HttpClient
}

private companion object {
val json = Json { ignoreUnknownKeys = true }
const val UPLOAD_TIMEOUT_MS = 30L * 60L * 1_000L
val SOCKET_TIMEOUT_MS = 60_000L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,27 @@ class FilesystemApi private constructor(
)
}

/**
* v2 `GET /api/fs/read/<path>`, [relativePath] under [location]. The route is confined to its
* location, so a file outside the project (an upload under the server's tmp directory) is
* read by locating at a directory that contains it. Null on any failure or past [maxBytes].
*/
suspend fun readServerFileV2(
location: String,
relativePath: String,
maxBytes: Int,
): ByteArray? =
httpClient
.get()
.prepareGet {
url { appendEncodedPathSegments(v2ReadPathSegments(relativePath)) }
applyLocationDirectory(location)
}.execute { response ->
response.requireSuccess()
val read = response.bodyAsChannel().readCapped(maxBytes)
read.bytes.takeUnless { read.exceeded }
}

private fun v2ReadPathSegments(relativePath: String): List<String> =
listOf("api", "fs", "read") + encodeRelativePathSegments(relativePath)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ data class MessagePartDto(
val mime: String? = null,
val url: String? = null,
val filename: String? = null,
/** Absolute server path of a file the client uploaded (from a v2 prompt's `metadata.attachments`). */
val serverPath: String? = null,
val system: String? = null,
val tool: String? = null,
val source: JsonObject? = null,
Expand Down Expand Up @@ -198,6 +200,8 @@ data class V2PromptRequestDto(
val agents: List<V2PromptAgentDto>? = null,
val skills: List<V2PromptSkillDto>? = null,
val delivery: String,
/** `{attachments: [{name, mime, path}]}` for files uploaded to the server instead of sent inline. */
val metadata: JsonObject? = null,
/** Project-file mentions. Written into `files` as literal URIs, after device attachments. */
@Transient val fileMentions: List<V2PromptFileMentionDto>? = null,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,5 @@ data class V2InboxItemDto(
@Serializable
data class V2InboxUserPayloadDto(
val text: String = "",
val metadata: JsonObject? = null,
)
18 changes: 18 additions & 0 deletions android/app/src/main/java/dev/opencode/mobile/di/MessageModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@ import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.opencode.mobile.data.remote.AttachmentUploadApi
import dev.opencode.mobile.domain.event.ForegroundEventStream
import dev.opencode.mobile.domain.live.LiveStoreScope
import dev.opencode.mobile.domain.message.AttachmentUploadService
import dev.opencode.mobile.domain.message.DefaultAttachmentUploadService
import dev.opencode.mobile.domain.message.DefaultMessageRepository
import dev.opencode.mobile.domain.message.DefaultServerFilePreviews
import dev.opencode.mobile.domain.message.DisplayMessagePipeline
import dev.opencode.mobile.domain.message.MessageContentPreparer
import dev.opencode.mobile.domain.message.MessageDomainAdapter
Expand All @@ -17,9 +21,11 @@ import dev.opencode.mobile.domain.message.MessageRemote
import dev.opencode.mobile.domain.message.MessageRepository
import dev.opencode.mobile.domain.message.MessageSync
import dev.opencode.mobile.domain.message.ProtocolSelectedMessageRemote
import dev.opencode.mobile.domain.message.ServerFilePreviews
import dev.opencode.mobile.domain.message.SessionMessageEngine
import dev.opencode.mobile.domain.sessioncache.SessionCache
import dev.opencode.mobile.domain.sync.SyncCoordinator
import dev.opencode.mobile.network.OpencodeHttpClient
import javax.inject.Singleton

@Module
Expand All @@ -33,7 +39,19 @@ abstract class MessageModule {
@Singleton
abstract fun bindMessageRemote(impl: ProtocolSelectedMessageRemote): MessageRemote

@Binds
@Singleton
abstract fun bindServerFilePreviews(impl: DefaultServerFilePreviews): ServerFilePreviews

@Binds
@Singleton
abstract fun bindAttachmentUploadService(impl: DefaultAttachmentUploadService): AttachmentUploadService

companion object {
@Provides
@Singleton
fun provideAttachmentUploadApi(httpClient: OpencodeHttpClient): AttachmentUploadApi = AttachmentUploadApi(httpClient)

@Provides
@Singleton
fun provideMessageDomainAdapter(): MessageDomainAdapter = MessageDomainAdapter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import dev.opencode.mobile.data.remote.dto.V2PromptSkillDto
import dev.opencode.mobile.data.remote.dto.V2RunCommandRequestDto
import dev.opencode.mobile.data.remote.dto.V2SkillDto
import dev.opencode.mobile.data.remote.dto.V2SwitchModelRequestDto
import dev.opencode.mobile.domain.message.UploadedAttachments
import dev.opencode.mobile.domain.message.inlineAttachments
import io.ktor.client.plugins.ResponseException
import io.ktor.serialization.JsonConvertException

Expand Down Expand Up @@ -101,9 +103,14 @@ class CommandDomainAdapter {
fun toV2RunRequest(options: CommandRunOptions): V2RunCommandRequestDto =
V2RunCommandRequestDto(
name = options.command,
text = options.arguments,
text =
UploadedAttachments.promptText(
options.arguments,
options.attachments.mapNotNull { it.uploadedServerPath },
),
files =
options.attachments
.inlineAttachments()
.map { attachment ->
V2PromptFileDto(
uri = attachment.dataUrl,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package dev.opencode.mobile.domain.command
import dev.opencode.mobile.data.remote.CommandsApi
import dev.opencode.mobile.data.remote.MessagesApi
import dev.opencode.mobile.domain.connection.ServerProtocol
import dev.opencode.mobile.domain.message.inlineAttachments
import dev.opencode.mobile.network.ActiveConnectionManager
import javax.inject.Inject
import javax.inject.Singleton
Expand Down Expand Up @@ -42,7 +43,7 @@ class DefaultCommandRepository
adapter.toV2SwitchModelRequest(options)?.let { model ->
messagesApi.switchSessionModel(sessionId, model, directory)
}
api.runCommandV2(sessionId, adapter.toV2RunRequest(options), options.attachments)
api.runCommandV2(sessionId, adapter.toV2RunRequest(options), options.attachments.inlineAttachments())
} else {
api.runCommand(sessionId, adapter.toRunRequest(options), directory, options.attachments)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.http.isSuccess
import kotlinx.serialization.json.Json
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.json.JsonObject

class ConnectionProbeService(
Expand Down Expand Up @@ -54,12 +55,36 @@ class ConnectionProbeService(
message = response.status.description,
)
}
return V2ServerContract.features(response.body<JsonObject>())
val document = response.body<JsonObject>()
val features = V2ServerContract.features(document)
if (!V2ServerContract.declaresAttachmentUpload(document)) return features
// The route alone is not enough: the upload path is built under the server's tmp directory.
val tmp =
try {
fetchTmpDirectory(client)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Throwable) {
return features.copy(tmpDirectoryUnread = true)
}
return features.copy(attachmentUploadTmp = tmp)
} finally {
client.close()
}
}

/** Null when `/api/info` answers without `paths.tmp`; throws when it cannot be read. */
private suspend fun fetchTmpDirectory(client: HttpClient): String? {
val response: HttpResponse = client.get(V2ServerContract.INFO_PATH)
if (!response.status.isSuccess()) {
throw ServerProbeError.Http(
statusCode = response.status.value,
message = response.status.description,
)
}
return V2ServerContract.tmpDirectory(response.body<JsonObject>())
}

private suspend fun HttpClient.fetchHealth(path: String): HealthDto {
val response: HttpResponse = get(path)
if (!response.status.isSuccess()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ data class ServerCapabilities(
* without adding to it (v2 releases that declare it). v1 has no equivalent.
*/
val supportsSideQuestion: Boolean = false,
/** Attachments stream to the server (`POST /api/experimental/fs/write` plus `paths.tmp`, v2). */
val supportsAttachmentUpload: Boolean = false,
) {
companion object {
fun forProtocol(
Expand All @@ -65,6 +67,7 @@ data class ServerCapabilities(
supportsSessionViewed = true,
supportsSessionMove = true,
supportsSideQuestion = v2Features.sessionGenerate,
supportsAttachmentUpload = v2Features.attachmentUpload,
)
}
}
Expand Down
Loading
Loading